Mediabibliotheek: module Media, beheerscherm, prullenbak en opruiming, Hero via de bibliotheek #22
@@ -15,6 +15,11 @@ on:
|
||||
description: 'Deploy ASF test (Andrea Slop Fotografie)'
|
||||
type: boolean
|
||||
default: false
|
||||
media_library_copy:
|
||||
description: 'Media library copy on the TEST deploys (Media__Library__CopyOnStartup in shared/env): unchanged, on or off'
|
||||
type: choice
|
||||
options: [unchanged, 'on', 'off']
|
||||
default: unchanged
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
push:
|
||||
@@ -555,6 +560,7 @@ jobs:
|
||||
service_name: ${{ vars.SERVICE_NAME_TEST }}
|
||||
health_check_url: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||
run_db_backup: false
|
||||
media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }}
|
||||
|
||||
# Production deploy ONLY on an explicit workflow_dispatch run with deploy_sls_production checked, and
|
||||
# only when that run is on a release/* branch (same rule as ASF) — never reachable from a plain push
|
||||
@@ -682,6 +688,7 @@ jobs:
|
||||
service_name: ${{ vars.SERVICE_NAME_ASF_TEST }}
|
||||
health_check_url: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
|
||||
run_db_backup: false
|
||||
media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }}
|
||||
|
||||
# --- Smoke tests of the deployed compositions (anonymous requests, see scripts/smoke-site.sh) ---
|
||||
# The CI tests the master CMS; this is the check that the composition of each site that was just deployed to test
|
||||
|
||||
@@ -37,6 +37,11 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: scp
|
||||
media_library_copy:
|
||||
description: 'unchanged | on | off: sets Media__Library__CopyOnStartup in shared/env before the restart. TEST only, never production.'
|
||||
required: false
|
||||
type: string
|
||||
default: unchanged
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
@@ -211,6 +216,37 @@ jobs:
|
||||
ln -sf \"../../shared/modules/\$name\" \"$RELEASE_DIR/\$name\"; \
|
||||
done"
|
||||
|
||||
# The media library copy switch (migration plan of the media library, decision 13): the application reads
|
||||
# Media__Library__CopyOnStartup from the host environment file shared/env (D-16). The deploy account can edit that file,
|
||||
# nobody else needs a shell on the host. Only this ONE key is touched (nothing else of the file is read or printed, the
|
||||
# file holds secrets), only on a test environment, and only with a value that is exactly on, off or unchanged.
|
||||
# `on` makes the next start copy the photos into the library's tables and verify the copy (log line
|
||||
# "Media library copy verified: N photos and M uses"); `off` removes the key again (the default is off).
|
||||
- name: Set the media library copy switch (test only)
|
||||
if: inputs.media_library_copy != 'unchanged'
|
||||
env:
|
||||
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||
SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||
run: |
|
||||
MODE="${{ inputs.media_library_copy }}"
|
||||
if [ "${{ inputs.environment }}" != "test" ]; then
|
||||
echo "The media library copy switch is for the test environment only (environment: ${{ inputs.environment }})." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$MODE" != "on" ] && [ "$MODE" != "off" ]; then
|
||||
echo "media_library_copy must be unchanged, on or off (got: $MODE)." >&2
|
||||
exit 1
|
||||
fi
|
||||
ENV_FILE="${{ inputs.deploy_path }}/shared/env"
|
||||
if [ "$MODE" = "on" ]; then
|
||||
rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE && echo 'Media__Library__CopyOnStartup=true' >> $ENV_FILE"
|
||||
else
|
||||
rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE"
|
||||
fi
|
||||
echo "Media__Library__CopyOnStartup is now: $(rssh "grep '^Media__Library__CopyOnStartup=' $ENV_FILE || echo '(not set = off)'")"
|
||||
|
||||
# Atomic release switch (FR-06, D-27): `ln -sfn` replaces the `current` symlink target in a
|
||||
# single filesystem operation, so there is no moment where `current` points at a half-written
|
||||
# directory. The process is then restarted so it picks up the new assemblies — a running .NET
|
||||
@@ -227,6 +263,20 @@ jobs:
|
||||
"ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \
|
||||
systemctl --user restart ${{ inputs.service_name }}"
|
||||
|
||||
# After a restart with the copy on, show the verification line of the copy in this run's log (the journal of the user
|
||||
# service), so nobody needs a shell on the host to see "Media library copy verified: N photos and M uses".
|
||||
- name: Report the media library copy (test only)
|
||||
if: inputs.media_library_copy == 'on'
|
||||
env:
|
||||
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||
SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||
run: |
|
||||
sleep 20
|
||||
rssh "journalctl --user -u ${{ inputs.service_name }} --since '-10 min' --no-pager 2>/dev/null | grep -E 'Media library copy|media library copy' | tail -5 || true"
|
||||
echo "Look for 'Media library copy verified: N photos and M uses'. An error line means the copy was rolled back and nothing was copied."
|
||||
|
||||
# Verifies the restart actually produced a healthy process before this run is allowed to
|
||||
# report success. Retries absorb process-startup time, which is about 10 seconds normally but
|
||||
# 30 seconds or more when the host is busy (a migration step, two services restarting at once
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
"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.Media\\SlpModularCms.Modules.Media.csproj",
|
||||
"src\\SlpModularCms.Modules.Media.Tests\\SlpModularCms.Modules.Media.Tests.csproj",
|
||||
"src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj",
|
||||
"src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj"
|
||||
]
|
||||
|
||||
@@ -50,6 +50,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Hero"
|
||||
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
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Media", "src\SlpModularCms.Modules.Media\SlpModularCms.Modules.Media.csproj", "{729ABD96-ADEB-4352-8030-2F6074B977F0}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Media.Tests", "src\SlpModularCms.Modules.Media.Tests\SlpModularCms.Modules.Media.Tests.csproj", "{E697D4E1-FA8D-468C-BC31-81520715E246}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -300,6 +306,30 @@ Global
|
||||
{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
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x64.Build.0 = Release|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -327,5 +357,7 @@ Global
|
||||
{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}
|
||||
{729ABD96-ADEB-4352-8030-2F6074B977F0} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
||||
{E697D4E1-FA8D-468C-BC31-81520715E246} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -46,3 +46,7 @@ Kept while Bryan was away (2026-11-16): no questions to him, a likely assumption
|
||||
| 20 | ASF production hosting (write access, back-up) | Unchanged: Bryan tests with ASF later. | Open. |
|
||||
| HEIC | iPhone HEIC upload | Still to be tested by Bryan with a real iPhone file (the build cannot write HEIC; only the library self-test ran). | Open. |
|
||||
| other | Assumptions 2, 3, 6, 7, 9, 14, 17, 18, 20, 22 to 30 | Stay as documented. | None. |
|
||||
|
||||
## Change of 2026-11-17: a new crop applies at once
|
||||
|
||||
Assumption 1 above (a changed focus only takes effect when the hero is saved) is **replaced by Bryan's later wish**: a new crop must not need another click on Save. The focus dialog now sends the crop at once and the new variants are cut in the background; see assumption 38 of `features/media-library/assumptions-and-open-questions.md`.
|
||||
|
||||
@@ -4,27 +4,74 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
|
||||
|
||||
| # | Question | Assumption made | If Bryan chooses differently | Where |
|
||||
|---|---|---|---|---|
|
||||
| 1 | Which **uses** (places and ratios) exist? | Hero `wide` (3:2) and `tall` (2:3), ASF shoot-page **mosaic** tiles (a small fixed set of ratios per page, to be listed by the ASF session), **masonry** (natural ratio, no crop), **thumb** (library thumbnails, 1:1 or natural). A use is `(module, place, ratio set)`. | Other ratios only add rows to the use definitions; a free-form ratio per tile would need a ratio editor and more variants per photo. | Application design section 4 (`MediaUseDefinition`) |
|
||||
| 2 | **Several formats/variants per photo**: who decides the set? | The **use** decides the ratios and widths (as `VariantPlanner` does for Hero); the library never cuts a fixed set per photo. Formats stay WebP and AVIF as today. | A fixed set per photo costs more disk and CPU on the Pi and cuts variants nobody uses. | `VariantPlanner`, application design section 4 |
|
||||
| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. | Switch it off behind a setting (`Media:AutoCleanupUnattached`, default `true` until the library screen exists, then default `false`), so nothing is lost silently once the library can show and delete photos. Retired-file removal (after a replaced set) stays: that is housekeeping of generated files, not a person's photos. | Keep it on until phase C; or switch off now (risk: unused uploads pile up with no screen to remove them). | `HeroMediaCleanup`, `MediaOptions` |
|
||||
| 4 | **Rights per module**: who may see, use and delete which photos? | One shared library for Owner and Administrator (like Hero and Offerings). No per-module visibility yet. | Per-module visibility needs an owner field on a photo and a filter; the contract has room for it (`ModuleKey` on a use). | `[Authorize(Policy = "AdminOnly")]`, `MediaUse.Module` |
|
||||
| 5 | **Public addresses**: per module (`/media/<module>/...`) or a shared path? | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` |
|
||||
| 6 | **Usage register**: do modules report, or does the library keep it centrally? | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` |
|
||||
| 7 | **What counts as "unused"** in the clean-up? | A photo is unused when **no provider** reports a use. A photo used only by an inactive or unpublished slide still counts as used (it is in a slide). | Treating an inactive slide as unused would delete photos a person may want to switch on again; stricter would be safer than looser. | `MediaUsageService` |
|
||||
| 8 | **Clean-up default period** and slider range. | Default 7 days, slider 1 to 365 days, step 1; "Only unused photos" on. The period is measured from the upload date. | Measured from last use, or another range: a one-line change in the filter. | Clean-up component, `CleanupSelection` |
|
||||
| 9 | **Storage limit and warning**. | Limit = existing `Media:MaxTotalBytes` (2 GB, decided by Bryan, Hero assumption 12). Warning at 80 percent (amber) and at 100 percent (red, uploads refused with a clear message). Used bytes = originals plus all variants, cached 60 s. | Another threshold or limit: configuration only. | `MediaOptions`, `MediaStorageUsage` |
|
||||
| 10 | **Delete of a photo that is in use**. | Not possible from Clean-up (those rows are not selectable); possible from the library after a second confirmation that names the uses; the module detaches it first (Hero: the slide loses its image and is unpublished until a new one is chosen, as today). | Block deleting in-use photos completely: the extra confirmation path is removed. | `IMediaUsageProvider.DetachAsync`, library screen |
|
||||
| 11 | **Shared upload service**: does Hero's upload move into the library? | In phase A Hero keeps its own upload endpoint; the library also lists those photos. In phase B both call one upload service in Core. | Moving Hero upload earlier gives a single path sooner but touches Hero before the data model exists. | `HeroImageService`, `MediaUploadGuard` |
|
||||
| 12 | **Trash delay** (deleted photos recoverable for a while)? | No trash in phase A: the confirmation naming the count is the safety. A 7-day trash can be added in phase B (a `DeletedAt` and the existing retired-file mechanism). | Trash from the start: reuse `HeroRetiredFile` logic generalised in Core; about 1 day extra. | `HeroRetiredFile`, application design section 5 |
|
||||
| 13 | **Migration of existing `HeroImages`** (phase C). | Expand then contract: new `MediaAsset` and `MediaUse` tables are filled from `HeroImages` and `HeroSlides` with the **same ids, hashes and set hashes**; Hero reads the library; old columns are dropped in a later release. Needs a back-up and alignment: **not built**. | A one-step move is smaller but cannot be rolled back; or no migration at all and the library keeps reading through Hero (the provider approach) until the gallery module needs own tables. | Requirements section 9, application design section 6 |
|
||||
| 14 | **Crop per use**: data per use or per photo? | A use owns its crop (focus x, y and zoom per ratio); the photo owns the default focus new uses start from. The set hash of a use is `SetHash(originalSha256, crops of that use)` exactly as today, so existing Hero addresses are unchanged. | Crop per photo only (today's model) cannot serve a mosaic with several tiles of the same photo. | `MediaPaths.SetHash`, `MediaUse` |
|
||||
| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component |
|
||||
| 16 | **Deleting files from the store** when a photo is deleted. | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` |
|
||||
| 1 | Which **uses** (places and ratios) exist? **[Confirmed by Bryan "as designed", 2026-11-17]** | Hero `wide` (3:2) and `tall` (2:3), ASF shoot-page **mosaic** tiles (a small fixed set of ratios per page, to be listed by the ASF session), **masonry** (natural ratio, no crop), **thumb** (library thumbnails, 1:1 or natural). A use is `(module, place, ratio set)`. | Other ratios only add rows to the use definitions; a free-form ratio per tile would need a ratio editor and more variants per photo. | Application design section 4 (`MediaUseDefinition`) |
|
||||
| 2 | **Several formats/variants per photo**: who decides the set? **[Confirmed by Bryan "as designed", 2026-11-17]** | The **use** decides the ratios and widths (as `VariantPlanner` does for Hero); the library never cuts a fixed set per photo. Formats stay WebP and AVIF as today. | A fixed set per photo costs more disk and CPU on the Pi and cuts variants nobody uses. | `VariantPlanner`, application design section 4 |
|
||||
| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | **Built (2026-11-17, safe: default unchanged)**: the setting `Media:AutoCleanupUnattached` exists, default `true` (today's behaviour); set `Media__AutoCleanupUnattached=false` per host to keep every upload. Plan: switch it off (default `false`) once the library screen and delete are accepted by Bryan. Switch it off behind a setting (`Media:AutoCleanupUnattached`, default `true` until the library screen exists, then default `false`), so nothing is lost silently once the library can show and delete photos. Retired-file removal (after a replaced set) stays: that is housekeeping of generated files, not a person's photos. | Keep it on until phase C; or switch off now (risk: unused uploads pile up with no screen to remove them). | `HeroMediaCleanup`, `MediaOptions` |
|
||||
| 4 | **Rights per module**: who may see, use and delete which photos? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | One shared library for Owner and Administrator (like Hero and Offerings). No per-module visibility yet. | Per-module visibility needs an owner field on a photo and a filter; the contract has room for it (`ModuleKey` on a use). | `[Authorize(Policy = "AdminOnly")]`, `MediaUse.Module` |
|
||||
| 5 | **Public addresses**: per module (`/media/<module>/...`) or a shared path? **[Confirmed by Bryan "as designed", 2026-11-17]** | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` |
|
||||
| 6 | **Usage register**: do modules report, or does the library keep it centrally? **[Confirmed by Bryan "as designed", 2026-11-17]** | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` |
|
||||
| 7 | **What counts as "unused"** in the clean-up? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | A photo is unused when **no provider** reports a use. A photo used only by an inactive or unpublished slide still counts as used (it is in a slide). | Treating an inactive slide as unused would delete photos a person may want to switch on again; stricter would be safer than looser. | `MediaUsageService` |
|
||||
| 8 | **Clean-up default period** and slider range. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Default 7 days, slider 1 to 365 days, step 1; "Only unused photos" on. The period is measured from the upload date. | Measured from last use, or another range: a one-line change in the filter. | Clean-up component, `CleanupSelection` |
|
||||
| 9 | **Storage limit and warning**. **[Confirmed by Bryan "as designed", 2026-11-17]** | Limit = existing `Media:MaxTotalBytes` (2 GB, decided by Bryan, Hero assumption 12). Warning at 80 percent (amber) and at 100 percent (red, uploads refused with a clear message). Used bytes = originals plus all variants, cached 60 s. | Another threshold or limit: configuration only. | `MediaOptions`, `MediaStorageUsage` |
|
||||
| 10 | **Delete of a photo that is in use**. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Not possible from Clean-up (those rows are not selectable); possible from the library after a second confirmation that names the uses; the module detaches it first (Hero: the slide loses its image and is unpublished until a new one is chosen, as today). | Block deleting in-use photos completely: the extra confirmation path is removed. | `IMediaUsageProvider.DetachAsync`, library screen |
|
||||
| 11 | **Shared upload service**: does Hero's upload move into the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | In phase A Hero keeps its own upload endpoint; the library also lists those photos. In phase B both call one upload service in Core. | Moving Hero upload earlier gives a single path sooner but touches Hero before the data model exists. | `HeroImageService`, `MediaUploadGuard` |
|
||||
| 12 | **Trash delay** (deleted photos recoverable for a while)? **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | No trash in phase A: the confirmation naming the count is the safety. A 7-day trash can be added in phase B (a `DeletedAt` and the existing retired-file mechanism). | Trash from the start: reuse `HeroRetiredFile` logic generalised in Core; about 1 day extra. | `HeroRetiredFile`, application design section 5 |
|
||||
| 13 | **Migration of existing `HeroImages`** (phase C). **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Expand then contract: new `MediaAsset` and `MediaUse` tables are filled from `HeroImages` and `HeroSlides` with the **same ids, hashes and set hashes**; Hero reads the library; old columns are dropped in a later release. Needs a back-up and alignment: **not built**. | A one-step move is smaller but cannot be rolled back; or no migration at all and the library keeps reading through Hero (the provider approach) until the gallery module needs own tables. | Requirements section 9, application design section 6 |
|
||||
| 14 | **Crop per use**: data per use or per photo? **[Confirmed by Bryan "as designed", 2026-11-17]** | A use owns its crop (focus x, y and zoom per ratio); the photo owns the default focus new uses start from. The set hash of a use is `SetHash(originalSha256, crops of that use)` exactly as today, so existing Hero addresses are unchanged. | Crop per photo only (today's model) cannot serve a mosaic with several tiles of the same photo. | `MediaPaths.SetHash`, `MediaUse` |
|
||||
| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? **[Confirmed by Bryan "as designed", 2026-11-17]** | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component |
|
||||
| 16 | **Deleting files from the store** when a photo is deleted. **[Confirmed by Bryan "as designed", 2026-11-17]** | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` |
|
||||
| 17 | **Language of the screen**: nl and en like the rest of the admin. | Yes, `media.*` keys in both files; terms: "Mediabibliotheek", "Opruimen", "Alleen ongebruikte foto's". | Dutch only: remove one file. | `frontend/src/i18n/locales` |
|
||||
| 18 | **Phase A built (2026-11-17, on assumptions)**: what is in the first step? | Read-only only: the usage contract (`IMediaUsageProvider`, `MediaLibraryService`, pure `CleanupSelection`), the Hero provider and the selection components in the frontend (`PhotoSelectionList`, `BulkActionBar`, selection rules). **No endpoint, no screen, no delete, no migration, no address change yet.** | Wire the screen and endpoints next (list, storage, clean-up preview) and then delete (needs a Hero delete path and Bryan's check of assumptions 3, 7 and 10). | `Core/Media/Library`, `Modules.Hero/Services/HeroMediaUsageProvider.cs`, `frontend/src/features/media` |
|
||||
| 19 | The **position** of a slide in "Hero, slide 3". | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` |
|
||||
| 20 | The **thumbnail** of a Hero photo in the library. | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` |
|
||||
| 21 | A **name** for a photo. | Photos have no file name today (`HeroImage` does not store it), so the library shows a neutral label (date and size); a name field comes with the library's own tables (phase B). | Store the original file name at upload now (a small Hero migration, additive). | `PhotoItem.name`, phase B |
|
||||
| 19 | The **position** of a slide in "Hero, slide 3". **[Confirmed by Bryan "as designed", 2026-11-17]** | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` |
|
||||
| 20 | The **thumbnail** of a Hero photo in the library. **[Confirmed by Bryan "as designed", 2026-11-17]** | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` |
|
||||
| 21 | A **name** for a photo. **[Decided by Bryan, 2026-11-17, second round: see "Decisions of the second round"]** | Photos have no file name today (`HeroImage` does not store it), so the library shows a neutral label (date and size); a name field comes with the library's own tables (phase B). | Store the original file name at upload now (a small Hero migration, additive). | `PhotoItem.name`, phase B |
|
||||
| 22 | **Select all** and ranges with photos that cannot be selected (in use during a clean-up). | They are skipped by "select all" and by shift-ranges; the header box shows "some" when only part is selected. | Include them but refuse at confirmation. | `PhotoSelectionList`, `selection.ts` |
|
||||
| 23 | Where does Hero **list all photos** (performance)? | In memory, newest first, as the rest of the Hero repository does (a few dozen photos; the MySQL provider has limits with Guid lists). Paging comes with the screen when the count grows. | Server-side paging by `CreatedAt` (needs an index). | `HeroRepository.GetAllImagesReadOnlyAsync` |
|
||||
| 24 | **Tile ratios of the ASF mosaic** (assumption 1). | Asked of the ASF session through SLS-Main (2026-11-17); until then the design only names "tiles with a fixed set of ratios per page". | Each answer only adds use definitions. | Application design section 4 |
|
||||
| 24 | **Tile ratios of the ASF mosaic** (assumption 1). | **Answered by the ASF session (2026-11-17, from its code)**: the mosaic shows at most 4 tiles per shoot page, from 2 photos up (layouts for 2, 3, 4). The tile shape is fixed per page by the photo count and order, not chosen per photo: **large** (photo 1) 2x2, desktop about 1:1 (max about 656x632), phone 4:3; **wide** (photo 2 with 3 or 4 photos) 2x1, desktop about 2.2:1 (max about 656x300), phone 3:2; **small** (photos 3 and 4 with 4 photos) 1x1, about 1.04:1 (max about 312x300), phone 1:1. With 2 photos: two large side by side. All object-fit cover (a crop). Widths: large and wide up to about 656 px, small about 312 px; phone half width about 175-300, full width about 350-600; retina variants 480, 640, 960, 1280. **Masonry** (portfolio): natural ratio only, no crop (rounding below half a row of 1/40 of the column width); 1, 2 or 3 columns, column width up to about 427 px; thumb now 800 px wide with the height following the ratio, variants about 480 and 800; the lightbox uses a separate `full`. Used in the design as uses `mosaic-large`, `mosaic-wide`, `mosaic-small` (each with a focus point and a desktop and phone shape) and `masonry` (no crop). | Each answer only adds use definitions. A ratio per photo (not per tile shape) would need a ratio editor. | Application design section 4 |
|
||||
| 25 | **Use definitions in code** (built 2026-11-17, pure data, nothing consumes them yet). | `MediaUseDefinition` (ratios with widths, or natural) and `GalleryUses` for the ASF needs: `mosaic-large` (`tilelarge` 1:1, `tilelargem` 4:3), `mosaic-wide` (`tilewide` 11:5, `tilewidem` 3:2), `mosaic-small` (`tilesmall` 26:25, `tilesmallm` 1:1), `masonry` (`natural`, no crop). Ratio names are letters only (2 to 10) to fit the address allow-list, so a phone shape is a name with an `m` suffix. Widths: large and wide 480, 640, 960, 1280 (retina set from the ASF answer); small 312, 480, 640; masonry 480 and 800. The set hash uses the shared `MediaPaths.SetHash` formula (a test shows it equals the Hero's). Hero's own `wide` (3:2) and `tall` (4:5, not the 2:3 the first design sketch said) stay as built in `VariantPlanner`. | Other widths or ratio values change only the definitions; the ASF `full` (lightbox) variant is not defined yet (it is the full-frame preview ratio). | `Core/Media/Library/MediaUseDefinition.cs` |
|
||||
| 26 | **Choose or upload everywhere (ML-17)**: how does the Hero upload relate to the library? **[Confirmed by Bryan "as designed", 2026-11-17]** | Now the Hero keeps its own upload and table; its photos are already in the library list through the provider. When the library owns uploads (phase B) every upload creates exactly one library record (same file = same record by hash). The Hero switches to the shared picker with the phase C migration. Until then the Hero upload flow does not change. | Moving the Hero to the picker earlier (before phase B) would give a single upload path sooner but touches the Hero flow and needs the data model first. | Application design section 10 |
|
||||
| 27 | **Scope of the shared picker**: single choice or several, and what does it include? **[Confirmed by Bryan "as designed", 2026-11-17]** | One photo per picker (single choice, radio group). It includes the library photos and one upload button (one file at a time); the Hero's multi-file upload and drag and drop stay on the Hero screen. The picker is pure: the module passes the list and the upload callback. | Several photos at once or drag and drop in the picker: a larger component, added when a module needs it (the gallery will probably need multiple). | `features/media/components/ImagePicker.tsx` |
|
||||
| 28 | **Uploaded photo not ready yet** in the picker. **[Confirmed by Bryan "as designed", 2026-11-17]** | It is chosen at once but shows "no preview" until the background renderer has cut its set; an image without a set is not published (as in the Hero today). | Block choosing until it is ready: simpler to explain, slower to work with. | `ImagePicker`, `HeroRenderService` |
|
||||
|
||||
## Decisions of the second round (Bryan, 2026-11-17, via SLP Software - SLS - Main)
|
||||
|
||||
| # | Decision | Consequence in design and code |
|
||||
|---|---|---|
|
||||
| 3 | The automatic removal of unused Hero uploads is switched off once Bryan has approved the screen (PR #22). | `Media:AutoCleanupUnattached` keeps its default `true`; it becomes `false` only at or after his approval of PR #22. |
|
||||
| 4 | One shared library for Owner and Administrator, no rights per module. | As designed (`AdminOnly`). |
|
||||
| 7 | A photo used only by a switched-off slide counts as **used**. | As designed (`HeroMediaUsageProvider` reports it as a use with `Active = false`). |
|
||||
| 8 | The clean-up period counts from the **last use**, not the upload date. | Each photo gets "unused since" (the moment it was last detached from a slide; the upload date when it was never used). Details in assumption 29. |
|
||||
| 10 | Deleting a photo that is in use is possible after a **second confirmation that names the places**. | Delete refuses an in-use photo unless the request says it was confirmed twice; the module detaches it (Hero: the slides using it are removed). Assumption 30. |
|
||||
| 12 | There is a **trash**: recoverable for 7 days (`DeletedAt` plus the existing retired-file mechanism). | Delete means "to the trash"; the files go 7 days later. A trash view lists them with Restore. Assumption 31. |
|
||||
| 13 | The migration of `HeroImages` to the library's own tables may be built next (expand then contract, same ids, hashes and addresses). | Conditions: document a back-up and rollback plan first; roll out only to TEST, never production; tell SLS-Main before deploying to test. Assumption 32. |
|
||||
| 21 | The original file name is stored at every upload from now on (additive); existing photos keep the neutral label. | `OriginalFileName` on the Hero image (additive migration); the library shows it. |
|
||||
|
||||
### New assumptions from these decisions
|
||||
|
||||
| # | Question | Assumption made | If Bryan chooses differently | Where |
|
||||
|---|---|---|---|---|
|
||||
| 29 | **Reference date of the clean-up** (decision 8). | For a photo that is not in use: the moment it was last detached from a slide (`LastUsedAt`), else its upload date. For a photo that is in use right now (clean-up with "Only unused photos" off): its upload date, since "last used" is "now" and nothing would ever be old enough. The period slider keeps its range (1 to 365 days, default 7). | "Last used" for a photo in use = the last save that kept it, so with the filter off only photos left alone for the whole period are offered. | `HeroImage.LastUsedAt`, `HeroService.SaveAsync`, `CleanupSelection` |
|
||||
| 30 | **Detaching a used photo when it is deleted** (decision 10). | In the Hero the slides that use the photo are removed from the hero (a slide cannot exist without an image); the second confirmation names them ("Hero, slide 3"). The hero then has fewer slides and stays published as long as it has a title. | Keep the slide and mark it "image missing" until a new image is chosen: needs a nullable slide image and a changed public contract. | `HeroMediaUsageProvider.TrashAsync` |
|
||||
| 31 | **Trash mechanics** (decision 12). | `DeletedAt` on the Hero image: a trashed photo is hidden from the Hero (slides, upload by hash, renderer) and shown in the library trash; Restore clears it. After 7 days the cleanup turns it into retired files (removed immediately) and removes the row. Uploading the same file again restores it. The trash period is `Media:TrashDays` (7). | Another period: the setting; no trash: delete straight to retired files. | `HeroImage.DeletedAt`, `HeroMediaCleanup`, `MediaOptions.TrashDays` |
|
||||
| 32 | **Migration of `HeroImages`** (decision 13): the plan and the safeguards. | Designed in `inception/application-design/migration-plan.md` (back-up, rollback, verification, test-only rollout). The additive columns of this round (`OriginalFileName`, `DeletedAt`, `LastUsedAt`) are copied with the rest. Not run anywhere until SLS-Main has been told and agrees to the test deploy. | n/a | `migration-plan.md` |
|
||||
|
||||
### Status of the assumptions (2026-11-17)
|
||||
|
||||
- **Decided by Bryan** (second round, table above): 3, 4, 7, 8, 10, 12, 13, 21.
|
||||
- **Confirmed by Bryan "as designed"**: 1, 2, 5, 6, 9, 11, 14, 15, 16, 19, 20, 26, 27, 28.
|
||||
- **Still assumptions** (not put to him separately): 17 (language), 18 (what phase A contained, now overtaken), 22 (selectability), 23 (performance), 24 (ASF data), 25 (use definitions); and the older rows 18 to 25 above. Assumptions 29 to 32 follow from his decisions.
|
||||
- Assumption 12 now reads: there IS a trash (decision 12), the earlier "no trash in phase A" no longer applies. Assumption 10: deleting a used photo is possible after a second confirmation (built). Assumption 21: the original file name is stored from now on (built).
|
||||
| 33 | **Where the copy runs and what it copies** (built 2026-11-17). | A new module `Modules.Media` owns the tables (`MediaAssets`, `MediaUses`); modules offer their data through `IMediaMigrationSource` so the library module does not depend on the Hero. The copy is a verified mirror in one transaction behind `Media:Library:CopyOnStartup` (default false). The use of a hero slide carries both crops (`wide`, `tall`) of its photo as JSON; its set hash is the photo's current set hash. | A copy job triggered from the admin instead of start-up: easier to time, needs an endpoint and a button. | `Modules.Media/Services/MediaLibraryCopier.cs`, `HeroMediaMigrationSource` |
|
||||
| 34 | **Naming**: entity `MediaAssetUse` (table `MediaUses`), because `MediaUse` already names the read model in Core. | As built. | Rename the table or the record: a small migration. | `Modules.Media/Data` |
|
||||
| 35 | **Test deploy without a separate database dump** (decided on assumption by SLS-Main, 2026-11-17, Bryan away). | The Raspberry Pi test host cannot be dumped by SLS-Main; the test data can be rebuilt with the seed scripts and both database changes of the branch (`AddMediaLibraryColumns`, the empty Media tables) are additive, so the test deploy goes ahead without a dump. The copy stays OFF until Bryan agrees. | Take a dump on the Pi before the deploy (and certainly before the copy is switched on). | `migration-plan.md`, section "Test host" |
|
||||
| 36 | **Choose from the library in a hero slide** (built 2026-11-17 at Bryan's request, before the migration). | Each slide has "Choose from library" next to its photo: the shared `ImagePicker` lists the library photos of the modules that can be chosen (now the hero's own photos, also those in no slide, never the trash) and a new photo can be uploaded on the spot with the hero's own upload (same checks, limits and background processing). Choosing only sets the slide's existing image id (no data model change). A photo that is already in another slide can be chosen again: it is the same photo, so its **crop is shared by the slides that use it** (the crop belongs to the photo in the hero today; a crop per slide comes with the library's own use records). | A separate crop per slide now would need the use records of phase 2 (or a copy of the photo). | `features/hero/components/LibraryPickerDialog.tsx`, `HeroPage.tsx` |
|
||||
| 37 | **Removing from the trash for good** (Bryan, 2026-11-17). | `POST media-library/purge {ids}` (at most 100) or `{all:true}` (the server empties the whole trash in batches). Only photos that are in the trash and used nowhere are removed; the module checks it again and answers per photo (`purged`, `notInTrash`, `inUse`, `failed`). The original and the cut set go through `IMediaStore`; a file another photo still shares stays. The UI asks a clear confirmation that says it cannot be undone and names the number (and the size for the whole trash); "Empty the trash" is disabled when the trash is empty. No separate waiting period. | A short undo window for a purge: not built (the trash itself is the undo). | `MediaLibraryService.PurgeAsync`, `HeroImageService.PurgeAsync`, `PurgeDialog` |
|
||||
| 38 | **A new crop applies at once, without saving the hero** (Bryan, 2026-11-17; replaces Hero assumption 1 of 2026-11-16, which said a focus change only takes effect when the hero is saved). | The focus dialog's Apply sends the crop at once (`PUT hero/images/{id}/focus`); the server cuts the new variants in the background and the photo switches to them when they are complete, so what is live changes only then, without another Save. The photo shows "Wordt verwerkt…", a 0-100% bar and the percentage on itself (no spinner); the upload keeps its own display. The counter "x of y processed" counts the current upload batch only. | Back to applying only on Save: restore the focus edits kept locally in `HeroPage`. | `HeroImageService.SetFocusAsync`, `HeroPage.applyFocus`, `RecutThumbnail` |
|
||||
| 39 | **Crop PER USE, not per photo** (Bryan, 2026-11-17: a photo on two slides can have its own crop on each slide). | Decided, **not built yet**: it is too large and risky for the hero as it is today, because the cut sets, their set hash and the public output all hang on the photo (`HeroImage.SetHash`, `Variants`), so a crop per slide means a set per slide. The smallest safe step is built instead: a photo may be chosen for several slides, the crop is shared and the slide says so ("This photo is in more slides; the crop applies to all of them"). Design of the rest in `inception/application-design/per-use-crop.md`: it comes with phase 2 of the migration, because the library's own use records (`MediaUses.Crops`, `MediaUses.SetHash`) are where a crop per slide lives and the renderer then cuts a set per distinct crop. No public address or set hash changes until then. | An additive nullable focus on the slide (x, y, zoom) that overrides the photo's default focus, with a set per (photo, crop) and the public hero choosing the slide's set: possible without the library tables, but it rebuilds the renderer and the public mapping of the hero first; then phase 2 would have to move it again. | `HeroSlide`, `HeroImageService.RenderNextPendingAsync`, `HeroMapping` |
|
||||
| 40 | **Switching the copy on at the test hosts without access to the Pi** (Bryan, 2026-11-17: the copy may run on test). | The deploy workflow has a new input `media_library_copy` (unchanged, on, off; dispatch input of the CI workflow, passed to the SLS test and ASF test deploys). A step edits ONLY the key `Media__Library__CopyOnStartup` in `<deploy_path>/shared/env` over the deploy account's SSH access (refuses any environment that is not `test`, accepts only on, off or unchanged, never prints the file), before the service restart; after the restart a step shows the journal line `Media library copy verified: N photos and M uses`. `off` removes the key again. | Set the variable by hand in `shared/env` on the Pi (needs a shell there). | `.gitea/workflows/deploy-scp.yaml`, `continuous_integration.yaml` |
|
||||
| 41 | **The picker has a single and a multiple mode** (Bryan, 2026-11-17). | `ImagePicker` takes `mode="single"` (default, radio group, used by the hero slides) or `mode="multiple"` (checkboxes, several photos, several files per upload, ready for the gallery). Both use the same upload checks. | n/a | `ImagePicker.tsx` |
|
||||
| 42 | **One progress pattern for upload, processing and a new crop** (Bryan, 2026-11-17, after seeing it on test). | A shared `ProcessingProgress` (text "Wordt verwerkt…", one 0-100% bar, the percentage, no spinner, no step counts) is used on every photo and for the batch. The batch bar covers upload and processing together; there are no byte counts from the upload, so a photo's percentage is staged: waiting 0, uploading 15, uploaded 30, then 30-100 from the server's processing steps. A new crop uses the full 0-100 from its steps. The counter "x van y verwerkt" stays per batch. | Real upload byte progress (needs XHR progress in the API client). | `features/media/components/ProcessingProgress.tsx`, `lib/photoProgress.ts`, `hero/components/ProcessingStatus.tsx` |
|
||||
| 43 | **"Slide toevoegen" replaces the per-slide library button** (Bryan, 2026-11-17, after seeing it on test; replaces assumption 36's per-slide button). | The per-slide "Kies uit bibliotheek" is gone. The existing add button is "Slide toevoegen" and opens the shared picker: choose a library photo or upload one on the spot (it also lands in the library, ML-17); one photo makes one NEW slide. A slide's photo cannot be changed or replaced: remove the slide and add another. Dropping files on the section still adds one slide per file (same upload as before). The crop per slide stays a goal (phase 2). | Keep a per-slide change button: Bryan said no. | `HeroPage.addSlideWithPhoto`, `LibraryPickerDialog` |
|
||||
| 44 | **Tiles or list in the library** (Bryan, 2026-11-17). | The library and the trash show the photos as tiles (grid of thumbnails, selectable, same usage and links) by default, with a switch Tiles / List next to the filters. The choice is remembered in the browser (`localStorage`, guarded; it falls back to tiles). The clean-up dialog keeps its list. The picker already is a grid. | Remember the choice on the server per user: needs a user-settings store. | `PhotoSelectionList` (`layout`), `lib/layoutPreference.ts`, `MediaLibraryPage` |
|
||||
| 45 | **Media screen details** (Bryan, 2026-11-17): bulk bar keeps its height; the whole tile selects; smaller tiles; 0 days in the clean-up; no time-basis choice. | The bar is an invisible placeholder of the same height (h-9) while nothing is selected. A click on a tile selects it (shift for a range); links, buttons and the box itself do their own thing. One more tile per row at every width. The clean-up slider goes from 0: 0 days means every photo that is not in use right now qualifies at the next clean-up (preview and confirmation unchanged, with a note at 0). The period always counts from the last use (assumption 29); there was no separate checkbox for the time basis in the clean-up (the only checkbox is "Alleen ongebruikte foto's", a filter, which stays because it protects photos in use), so nothing was removed. | If Bryan meant "Alleen ongebruikte foto's": removing it would put photos in use in the clean-up (counted from their upload date). | `BulkActionBar`, `PhotoSelectionList`, `CleanupDialog`, `CleanupSelection.MinDays` |
|
||||
| 46 | **Compact tiles in the clean-up and the delete confirmation** (product owner request, 2026-11-17). | `PhotoSelectionList` has a third layout `compact` (3/4/6/8 columns, square small thumbnails, name and a short usage line on one truncated line each, full name, date, size and usage in the tooltip; checkbox chip, whole-tile select, select all and the bulk bar unchanged). The clean-up dialog uses it. The "places that lose the photo" list in the second step of `DeleteDialog` is a read-only compact grid of the same kind. `PurgeDialog` shows no photo list (only a count), so it is unchanged; the library tiles and the ImagePicker are unchanged. | Long row lists again in the dialogs (much scrolling, little overview). | `PhotoSelectionList.tsx` (`layout="compact"`), `CleanupDialog.tsx`, `DeleteDialog.tsx` (`delete-places`) |
|
||||
|
||||
@@ -114,6 +114,17 @@ Text alternative: one photo has uses in Hero (wide and tall share one set), a mo
|
||||
|
||||
- `MediaUseDefinition` (code, per module): ratio names, ratio values and widths for the variant planner. Hero's `wide` and `tall` exist today; the mosaic's tile ratios and masonry's natural ratio are added by the gallery module.
|
||||
- A natural-ratio use stores no crop (focus ignored); the planner produces widths only.
|
||||
- **Use definitions from the ASF site (2026-11-17, see assumption 24)**:
|
||||
|
||||
| Use | Ratio (desktop / phone) | Widths | Crop |
|
||||
|---|---|---|---|
|
||||
| `hero-wide`, `hero-tall` | 3:2 / 2:3 (as built) | as built | focus per use |
|
||||
| `mosaic-large` (photo 1) | about 1:1 / 4:3 | up to 656, retina 480, 640, 960, 1280 | focus point |
|
||||
| `mosaic-wide` (photo 2 of 3 or 4) | about 2.2:1 / 3:2 | up to 656, same retina set | focus point |
|
||||
| `mosaic-small` (photos 3 and 4 of 4) | about 1.04:1 / 1:1 | up to 312, retina set | focus point |
|
||||
| `masonry` | natural | about 480 and 800 (thumb), plus `full` for the lightbox | none |
|
||||
|
||||
The mosaic tile shape is fixed per page by the number and order of the photos, so a use is `(page, tile role)`; a photo can have a different crop in each role. Phone shapes differ from desktop shapes, so a mosaic use carries two ratios (desktop and phone), like Hero's `wide` and `tall`.
|
||||
- The Hero sets are unchanged: one use per slide carrying the image's `wide` and `tall` crops, one set hash.
|
||||
|
||||
## 5. Delete and clean-up flow
|
||||
@@ -174,3 +185,60 @@ The model and services live in **Core** (`SlpModularCms.Core.Media`, next to the
|
||||
- Hero provider: uses per slide, detach.
|
||||
- Regression: golden files and the host-injection tests unchanged; a set made before the library is still served.
|
||||
- Frontend: selection by mouse and keyboard, announcements, dialog flow, i18n nl and en.
|
||||
|
||||
## 10. Choose or upload (ML-17)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M[Module screen, for example a hero slide] --> P[ImagePicker]
|
||||
P -->|choose| L[Library photos]
|
||||
P -->|upload on the spot| U[Module upload callback]
|
||||
U --> S[Upload service: guard, limits, store]
|
||||
S --> R[Background renderer]
|
||||
S --> L
|
||||
L --> P
|
||||
classDef m fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
|
||||
classDef c fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
|
||||
classDef s fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
|
||||
class M m;
|
||||
class P,L c;
|
||||
class U,S,R s;
|
||||
```
|
||||
|
||||
Text alternative: a module screen uses the picker, which either chooses a library photo or uploads through the module's upload callback; the upload service validates and stores, the renderer cuts variants in the background, and the new photo is in the library and is chosen at once.
|
||||
|
||||
- **Component**: `features/media/components/ImagePicker` (frontend, built as a pure component, not wired anywhere yet). Props: the library photos, the chosen id, `onChange`, an optional `onUpload(file) => Promise<photo>`, the upload limit and a short limits text. It is a radio group of thumbnails (arrow keys), plus an upload button; after a successful upload it chooses the new photo. It holds no data and calls nothing by itself, so each module decides what an upload does.
|
||||
- **Same checks as the Hero**: the quick client checks are one shared function (`validateUpload`: an image, not over the limit); the host repeats and extends them (signature, pixel limit, rate limit, total storage) through the one `IMediaUploadGuard`. A multi-file upload and drag and drop stay module screens' choice (Hero keeps its own).
|
||||
- **Background processing**: unchanged. An upload stores the original and returns at once; `HeroRenderService` (later a shared renderer) cuts variants. The picker shows a photo without a thumbnail ("no preview") until its set exists, and the library list refreshes while photos are processing.
|
||||
- **How the Hero upload relates to the library**:
|
||||
- Now (phase A): the Hero keeps its own upload (`POST /hero/images`) and its `HeroImages` table. Hero photos already appear in the library through the usage provider, so a photo uploaded in the Hero is visible and clean-up-able in the library. The Hero screen does not use the picker yet, and no behaviour changes.
|
||||
- Phase B: one upload service in Core; **every upload creates exactly one library record** (`MediaAsset`), whichever module's screen it came from; the same file is one record (hash). The Hero's slide then refers to the library photo instead of its own image row.
|
||||
- Phase C: the existing `HeroImages` are copied as library records with the same ids, hashes and set hashes (design section 6), after which the Hero screen switches to the picker.
|
||||
- **Other modules** (gallery, mosaic, masonry) use the picker from the start, with their own use definition (`GalleryUses`) deciding the ratios and crops of the chosen photo.
|
||||
- **Rights and limits**: the same Owner and Administrator rights as the library; the hero upload rate limit (100 per user per hour) applies to the shared upload service.
|
||||
|
||||
## 11. Delete, trash and last use (built 2026-11-17, decisions 8, 10, 12, 21)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
L[Library or Clean-up] -->|delete ids| C[MediaLibraryService]
|
||||
C -->|uses again| P[Usage provider]
|
||||
P -->|none, or confirmed twice| T[Module trash: detach and DeletedAt]
|
||||
T --> TR[(Trash 7 days)]
|
||||
TR -->|restore| P
|
||||
TR -->|after the period| R[Retired files, removed with the sets]
|
||||
classDef a fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
|
||||
classDef b fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
|
||||
classDef c fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
|
||||
class L a;
|
||||
class C,P b;
|
||||
class T,TR,R c;
|
||||
```
|
||||
|
||||
Text alternative: delete goes through the library service, which checks the usage again and asks the module to trash the photo; the trash keeps it for the trash period and can restore it; afterwards its files are retired and removed.
|
||||
|
||||
- API: `POST media-library/delete {ids, confirmedInUse}` and `POST media-library/restore {ids}` (at most 100 ids), `GET media-library/trash`; the answer lists a status per photo (`trashed`, `inUse`, `notFound`, `failed`).
|
||||
- Hero: `HeroImages.DeletedAt`, `LastUsedAt`, `OriginalFileName` (additive migration `AddMediaLibraryColumns`); a trashed image is left out of every Hero lookup, the renderer and slide validation; slides using it are removed when it is trashed; `HeroMediaCleanup` empties the trash after `Media:TrashDays`.
|
||||
- Last use: `LastUsedAt` is set when a hero save detaches the photo from its last slide, and when it is trashed while in use. The clean-up counts from there (assumption 29).
|
||||
- Frontend: `DeleteDialog` (first and second confirmation), trash view with Restore, the clean-up dialog now confirms into the same delete flow.
|
||||
- The migration to own tables is planned in `migration-plan.md` (not built).
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# Migration plan: HeroImages to the library's own tables (decision 13)
|
||||
|
||||
Status: plan, not built, not run anywhere. Decided by Bryan 2026-11-17 (via SLP Software - SLS - Main): it may be built in the next step, **only after this plan with its back-up and rollback exists**, **rolled out to TEST only (never production)**, and **SLS-Main is told before anything is deployed to test**.
|
||||
|
||||
## Goal
|
||||
|
||||
Give every photo one library record that does not depend on the Hero: `MediaAsset` (the photo) and `MediaUse` (where it is used), with **the same ids, hashes, set hashes and public addresses** as today. Nothing in `/media/hero/<setHash>/...` changes, so ASF, SLS and the golden files stay as they are.
|
||||
|
||||
## Why expand then contract
|
||||
|
||||
| Phase | What | Reversible? |
|
||||
|---|---|---|
|
||||
| 0 Back-up | Back-up of the database and a listing of the media directory (below). | n/a |
|
||||
| 1 Expand | New tables `MediaAssets` and `MediaUses`, filled by copying `HeroImages` and `HeroSlides`. The Hero keeps reading and writing its own tables; the library reads the new tables behind a setting. | Yes: drop the two new tables, nothing else changed. |
|
||||
| 2 Switch | Hero reads photos from the library tables (setting on). New uploads write both (dual write) so the old tables stay complete. | Yes: switch the setting off; the old tables are complete. |
|
||||
| 3 Contract (a later release, after acceptance) | The Hero stops writing its own image columns; they are dropped in a separate migration. | Only from the back-up of that moment. Not part of the first rollout. |
|
||||
|
||||
Files are never moved or renamed: the migration changes rows only, so the media directory is the same before and after.
|
||||
|
||||
## Mapping
|
||||
|
||||
| `HeroImages` column | `MediaAssets` column | Note |
|
||||
|---|---|---|
|
||||
| `Id` | `Id` | Same id, so references keep working. |
|
||||
| `OriginalSha256`, `OriginalKey`, `SourceFormat`, `Width`, `Height`, `Bytes` | same | |
|
||||
| `FocusX`, `FocusY`, `Zoom` | `DefaultFocusX`, `DefaultFocusY`, `DefaultZoom` | The photo's default focus. |
|
||||
| `WideFocus*`, `TallFocus*` | `MediaUses` rows (one per slide use, ratios `wide` and `tall`) | The per-use crop; for a photo without a slide the default focus is enough. |
|
||||
| `SetHash`, `Variants` | `MediaUses.SetHash` (per use) | Unchanged values; computed by the existing formula. |
|
||||
| `CreatedAt`, `CreatedByUserId` | same | |
|
||||
| `OriginalFileName`, `LastUsedAt`, `DeletedAt` | same | Added in the media-library step (additive columns of the Hero). |
|
||||
|
||||
| `HeroSlides` | `MediaUses` |
|
||||
|---|---|
|
||||
| `Id`, `ImageId` | `Id`, `AssetId` (module `hero`, place kind `slide`, place id = slide id) |
|
||||
|
||||
## Back-up (before phase 1, every environment)
|
||||
|
||||
1. **Database**: a full dump of the Hero database (and of the CMS database if it is one), written to a dated file outside the deploy directory, for example `mysqldump --single-transaction <database> > hero-before-media-migration-YYYYMMDD.sql`. Keep it until the contract phase is accepted.
|
||||
2. **Media directory**: nothing is moved, but a listing with sizes and hashes is saved (`find <Media__Directory> -type f -exec sha256sum {} +` to a text file) so the directory can be compared afterwards. On the Raspberry Pi a copy of the directory is also a quick option (`cp -a`), if there is room.
|
||||
3. **Row counts** noted: `HeroImages`, `HeroSlides`, `HeroRetiredFiles`.
|
||||
|
||||
## Verification (right after phase 1, every environment)
|
||||
|
||||
The migration job compares and **aborts** (rolls its transaction back) on any difference:
|
||||
|
||||
- number of `MediaAssets` = number of `HeroImages` (all rows, also those in the trash);
|
||||
- every `HeroImages.Id`, `OriginalSha256` and `SetHash` has an identical `MediaAssets`/`MediaUses` counterpart;
|
||||
- number of `MediaUses` of module `hero` = number of `HeroSlides`;
|
||||
- a sample of ten public addresses (`/media/hero/<setHash>/<file>`) is requested before and after and gives the same bytes (checked by the smoke test).
|
||||
|
||||
## Rollback
|
||||
|
||||
| When | How |
|
||||
|---|---|
|
||||
| The verification fails | The migration runs in one transaction and rolls back by itself; nothing is left. |
|
||||
| After phase 1, before the switch | Drop `MediaUses` and `MediaAssets` (the EF `Down` migration). The Hero never read them. |
|
||||
| After the switch | Switch the setting back (`Media:Library:ReadFromLibrary=false`); the old tables are complete because of the dual write. Then drop the new tables if wanted. |
|
||||
| After the contract phase (later) | Restore the database dump taken before that migration and the media listing check. |
|
||||
|
||||
## Roll-out rules (from Bryan)
|
||||
|
||||
1. **Test only.** No production variables, no production deploy, no release branch.
|
||||
2. **Tell SLS-Main before deploying to test** (they run the deploy and the smoke test).
|
||||
3. Back-up first (above), on the test host too.
|
||||
4. Deploy with the setting **off**, check the verification result in the log, then switch it on, then the smoke test (hero markers, `/theme-init.js`, a sample of media addresses), then Bryan checks the admin.
|
||||
|
||||
## Status (2026-11-17): phase 1 (expand) is built, behind a setting that is OFF
|
||||
|
||||
Built on `feature/media-library-screen`, not yet deployed anywhere:
|
||||
|
||||
- New module `SlpModularCms.Modules.Media` (own `MediaDbContext`, tables `MediaAssets` and `MediaUses`, additive migration `InitialCreate`; no existing table is touched). It is referenced by the three hosts, so a deploy of this code creates the two empty tables at start-up and nothing else.
|
||||
- `IMediaMigrationSource` (Core) and `HeroMediaMigrationSource` (Hero, read-only): the hero's photos (also those in the trash) and slides with their own ids, hashes and set hashes.
|
||||
- `MediaLibraryCopier`: copies and **verifies** (counts, ids, hash, key, size, set hash) in one transaction; any difference or error rolls the whole copy back and nothing is left. It MIRRORS the source, so running it again gives the same result; rows of other modules are not touched.
|
||||
- The copy runs only when `Media__Library__CopyOnStartup=true` (default **false**) and a failure is logged, never fatal.
|
||||
- Tested in memory and against a real MariaDB (migration, copy twice, rollback on a failing copy).
|
||||
|
||||
Nothing reads from the new tables yet (phase 2, the switch, is not built). The library screen still reads the hero through the usage provider.
|
||||
|
||||
### Roll-out on TEST (needs SLS-Main to be told first)
|
||||
|
||||
1. Back-up (database dump and media listing) as above.
|
||||
2. Deploy the branch with `Media__Library__CopyOnStartup` unset: the two empty tables appear; check the log for the Media migration.
|
||||
3. Set `Media__Library__CopyOnStartup=true` and restart: the log says `Media library copy verified: N photos and M uses from hero` (or the error and the rollback).
|
||||
4. Rollback at any point: set it back to false (the tables stay, unused) or drop `MediaUses` and `MediaAssets`.
|
||||
5. Never on production.
|
||||
|
||||
### Still to build (phases 2 and 3)
|
||||
|
||||
The switch (`Media:Library:ReadFromLibrary`, dual write of new uploads, library reading from the new tables) and the contract phase. They need Bryan's acceptance of the copy on test first.
|
||||
|
||||
## Test host: what to check around the copy (prepared 2026-11-17; the copy is NOT switched on yet)
|
||||
|
||||
**Deploy without the copy (decided on assumption by SLS-Main, Bryan away):** the test deploy of the branch carries two additive database changes, the Hero migration `AddMediaLibraryColumns` (three nullable columns) and the empty tables of the Media module. No separate database dump is taken on the Raspberry Pi (SLS-Main cannot make one); the assumption is that the test data can be rebuilt with the seed scripts and that both changes are additive. Bryan checks this assumption later.
|
||||
|
||||
After that deploy, check in the log:
|
||||
|
||||
- `Applying migration '..._AddMediaLibraryColumns'` and `Applying migration '..._InitialCreate'` (Media) appear once, no error;
|
||||
- the Hero admin still opens, a photo can be uploaded and a slide saved (smoke test), and `/media/hero/<setHash>/...` addresses still answer;
|
||||
- `Media__Library__CopyOnStartup` is NOT set: no line `Media library copy verified` appears.
|
||||
|
||||
**To switch the copy on (only after Bryan's agreement):**
|
||||
|
||||
1. Make a database dump first if it can be done, and note the number of rows: `SELECT COUNT(*) FROM HeroImages; SELECT COUNT(*) FROM HeroSlides;`.
|
||||
2. Set the environment variable `Media__Library__CopyOnStartup=true` on the test host and restart the application.
|
||||
3. The log must say `Media library copy verified: N photos and M uses from hero.` with N equal to the `HeroImages` count and M equal to the `HeroSlides` count. An error line `The media library copy failed and was rolled back` means nothing was copied.
|
||||
4. Check: `SELECT COUNT(*) FROM MediaAssets; SELECT COUNT(*) FROM MediaUses;` equals the same counts; the library screen still shows the same photos (it still reads the hero).
|
||||
5. Switch it off again (remove the variable, restart) when done: the copy can be repeated at any time; it is a mirror.
|
||||
|
||||
**Rollback:** remove the variable (the tables stay, unused), or drop the tables with the EF `Down` migration of the Media module; the Hero's own tables are never changed by the copy.
|
||||
|
||||
## Switching the copy on at the test hosts (no shell on the Pi needed)
|
||||
|
||||
The application reads `Media__Library__CopyOnStartup` from the host's `shared/env` (the file the service starts with). The deploy workflow can set exactly this one key, so nobody needs a shell on the Raspberry Pi:
|
||||
|
||||
1. Dispatch the CI workflow (`Continuous Integration`) on the branch with **deploy_sls_test** and/or **deploy_asf_test** checked and **media_library_copy = on**. Each test deploy then sets `Media__Library__CopyOnStartup=true` in its own `shared/env` before restarting the service, and the run log shows the line `Media library copy verified: N photos and M uses from hero` (or the error line that says the copy was rolled back).
|
||||
2. Check N and M against the hero (photos and slides) and the library screen.
|
||||
3. Dispatch once more with **media_library_copy = off** (and the deploy flags again): the key is removed and the next start does not copy. (`unchanged`, the default, never touches the file.)
|
||||
|
||||
The input is refused for any environment other than `test`, and only the three values are accepted; the workflow never prints the file (it holds secrets). Production is not reachable.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Crop per use (decision of Bryan, 2026-11-17)
|
||||
|
||||
A photo on two slides can have its own crop on each slide. Decided; **not built yet**. What exists today, why it waits, and the plan.
|
||||
|
||||
## Today
|
||||
|
||||
- The crop (default focus and the `wide` and `tall` overrides) is a property of the **photo** (`HeroImage`). The cut set (`SetHash`, `Variants`) belongs to the photo too, and so does the public output of the hero. A photo chosen for two slides therefore has one crop; the slide says so.
|
||||
- The set hash is `MediaPaths.SetHash(originalSha256, crops)`, so a set is already addressed by photo plus crops; the formula does not have to change.
|
||||
|
||||
## Why not now
|
||||
|
||||
A crop per slide means a set per (photo, crop). The renderer (`HeroRenderService`), the public hero mapping and the admin all assume one set per photo. Changing that on the hero's own tables and then moving it again when the library takes over (`MediaUses` already has `Crops` and `SetHash` per use) would be done twice and puts the public output at risk before the library is accepted.
|
||||
|
||||
## Plan (with phase 2 of the migration)
|
||||
|
||||
1. The library's `MediaUses` (one per slide) carry the crops and the set hash of that use (the copy already fills them from the photo).
|
||||
2. The hero slide gets its own crop (nullable focus overriding the photo's default; empty = the default), edited in the same focus dialog, applied at once like today.
|
||||
3. The renderer cuts one set per distinct (photo, crops); a set that two uses share (same crops) is cut once; a set nobody uses any more is cleaned up like a retired set.
|
||||
4. The public hero maps each slide to the set of its use. With no override the set is exactly today's set hash, so existing addresses and the golden files do not change.
|
||||
5. Tests: two slides with one photo and different crops give two sets and two addresses; with the same crop one set; no override gives today's hash.
|
||||
|
||||
## Smallest safe step built now
|
||||
|
||||
A photo may be chosen for several slides and the slide shows "This photo is in more slides; the crop applies to all of them" (assumption 36 and 39).
|
||||
@@ -39,9 +39,9 @@
|
||||
| ML-02 | **Usage indicator.** Per photo: "in use" or "not used", and where (module and place, for example "Hero, slide 3"). | Several uses are all listed; the indicator is computed from the modules' own data, not guessed; a photo used nowhere shows "Not used". |
|
||||
| ML-03 | **Keep everything.** No automatic removal of any photo or its files. | The Hero step that retires unattached images is switched off once the library owns the retention (see section 8, phase A: behind a setting, default decided in the assumptions); a test proves nothing is removed without a person's action. |
|
||||
| ML-04 | **Selection component** (own reusable component): checkboxes per photo, select all and clear, a range with shift-click, keyboard operation, a visible count, and a live-region announcement of the count. | Works for mouse, keyboard and screen reader; reused by the library and the clean-up; uses the shared `Checkbox` of the theme. |
|
||||
| ML-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete**. The action bar is a separate component so more actions (tags, move) can be added without touching the list. | Delete asks for confirmation naming the number of photos and how many are in use; a failure of one photo does not stop the others and is reported per photo. |
|
||||
| ML-06 | **Delete rules.** A photo that is in use is not deleted unless the person explicitly confirms and the use is detached first. | Default: in-use photos are not selectable for delete in "Clean up" and are marked in the library; deleting an in-use photo from the library shows what will lose its image and requires a second confirmation; the host falls back as it does today for a slide without a set. |
|
||||
| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything older than 7 days, with a slider to look more or fewer days back, and a checkbox **Only unused photos**, default on (off = all photos in the period). | The list is newest first; all rows start selected; the person can deselect before confirming; confirming deletes exactly the selected rows; the summary shows the number and the bytes that will be freed. |
|
||||
| ML-05 | **Bulk actions** on the selection, in the library itself. First action: **Delete** (to the trash, ML-18). The action bar is a separate component so more actions (tags, move) can be added without touching the list. | Delete asks for confirmation naming the number of photos and how many are in use; a failure of one photo does not stop the others and is reported per photo. |
|
||||
| ML-06 | **Delete rules** (decision 10). A photo that is in use can be deleted after a **second confirmation that names the places**; the module detaches it first (Hero: its slides are removed). | The first confirmation says how many photos and how many are in use; the second names the places per photo; the server refuses a photo in use unless the request carries the confirmation and checks the usage again at that moment; one photo failing does not stop the others and is reported per photo. |
|
||||
| ML-07 | **"Clean up" button.** Opens the overview of photos that would be cleaned: default everything not used for more than 7 days (counted from the LAST USE, decision 8), with a slider to look more or fewer days back, and a checkbox **Only unused photos**, default on (off = all photos in the period). | The list is newest first; all rows start selected; the person can deselect before confirming; confirming deletes exactly the selected rows; the summary shows the number and the bytes that will be freed. |
|
||||
| ML-08 | **Clean-up is the same component as the library** (ML-04, ML-05) in a preselected view, not a second implementation. | One list/selection component, two entry points. |
|
||||
| ML-09 | **Storage usage and limit warning.** The screen shows the used space (originals plus variants), the configured limit, and a warning at a threshold and at the limit. | Used bytes are computed from the store and cached for a short time; the warning level is configurable (assumption: 80 percent); at the limit, uploads give a clear message instead of a failure; the existing `Media:MaxTotalBytes` (2 GB) is the limit. |
|
||||
| ML-10 | **Upload into the library** (single and multiple), with the same limits and checks as Hero today (type signature, size, megapixels, rate limit). | The Hero upload path and the library share one upload service; the same file is one photo (hash). |
|
||||
@@ -50,6 +50,7 @@
|
||||
| ML-13 | **Usage register for modules.** A module reports where it uses photos and can be asked to detach a photo. | Contract in the design (section 3 of the application design); Hero is the first provider; a module without a provider counts as "uses nothing" and the library shows a warning that its uses are unknown (so a photo is not silently deleted). |
|
||||
| ML-14 | **Public addresses unchanged.** `/media/hero/<setHash>/<ratio>-<width>.<ext>` and every existing set hash stay valid. | Golden files and the host-injection tests stay green without edits; a regression test serves a set created before the library. |
|
||||
| ML-15 | **Permissions.** Owner and Administrator may use the library (like Hero and Offerings). | `[Authorize(Policy = "AdminOnly")]`; rate limits on upload and bulk delete. |
|
||||
| ML-17 | **Choose or upload, in every part that needs an image** (new requirement of Bryan, 2026-11-17). In every module that needs an image (Hero, later gallery, mosaic, masonry) the person can upload on the spot, also when the library holds no suitable image yet, and can choose from the existing library photos. An image uploaded on the spot is added to the library automatically and can be chosen everywhere afterwards. | One shared component "choose or upload" (a picker of the library photos plus an upload button) is reused by every module; it applies the same validation, limits and background processing as the Hero upload today; after an upload the new photo is chosen at once; the module keeps its own use (place, crop) of the chosen photo; a photo uploaded in one module is listed and choosable in the others. Until the library owns uploads (phase B) the Hero upload flow stays as it is. |
|
||||
| ML-16 | **Audit.** Each deletion (single, bulk, clean-up) is logged with user, photo ids and count. | Structured log entry per action; no photo content in the log. |
|
||||
|
||||
## 5. Non-functional requirements
|
||||
@@ -87,8 +88,8 @@
|
||||
|
||||
| Phase | Content | Moves data? | Build now? |
|
||||
|---|---|---|---|
|
||||
| A. Foundations (safe, reversible) | Usage contract in Core (`IMediaUsageProvider`), Hero provider (read only), library read model over `HeroImages`, storage usage service, selection and bulk-action components (frontend), clean-up selection logic, library screen (list, usage, selection, bulk delete through the Hero service), Hero retention setting | No (delete uses existing Hero delete path) | After Bryan acknowledges the assumptions; pure and read-only parts can start earlier |
|
||||
| B. Own tables | `MediaAsset` and `MediaUse` tables, upload into the library, default focus | New tables only | Needs alignment |
|
||||
| A. Foundations (safe, reversible) | The shared `ImagePicker` component (pure, not wired), usage contract in Core (`IMediaUsageProvider`), Hero provider (read only), library read model over `HeroImages`, storage usage service, selection and bulk-action components (frontend), clean-up selection logic, library screen (list, usage, selection, bulk delete through the Hero service), Hero retention setting | No (delete uses existing Hero delete path) | After Bryan acknowledges the assumptions; pure and read-only parts can start earlier |
|
||||
| B. Own tables | `MediaAsset` and `MediaUse` tables, upload into the library (one library record per upload, ML-17), default focus | New tables only | Needs alignment |
|
||||
| C. Migration of Hero | Copy `HeroImages` into `MediaAsset` plus `MediaUse` (one use per slide), keep set hashes and addresses, switch Hero to the library, drop old columns later (expand then contract) | Yes | Needs alignment and a back-up |
|
||||
| D. Gallery module | First other consumer (mosaic, masonry) | Own data | Separate feature |
|
||||
|
||||
@@ -101,5 +102,15 @@
|
||||
| 3 Overview newest first, usage indicator | ML-01, ML-02, ML-07 |
|
||||
| 4 and 6 Bulk actions as own component | ML-04, ML-05, ML-08 |
|
||||
| 5 Storage and limit warning | ML-09 |
|
||||
| 8 (2026-11-17) Choose or upload in every part that needs an image | ML-17, design section 10 |
|
||||
| 7 Crop per use | ML-11, ML-12, design section 4 |
|
||||
| Boundary: addresses and set hashes | ML-14, NFR-ML-05 |
|
||||
|
||||
## 11. Added by decisions of 2026-11-17
|
||||
|
||||
| ID | Requirement | Acceptance criteria |
|
||||
|---|---|---|
|
||||
| ML-18 | **Trash** (decision 12). Delete means "to the trash": recoverable for 7 days (`Media:TrashDays`); a trash view lists the photos with Restore; after the period the files are removed by the existing retired-file mechanism. Uploading the same file again brings it back. | A trashed photo is hidden from the hero and from the renderer; restore returns it (without its old slides); the clean-up of the trash is idempotent; a photo is never removed while it is referenced. |
|
||||
| ML-19 | **Original file name** is stored at every upload (additive) and shown in the library; photos from before keep a neutral label. | The name is cleaned (no path, no control characters, at most 200 characters) and never used as a path. |
|
||||
| ML-20 | **Last use** per photo: the moment it was last detached from a slide (or trashed); the clean-up period counts from there, from the upload date for a photo that was never used. | See assumption 29. |
|
||||
| ML-21 | **Migration of the Hero photos** to the library's own tables, expand then contract, same ids, hashes and addresses; documented back-up and rollback first; test only; SLS-Main is told before a test deploy. | See `migration-plan.md`. |
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ De admin toont alleen een badge Live of Niet live.
|
||||
| Instelling | Betekenis |
|
||||
|---|---|
|
||||
| `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. |
|
||||
| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. |
|
||||
| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__TrashDays` (standaard 7: bewaartijd van foto's in de prullenbak van de mediabibliotheek), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. |
|
||||
| `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. |
|
||||
| `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (`<span class="cms-hero-title-prefix">`), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. |
|
||||
| `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react';
|
||||
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon, Images } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
@@ -38,6 +38,14 @@ const NAV_ITEMS: NavItem[] = [
|
||||
roles: ['Owner', 'Administrator'],
|
||||
requiredModule: 'Hero',
|
||||
},
|
||||
{
|
||||
to: '/media',
|
||||
labelKey: 'nav.media',
|
||||
icon: Images,
|
||||
testId: 'nav-media',
|
||||
roles: ['Owner', 'Administrator'],
|
||||
requiredModule: 'Hero',
|
||||
},
|
||||
{
|
||||
to: '/offerings',
|
||||
labelKey: 'nav.offerings',
|
||||
|
||||
@@ -98,7 +98,6 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply
|
||||
return (
|
||||
<div className="space-y-4" data-testid="focus-dialog">
|
||||
<p className="text-sm text-muted-foreground">{t('hero.focus.intro')}</p>
|
||||
<p className="text-sm font-medium" data-testid="focus-apply-hint">{t('hero.focus.applyHint')}</p>
|
||||
|
||||
<fieldset className="flex flex-wrap gap-4">
|
||||
<legend className="sr-only">{t('hero.focus.targetLegend')}</legend>
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { ImagePicker } from '@/features/media/components/ImagePicker';
|
||||
import type { PhotoItem } from '@/features/media/components/PhotoSelectionList';
|
||||
import { toPhotoItem } from '@/features/media/lib/toPhotoItem';
|
||||
import { useMediaPhotos } from '@/features/media/services/hooks';
|
||||
import { useUploadHeroImage } from '../services/hooks';
|
||||
import type { HeroImageDto } from '../services/types';
|
||||
|
||||
interface LibraryPickerDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Which photo was chosen (the hero image id) and, for a photo uploaded here, the image the server answered with. */
|
||||
onChoose: (imageId: string, uploaded?: HeroImageDto) => void;
|
||||
maxUploadBytes: number;
|
||||
limitsText?: string;
|
||||
}
|
||||
|
||||
const MODULE = 'hero';
|
||||
|
||||
/**
|
||||
* "Add slide": the photos of the media library that a hero slide can use (now the hero's own
|
||||
* photos, also those that are in no slide; never the trash), or a new photo uploaded on the spot with the hero's own upload
|
||||
* (same checks and limits, variants cut in the background; it also lands in the library). One photo makes one new slide. A photo
|
||||
* that is already in another slide can be chosen again (assumption 36).
|
||||
*/
|
||||
export function LibraryPickerDialog({ open, onOpenChange, onChoose, maxUploadBytes, limitsText }: LibraryPickerDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const library = useMediaPhotos(open);
|
||||
const upload = useUploadHeroImage();
|
||||
// The picker chooses a freshly uploaded photo by itself (onChange); the dialog hands the server's answer along with it.
|
||||
const uploaded = useRef(new Map<string, HeroImageDto>());
|
||||
const items = (library.data?.photos ?? []).filter((p) => p.module === MODULE).map((p) => toPhotoItem(p, t));
|
||||
|
||||
const uploadHere = async (file: File): Promise<PhotoItem> => {
|
||||
const image = await upload.mutateAsync(file);
|
||||
uploaded.current.set(image.id, image);
|
||||
return { id: `${MODULE}:${image.id}`, name: file.name, bytes: file.size, createdAt: new Date().toISOString(), uses: [], thumbnailUrl: null };
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto" data-testid="library-picker">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('hero.library.title')}</DialogTitle>
|
||||
<DialogDescription>{t('hero.library.description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{library.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
{library.isPending ? (
|
||||
<p className="text-sm text-muted-foreground">{t('media.loading')}</p>
|
||||
) : (
|
||||
<ImagePicker
|
||||
items={items}
|
||||
value={null}
|
||||
onChange={(id) => {
|
||||
const imageId = id.slice(MODULE.length + 1);
|
||||
onChoose(imageId, uploaded.current.get(imageId));
|
||||
}}
|
||||
onUpload={uploadHere}
|
||||
maxUploadBytes={maxUploadBytes}
|
||||
limitsText={limitsText}
|
||||
label={t('hero.library.group')}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Check, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ProcessingProgress } from '@/features/media/components/ProcessingProgress';
|
||||
import { photoProgress, recutProgress, type UploadStage } from '@/features/media/lib/photoProgress';
|
||||
import { useRetryHeroImage } from '../services/hooks';
|
||||
import type { HeroImageDto } from '../services/types';
|
||||
|
||||
@@ -13,46 +15,32 @@ export function Spinner({ className = 'size-4' }: { className?: string }) {
|
||||
* Shown above the form while photos of the saved hero are still being prepared in the background: how many are ready,
|
||||
* what that means for the website, and a way to try again for a photo that failed.
|
||||
*/
|
||||
export function ProcessingStatus({ images }: { images: HeroImageDto[] }) {
|
||||
export function ProcessingStatus({ images, pendingUploads = [] }: { images: HeroImageDto[]; pendingUploads?: UploadStage[] }) {
|
||||
const { t } = useTranslation();
|
||||
const retry = useRetryHeroImage();
|
||||
const total = images.length;
|
||||
const waiting = images.filter((image) => image.processing);
|
||||
if (waiting.length === 0) return null;
|
||||
if (waiting.length === 0 && pendingUploads.length === 0) return null;
|
||||
|
||||
const done = total - waiting.length;
|
||||
// The counter and the one bar cover the current batch: the files that are still being uploaded and the photos that are
|
||||
// being processed. The bar is the overall progress of the whole chain, upload and processing together.
|
||||
const total = images.length + pendingUploads.length;
|
||||
const done = images.length - waiting.length;
|
||||
const failed = waiting.filter((image) => image.failed);
|
||||
const working = waiting.length - failed.length;
|
||||
// The photo the server is busy with right now, and how far along it is (a photo that waits has no step yet).
|
||||
const busy = waiting.find((image) => image.renderTotal) ?? null;
|
||||
const fraction = busy && busy.renderTotal ? (busy.renderDone ?? 0) / busy.renderTotal : 0;
|
||||
const percent = total === 0 ? 0 : Math.min(100, ((done + fraction) / total) * 100);
|
||||
const working = waiting.length - failed.length + pendingUploads.length;
|
||||
const percents = [
|
||||
...images.map((image) => photoProgress({ ready: !image.processing, upload: 'done', renderDone: image.renderDone, renderTotal: image.renderTotal })),
|
||||
...pendingUploads.map((stage) => photoProgress({ upload: stage })),
|
||||
];
|
||||
const percent = percents.length === 0 ? 0 : percents.reduce((sum, value) => sum + value, 0) / percents.length;
|
||||
|
||||
return (
|
||||
<div className="space-y-3 rounded-md border bg-muted/40 p-4" data-testid="hero-processing">
|
||||
{working > 0 && (
|
||||
<div className="space-y-2" role="status">
|
||||
<p className="flex items-center gap-2 text-sm font-medium">
|
||||
<Spinner />
|
||||
<span data-testid="hero-processing-count">{t('hero.processing.count', { done, total })}</span>
|
||||
<p className="text-sm font-medium" data-testid="hero-processing-count">
|
||||
{t('hero.processing.count', { done, total })}
|
||||
</p>
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label={t('hero.processing.label')}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={total}
|
||||
aria-valuenow={done}
|
||||
aria-valuetext={t('hero.processing.count', { done, total })}
|
||||
className="h-2 w-full overflow-hidden rounded bg-muted"
|
||||
data-testid="hero-processing-bar"
|
||||
>
|
||||
<div className="h-full bg-primary transition-all" style={{ width: `${percent}%` }} />
|
||||
</div>
|
||||
{busy && (
|
||||
<p className="text-sm" data-testid="hero-processing-current">
|
||||
{t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })}
|
||||
</p>
|
||||
)}
|
||||
<ProcessingProgress percent={percent} testId="hero-processing-bar" />
|
||||
<p className="text-sm text-muted-foreground">{t('hero.processing.explain')}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('hero.processing.stuck')}{' '}
|
||||
@@ -97,40 +85,38 @@ export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; te
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1 text-center text-xs ${failed ? 'bg-destructive/10 text-destructive' : 'hero-shimmer bg-muted'}`}
|
||||
className={`flex h-20 w-28 flex-col items-center justify-center gap-1 rounded p-1.5 text-center text-xs ${failed ? 'bg-destructive/10 text-destructive' : 'hero-shimmer bg-muted'}`}
|
||||
role="status"
|
||||
aria-busy={!failed}
|
||||
title={t('hero.slides.processingHint')}
|
||||
data-testid={testId}
|
||||
>
|
||||
{failed ? null : <Spinner className="size-3.5" />}
|
||||
<span>{failed ? t('hero.slides.failed') : t('hero.slides.processing')}</span>
|
||||
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
|
||||
{!failed && !step ? <span className="opacity-70" data-testid={`${testId}-queued`}>{t('hero.slides.queued')}</span> : null}
|
||||
{failed ? (
|
||||
<span>{t('hero.slides.failed')}</span>
|
||||
) : (
|
||||
<ProcessingProgress compact className="w-full" testId={`${testId}-progress`} percent={photoProgress({ upload: 'done', renderDone: step?.done, renderTotal: step?.total })} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photo of a slide whose crop is being made again (a changed focus point): the old picture stays visible underneath,
|
||||
* with the same calm shimmer and a short text, so it is clear that the change is not on the website yet.
|
||||
* The photo of a slide whose crop is being made again (a new crop): the old picture stays visible underneath, with one
|
||||
* short, readable line ("Wordt verwerkt…"), a progress bar from 0 to 100 percent and the percentage. No spinner, so it also
|
||||
* works without motion. A new crop needs no save: it goes live by itself when the new variants are complete.
|
||||
*/
|
||||
export function RecutThumbnail({ src, failed, testId, step }: { src: string; failed: boolean; testId: string; step?: { done: number; total: number } | null }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : ''}`} title={t('hero.slides.recutHint')} data-testid={testId}>
|
||||
<img src={src} alt="" className="h-full w-full object-cover" />
|
||||
<div
|
||||
className={`relative h-20 w-28 shrink-0 overflow-hidden rounded ${failed ? 'ring-2 ring-destructive' : 'hero-shimmer'}`}
|
||||
className={`absolute inset-x-0 bottom-0 space-y-1 px-1.5 py-1 text-xs ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background text-foreground'}`}
|
||||
role="status"
|
||||
aria-busy={!failed}
|
||||
title={t('hero.slides.recutHint')}
|
||||
data-testid={testId}
|
||||
>
|
||||
<img src={src} alt="" className="h-full w-full object-cover" />
|
||||
<span className={`absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-1 py-0.5 text-center text-[10px] leading-tight ${failed ? 'bg-destructive text-destructive-foreground' : 'bg-background/85 text-foreground'}`}>
|
||||
{failed ? null : <Spinner className="size-3" />}
|
||||
<span>{failed ? t('hero.slides.failed') : t('hero.slides.recut')}</span>
|
||||
{!failed && step ? <span className="tabular-nums opacity-80" data-testid={`${testId}-step`}>{step.done}/{step.total}</span> : null}
|
||||
</span>
|
||||
{failed ? <span>{t('hero.slides.failed')}</span> : <ProcessingProgress compact testId={`${testId}-progress`} percent={recutProgress(step?.done, step?.total)} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { AlertCircle, Check, Clock } from 'lucide-react';
|
||||
import { AlertCircle, Check, Clock, Upload } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Spinner } from './ProcessingStatus';
|
||||
|
||||
export interface UploadItem {
|
||||
key: number;
|
||||
@@ -11,7 +10,7 @@ export interface UploadItem {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** The files of the last choice, one row each: waiting, busy (spinner), added, or failed with the reason. */
|
||||
/** The files of the last choice, one row each: waiting, busy, added, or failed with the reason. */
|
||||
export function UploadProgress({ items, busy, onClose }: { items: UploadItem[]; busy: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
if (items.length === 0) return null;
|
||||
@@ -27,7 +26,7 @@ export function UploadProgress({ items, busy, onClose }: { items: UploadItem[];
|
||||
{items.map((item) => (
|
||||
<li key={item.key} className="flex items-start gap-2" data-testid={`hero-upload-item-${item.key}`} data-status={item.status}>
|
||||
<span className="mt-0.5 shrink-0">
|
||||
{item.status === 'uploading' && <Spinner />}
|
||||
{item.status === 'uploading' && <Upload className="size-4" aria-hidden="true" />}
|
||||
{item.status === 'waiting' && <Clock className="size-4 text-muted-foreground" aria-hidden="true" />}
|
||||
{item.status === 'done' && <Check className="size-4 text-green-600" aria-hidden="true" />}
|
||||
{item.status === 'failed' && <AlertCircle className="size-4 text-destructive" aria-hidden="true" />}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
|
||||
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroSlideAdminDto } from '@/features/hero/services/types';
|
||||
|
||||
const seedImage = (id: string, width = 1600, height = 1067): HeroImageDto => ({
|
||||
id,
|
||||
@@ -57,6 +57,7 @@ export const resetMockHero = (): void => {
|
||||
uploads = 0;
|
||||
uploadFailure = null;
|
||||
retried = [];
|
||||
focusRequests = [];
|
||||
recutting = new Set();
|
||||
};
|
||||
|
||||
@@ -79,6 +80,10 @@ export const getRetriedImages = (): string[] => retried;
|
||||
|
||||
export const getSavedHeroRequests = (): HeroSaveRequest[] => saved;
|
||||
|
||||
let focusRequests: { imageId: string; body: HeroFocusRequest }[] = [];
|
||||
/** The crops sent at once with PUT hero/images/{id}/focus (no save of the hero involved). */
|
||||
export const getFocusRequests = (): { imageId: string; body: HeroFocusRequest }[] => focusRequests;
|
||||
|
||||
export const failNextUpload = (failure: { status: number; error: string; message: string } | null): void => {
|
||||
uploadFailure = failure;
|
||||
};
|
||||
@@ -118,6 +123,17 @@ export const heroHandlers = [
|
||||
return HttpResponse.json(hero);
|
||||
}),
|
||||
|
||||
http.put(`${API_BASE}/api/v1/hero/images/:id/focus`, async ({ params, request }) => {
|
||||
const id = String(params.id);
|
||||
const body = (await request.json()) as HeroFocusRequest;
|
||||
focusRequests.push({ imageId: id, body });
|
||||
const current = images[id] ?? hero.slides.find((s) => s.imageId === id)?.image ?? seedImage(id);
|
||||
images[id] = { ...current, focus: body.focus, wideFocus: body.wide ?? null, tallFocus: body.tall ?? null, processing: true };
|
||||
recutting.add(id);
|
||||
hero = { ...hero, slides: hero.slides.map((s) => (s.imageId === id ? { ...s, image: images[id] } : s)) };
|
||||
return HttpResponse.json(images[id]);
|
||||
}),
|
||||
|
||||
http.get(`${API_BASE}/api/v1/hero/images/limits`, () =>
|
||||
HttpResponse.json({ formats: ['JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'WebP', 'AVIF'], maxUploadBytes: 10 * 1024 * 1024, maxMegapixels: 64 }),
|
||||
),
|
||||
|
||||
@@ -5,7 +5,8 @@ import { http, HttpResponse } from 'msw';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||
import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
|
||||
import { emptyHero, failNextUpload, finishMockRecut, getRetriedImages, getFocusRequests,
|
||||
getSavedHeroRequests, resetMockHero, setMockHero, slide } from '@/features/hero/mocks/handlers';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
const T = { timeout: 10000 };
|
||||
@@ -42,16 +43,16 @@ describe('Hero page', () => {
|
||||
expect(screen.queryByTestId('hero-slide-0-focus')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows how many photos are ready, with an accessible progress bar, and hides it when all are ready', async () => {
|
||||
it('counts only the photos that are being prepared, not the finished ones, with an accessible progress bar, and hides it when all are ready', async () => {
|
||||
const waiting = (n: number) => ({ ...slide(n), image: { ...slide(n).image, variants: [], src: '', processing: true } });
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), waiting(2), waiting(3)] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/1 van 3|1 of 3/);
|
||||
const bar = screen.getByRole('progressbar');
|
||||
expect(bar).toHaveAttribute('aria-valuenow', '1');
|
||||
expect(bar).toHaveAttribute('aria-valuemax', '3');
|
||||
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/0 van 2|0 of 2/);
|
||||
const bar = screen.getByRole('progressbar', { name: /verwerkt|processed|Verwerking|Processing/i });
|
||||
expect(bar).toHaveAttribute('aria-valuenow', '30');
|
||||
expect(bar).toHaveAttribute('aria-valuemax', '100');
|
||||
});
|
||||
|
||||
it('keeps unsaved edits when the background refresh brings a finished photo', async () => {
|
||||
@@ -280,7 +281,8 @@ describe('Focus dialog', () => {
|
||||
expect(screen.getByTestId('focus-y')).toHaveValue(50);
|
||||
expect(screen.getByTestId('focus-preview-wide')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('focus-preview-tall')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('focus-apply-hint')).toHaveTextContent(/pas nadat je de hero opslaat|only takes effect when you save the hero/);
|
||||
// A crop is processed at once: there is no note about saving the hero.
|
||||
expect(screen.queryByTestId('focus-apply-hint')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('moves the point with the keyboard', async () => {
|
||||
@@ -294,7 +296,7 @@ describe('Focus dialog', () => {
|
||||
expect(screen.getByTestId('focus-y')).toHaveValue(55);
|
||||
});
|
||||
|
||||
it('keeps a change locally until the hero is saved, then sends it with the save', async () => {
|
||||
it('applies a new crop at once, without saving the hero, and the photo shows it is being processed', async () => {
|
||||
await open();
|
||||
|
||||
fireEvent.change(screen.getByTestId('focus-x'), { target: { value: '30' } });
|
||||
@@ -306,42 +308,28 @@ describe('Focus dialog', () => {
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
|
||||
expect(getSavedHeroRequests()).toHaveLength(0);
|
||||
expect(screen.getByTestId('hero-slide-0-focus-pending')).toBeInTheDocument();
|
||||
|
||||
// Reopening shows the pending values.
|
||||
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
|
||||
expect(screen.getByTestId('focus-x')).toHaveValue(30);
|
||||
await userEvent.click(screen.getByTestId('focus-target-tall'));
|
||||
expect(screen.getByTestId('focus-override-tall')).toBeChecked();
|
||||
expect(screen.getByTestId('focus-x')).toHaveValue(80);
|
||||
expect(screen.getByTestId('focus-zoom')).toHaveValue('2');
|
||||
await userEvent.click(screen.getByTestId('focus-cancel'));
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toEqual([
|
||||
{
|
||||
await waitFor(() => expect(getFocusRequests()).toHaveLength(1));
|
||||
expect(getFocusRequests()[0]).toEqual({
|
||||
imageId: '10000000-0000-0000-0000-000000000001',
|
||||
focus: { x: 0.3, y: 0.5, zoom: 1 },
|
||||
wide: null,
|
||||
tall: { x: 0.8, y: 0.5, zoom: 2 },
|
||||
},
|
||||
]);
|
||||
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument());
|
||||
body: { focus: { x: 0.3, y: 0.5, zoom: 1 }, wide: null, tall: { x: 0.8, y: 0.5, zoom: 2 } },
|
||||
});
|
||||
expect(getSavedHeroRequests()).toHaveLength(0);
|
||||
expect(await screen.findByTestId('hero-slide-0-recut', {}, T)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-save')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('sends no focus edits when nothing was changed', async () => {
|
||||
it('sends no crop with the save: the hero save carries only the content', async () => {
|
||||
await open();
|
||||
await userEvent.click(screen.getByTestId('focus-cancel'));
|
||||
// Something else changed, so there is something to save; the cancelled focus is not part of it.
|
||||
await userEvent.type(screen.getByTestId('hero-tagline'), 'x');
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toEqual([]);
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toBeUndefined();
|
||||
expect(getFocusRequests()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('goes back to the general point when the own setting is switched off', async () => {
|
||||
@@ -693,9 +681,15 @@ describe('Order by dragging, wording and calm waiting', () => {
|
||||
expect(box).toHaveClass('hero-shimmer');
|
||||
expect(box).toHaveTextContent(/Wordt verwerkt|Processing/);
|
||||
}
|
||||
expect(screen.getByTestId('hero-slide-0-processing-step')).toHaveTextContent('3/16');
|
||||
expect(screen.getByTestId('hero-slide-1-processing-queued')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-2-processing-queued')).toBeInTheDocument();
|
||||
// The same pattern everywhere: the same text and a bar, no step counts on the photo itself.
|
||||
for (const i of [0, 1, 2]) {
|
||||
expect(screen.getByTestId(`hero-slide-${i}-processing-progress-text`)).toHaveTextContent(/^(Wordt verwerkt…|Processing…)$/);
|
||||
expect(screen.getByTestId(`hero-slide-${i}-processing-progress-bar`)).toHaveAttribute('role', 'progressbar');
|
||||
}
|
||||
expect(screen.getByTestId('hero-slide-0-processing')).not.toHaveTextContent('3/16');
|
||||
expect(Number(screen.getByTestId('hero-slide-0-processing-progress-bar').getAttribute('aria-valuenow'))).toBeGreaterThan(
|
||||
Number(screen.getByTestId('hero-slide-1-processing-progress-bar').getAttribute('aria-valuenow')),
|
||||
);
|
||||
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/0 van 3|0 of 3/);
|
||||
});
|
||||
|
||||
@@ -731,9 +725,14 @@ describe('Progress of a photo that is being prepared', () => {
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(await screen.findByTestId('hero-processing-current', {}, T)).toHaveTextContent(/foto 2 van 3.*stap 7 van 16|photo 2 of 3.*step 7 of 16/);
|
||||
expect(screen.getByTestId('hero-slide-1-processing-step')).toHaveTextContent('7/16');
|
||||
expect(screen.queryByTestId('hero-slide-2-processing-step')).not.toBeInTheDocument();
|
||||
// One overall bar (upload and processing together) and no step counts anywhere.
|
||||
const bar = await screen.findByTestId('hero-processing-bar-bar', {}, T);
|
||||
expect(bar).toHaveAttribute('role', 'progressbar');
|
||||
expect(screen.getByTestId('hero-processing-bar-text')).toHaveTextContent(/^(Wordt verwerkt…|Processing…)$/);
|
||||
expect(screen.queryByTestId('hero-processing-current')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-1-processing')).not.toHaveTextContent('7/16');
|
||||
expect(Number(bar.getAttribute('aria-valuenow'))).toBeGreaterThan(0);
|
||||
expect(Number(bar.getAttribute('aria-valuenow'))).toBeLessThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -743,28 +742,42 @@ describe('A changed focus point makes a new crop in the background', () => {
|
||||
resetMockHero();
|
||||
});
|
||||
|
||||
it('shows that the new crop is not live yet (old picture underneath), counts it in the total, and clears it when done', async () => {
|
||||
it('shows the new crop as processing right away (old picture underneath, text and a 0-100% bar, no spinner), outside the upload counter, and clears it when done', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
|
||||
fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '25' } });
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
const recut = await screen.findByTestId('hero-slide-0-recut', {}, T);
|
||||
expect(recut).toHaveClass('hero-shimmer');
|
||||
expect(recut.querySelector('img')).not.toBeNull();
|
||||
expect(recut).toHaveTextContent(/Nieuwe uitsnede|new crop/);
|
||||
expect(screen.getByTestId('hero-processing-count')).toHaveTextContent(/1 van 2|1 of 2/);
|
||||
expect(screen.getByTestId('hero-slide-0-recut-progress-text')).toHaveTextContent(/^(Wordt verwerkt…|Processing…)$/);
|
||||
const bar = screen.getByTestId('hero-slide-0-recut-progress-bar');
|
||||
expect(bar).toHaveAttribute('aria-valuemin', '0');
|
||||
expect(bar).toHaveAttribute('aria-valuemax', '100');
|
||||
expect(bar).toHaveAttribute('aria-valuenow', '0');
|
||||
expect(screen.getByTestId('hero-slide-0-recut-progress-percent')).toHaveTextContent('0%');
|
||||
expect(recut.querySelector('.animate-spin')).toBeNull();
|
||||
expect(screen.queryByTestId('hero-processing-count')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-slide-1-recut')).not.toBeInTheDocument();
|
||||
|
||||
// The server finishes the new crop; the page asks again by itself.
|
||||
finishMockRecut();
|
||||
await waitFor(() => expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument(), { timeout: 12000 });
|
||||
expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-0-focus')).toBeEnabled();
|
||||
}, 25000);
|
||||
|
||||
it('shows the step of a new crop as a percentage on the bar', async () => {
|
||||
const busy = { ...slide(1), image: { ...slide(1).image, processing: true, renderDone: 4, renderTotal: 16 } };
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [busy] });
|
||||
|
||||
await openPage();
|
||||
|
||||
await screen.findByTestId('hero-slide-0-recut', {}, T);
|
||||
expect(screen.getByTestId('hero-slide-0-recut-progress-bar')).toHaveAttribute('aria-valuenow', '25');
|
||||
expect(screen.getByTestId('hero-slide-0-recut-progress-percent')).toHaveTextContent('25%');
|
||||
});
|
||||
|
||||
it('shows a failed new crop with the retry', async () => {
|
||||
const failed = { ...slide(1), image: { ...slide(1).image, processing: true, failed: true } };
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [failed] });
|
||||
@@ -915,6 +928,43 @@ describe('Each photo shows by itself when its processing is finished', () => {
|
||||
expect(screen.queryByText(/stond al|already/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('counts only the newly uploaded photos, not the whole hero: one new photo next to eight finished ones is 0 of 1', async () => {
|
||||
const id = '70000000-0000-0000-0000-000000000021';
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [1, 2, 3, 4, 5, 6, 7, 8].map((n) => slide(n)) });
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(id), { status: 201 })),
|
||||
http.get(`${API_BASE}/api/v1/hero/images/${id}`, () => HttpResponse.json(cutting(id))),
|
||||
);
|
||||
await openPage();
|
||||
|
||||
await userEvent.upload(screen.getByTestId('hero-upload'), jpg('nieuw.jpg'));
|
||||
|
||||
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 1|0 of 1)/);
|
||||
expect(screen.getByTestId('hero-processing-bar-bar')).toHaveAttribute('aria-valuemax', '100');
|
||||
});
|
||||
|
||||
it('counts a batch of uploads as that batch only (0 of x), and the next upload starts a new count', async () => {
|
||||
const ids = ['70000000-0000-0000-0000-000000000031', '70000000-0000-0000-0000-000000000032', '70000000-0000-0000-0000-000000000033'];
|
||||
let n = 0;
|
||||
const finished = new Set<string>();
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/hero/images`, () => HttpResponse.json(cutting(ids[n++]), { status: 201 })),
|
||||
...ids.map((id) => http.get(`${API_BASE}/api/v1/hero/images/${id}`, () => HttpResponse.json(finished.has(id) ? ready(id) : cutting(id)))),
|
||||
);
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
|
||||
await openPage();
|
||||
|
||||
await userEvent.upload(screen.getByTestId('hero-upload'), [jpg('a.jpg'), jpg('b.jpg')]);
|
||||
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 2|0 of 2)/);
|
||||
|
||||
finished.add(ids[0]);
|
||||
finished.add(ids[1]);
|
||||
await waitFor(() => expect(screen.queryByTestId('hero-processing')).not.toBeInTheDocument(), { timeout: 12000 });
|
||||
|
||||
await userEvent.upload(screen.getByTestId('hero-upload'), jpg('c.jpg'));
|
||||
expect(await screen.findByTestId('hero-processing-count', {}, T)).toHaveTextContent(/^(0 van 1|0 of 1)/);
|
||||
}, 40000);
|
||||
|
||||
it('finishes photo by photo: the first one can be worked on while the second is still busy, and the total at the top follows', async () => {
|
||||
const ids = ['70000000-0000-0000-0000-000000000011', '70000000-0000-0000-0000-000000000012'];
|
||||
let n = 0;
|
||||
@@ -961,47 +1011,39 @@ describe('The picture of a slide is the way to adjust its crop', () => {
|
||||
expect(await screen.findByTestId('focus-dialog', {}, T)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the new crop on the thumbnail right after Apply, with the not-saved note, and drops it when the change is undone', async () => {
|
||||
it('starts processing the photo right after Apply, with no unsaved note', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
|
||||
await openPage();
|
||||
expect(screen.queryByTestId('hero-slide-0-focus-local')).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-slide-0-focus'));
|
||||
fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '10' } });
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('focus-dialog')).not.toBeInTheDocument());
|
||||
const local = await screen.findByTestId('hero-slide-0-focus-local', {}, T);
|
||||
expect(local.getAttribute('src')).toContain('full-1280.webp');
|
||||
expect(local.style.left).toMatch(/^-?\d/);
|
||||
expect(screen.getByTestId('hero-slide-0-focus-pending')).toHaveTextContent(/Focus gewijzigd, nog niet opgeslagen|Focus changed, not saved yet/);
|
||||
expect(await screen.findByTestId('hero-slide-0-recut', {}, T)).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-slide-0-focus-pending')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('follows the whole chain: Apply, Save sends the focus, the new crop is made (animation), then it is finished', async () => {
|
||||
it('follows the whole chain: Apply sends the crop at once, the new crop is made (bar), then it is finished, and the hero never needed saving', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-slide-1-focus'));
|
||||
fireEvent.change(await screen.findByTestId('focus-y', {}, T), { target: { value: '20' } });
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
await screen.findByTestId('hero-slide-1-focus-pending', {}, T);
|
||||
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].imageFocus).toEqual([
|
||||
expect.objectContaining({ imageId: '10000000-0000-0000-0000-000000000002', focus: { x: 0.5, y: 0.2, zoom: 1 } }),
|
||||
]);
|
||||
// Saved: the note of the unsaved change is gone and the new crop is being made, with the animation, on that photo only.
|
||||
await waitFor(() => expect(getFocusRequests()).toHaveLength(1));
|
||||
expect(getFocusRequests()[0].body.focus).toEqual({ x: 0.5, y: 0.2, zoom: 1 });
|
||||
const recut = await screen.findByTestId('hero-slide-1-recut', {}, T);
|
||||
expect(recut).toHaveClass('hero-shimmer');
|
||||
expect(recut).toHaveTextContent(/Nieuwe uitsnede wordt gemaakt|Making the new crop/);
|
||||
expect(screen.queryByTestId('hero-slide-1-focus-pending')).not.toBeInTheDocument();
|
||||
expect(within(recut).getByTestId('hero-slide-1-recut-progress-bar')).toHaveAttribute('role', 'progressbar');
|
||||
expect(screen.queryByTestId('hero-slide-0-recut')).not.toBeInTheDocument();
|
||||
expect(getSavedHeroRequests()).toHaveLength(0);
|
||||
|
||||
finishMockRecut();
|
||||
expect(await screen.findByTestId('hero-slide-1-done-text', {}, { timeout: 12000 })).toHaveTextContent(/Verwerking afgerond|Processing finished/);
|
||||
expect(screen.queryByTestId('hero-slide-1-recut')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-1-focus').tagName).toBe('BUTTON');
|
||||
expect(screen.getByTestId('hero-save')).toBeDisabled();
|
||||
}, 30000);
|
||||
});
|
||||
|
||||
@@ -1042,7 +1084,7 @@ describe('The Save button', () => {
|
||||
expect(screen.queryByTestId('hero-unsaved')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is greyed out again when a change is undone, and active for a focus change that is applied', async () => {
|
||||
it('is greyed out again when a change is undone, and stays greyed out for a crop (it needs no save)', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
|
||||
await openPage();
|
||||
const save = screen.getByTestId('hero-save');
|
||||
@@ -1056,7 +1098,8 @@ describe('The Save button', () => {
|
||||
fireEvent.change(await screen.findByTestId('focus-x', {}, T), { target: { value: '15' } });
|
||||
await userEvent.click(screen.getByTestId('focus-save'));
|
||||
|
||||
await waitFor(() => expect(save).toBeEnabled());
|
||||
await waitFor(() => expect(getFocusRequests()).toHaveLength(1));
|
||||
expect(save).toBeDisabled();
|
||||
});
|
||||
|
||||
it('stays active when saving failed, so it can be tried again', async () => {
|
||||
@@ -1170,4 +1213,117 @@ describe('Tabs Content and Images', () => {
|
||||
expect(bar).toHaveClass('-mx-6', 'bg-background', 'border-t');
|
||||
expect(bar.className).not.toMatch(/bg-background\//);
|
||||
});
|
||||
|
||||
it('sticks flush with the bottom of the viewport: undoes the padding of the scrolling area, no bottom margin, and the page cancels the padding below it', async () => {
|
||||
await openPage();
|
||||
|
||||
const bar = screen.getByTestId('hero-save-bar');
|
||||
// <main> has p-6 and a sticky box measures from the content edge, so -bottom-6 (measured in Chrome) puts it on the screen edge.
|
||||
expect(bar).toHaveClass('sticky', '-bottom-6');
|
||||
expect(bar.className).not.toMatch(/(^|\s)-?mb-/);
|
||||
expect(bar.className).not.toMatch(/(^|\s)(translate|bottom-)/);
|
||||
expect(screen.getByTestId('hero-page')).toHaveClass('-mb-6');
|
||||
// Room around the button: more padding above and below than before.
|
||||
expect(bar).toHaveClass('pt-4', 'gap-4');
|
||||
expect(bar.style.paddingBottom).toContain('1rem');
|
||||
expect(screen.getByTestId('hero-form').className).not.toMatch(/pb-/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('Add a slide with a photo from the library or an upload', () => {
|
||||
beforeEach(() => {
|
||||
resetMockHero();
|
||||
});
|
||||
|
||||
const libraryPhoto = (n: number, over: Record<string, unknown> = {}) => ({
|
||||
id: `hero:10000000-0000-0000-0000-00000000000${n}`,
|
||||
module: 'hero',
|
||||
bytes: 1000,
|
||||
width: 1600,
|
||||
height: 1067,
|
||||
createdAt: '2026-11-1' + n + 'T10:00:00Z',
|
||||
thumbnailUrl: `/media/hero/0123456789abcdef/wide-480.webp`,
|
||||
uses: [],
|
||||
originalFileName: `foto-${n}.jpg`,
|
||||
unusedSince: null,
|
||||
deletedAt: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
it('lists the library photos (also those in no slide, never the trash) and adds the chosen one as a new slide, ready to save', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
|
||||
server.use(
|
||||
http.get('*/media-library/photos', () =>
|
||||
HttpResponse.json({ photos: [libraryPhoto(3), libraryPhoto(2), libraryPhoto(1, { uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }] }), libraryPhoto(9, { module: 'gallery', id: 'gallery:x' })], modules: ['hero'] }),
|
||||
),
|
||||
http.get(`${API_BASE}/api/v1/hero/images/10000000-0000-0000-0000-000000000002`, () => HttpResponse.json(slide(2).image)),
|
||||
);
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-upload-button'));
|
||||
|
||||
const dialog = await screen.findByTestId('library-picker', {}, T);
|
||||
const radios = await within(dialog).findAllByRole('radio');
|
||||
expect(radios.map((r) => r.getAttribute('aria-label'))).toEqual(['foto-3.jpg', 'foto-2.jpg', 'foto-1.jpg']);
|
||||
expect(within(dialog).queryAllByRole('radio', { checked: true })).toHaveLength(0);
|
||||
expect(within(dialog).getByTestId('picker-upload-button')).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(within(dialog).getByRole('radio', { name: 'foto-2.jpg' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(screen.getByTestId('hero-save')).toBeEnabled());
|
||||
await userEvent.type(screen.getByTestId('hero-slide-1-alt'), 'Beschrijving');
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000001', '10000000-0000-0000-0000-000000000002']);
|
||||
expect(screen.queryByTestId('hero-slide-0-library')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('lets a photo that is already in another slide be chosen again as a new slide (same photo, separate slide)', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1), slide(2)] });
|
||||
server.use(
|
||||
http.get('*/media-library/photos', () => HttpResponse.json({ photos: [libraryPhoto(2, { uses: [{ module: 'hero', kind: 'slide', position: 2, active: true }] }), libraryPhoto(1)], modules: ['hero'] })),
|
||||
);
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-upload-button'));
|
||||
const dialog = await screen.findByTestId('library-picker', {}, T);
|
||||
|
||||
await userEvent.click(await within(dialog).findByRole('radio', { name: 'foto-2.jpg' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument());
|
||||
await userEvent.type(screen.getByTestId('hero-slide-2-alt'), 'Beschrijving');
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000001', '10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']);
|
||||
});
|
||||
|
||||
it('tells that the crop is shared when the same photo is in more than one slide', async () => {
|
||||
const one = slide(1);
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [one, { ...slide(2), imageId: one.imageId, image: one.image }, slide(3)] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(screen.getByTestId('hero-slide-0-shared-crop')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-1-shared-crop')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-slide-2-shared-crop')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
|
||||
server.use(http.get('*/media-library/photos', () => HttpResponse.json({ photos: [], modules: ['hero'] })));
|
||||
await openPage();
|
||||
await userEvent.click(screen.getByTestId('hero-upload-button'));
|
||||
const dialog = await screen.findByTestId('library-picker', {}, T);
|
||||
expect(await within(dialog).findByTestId('picker-empty')).toBeInTheDocument();
|
||||
|
||||
await userEvent.upload(within(dialog).getByTestId('picker-file'), new File([new Uint8Array(100)], 'nieuw.jpg', { type: 'image/jpeg' }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('library-picker')).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(screen.getByTestId('hero-save')).toBeEnabled());
|
||||
await userEvent.type(screen.getByTestId('hero-slide-1-alt'), 'Beschrijving');
|
||||
await userEvent.click(screen.getByTestId('hero-save'));
|
||||
await waitFor(() => expect(getSavedHeroRequests()).toHaveLength(1));
|
||||
expect(getSavedHeroRequests()[0].slides).toHaveLength(2);
|
||||
expect(getSavedHeroRequests()[0].slides[1].imageId).not.toBe('10000000-0000-0000-0000-000000000001');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useQueries } from '@tanstack/react-query';
|
||||
import { useQueries, useQueryClient } from '@tanstack/react-query';
|
||||
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -17,6 +17,7 @@ import { FieldError } from '@/components/ui/FieldError';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { FocusDialog } from '../components/FocusDialog';
|
||||
import { LibraryPickerDialog } from '../components/LibraryPickerDialog';
|
||||
import { CropThumbnail } from '../components/CropThumbnail';
|
||||
import { DoneStatus, PhotoPlaceholder, ProcessingStatus, RecutThumbnail, Spinner } from '../components/ProcessingStatus';
|
||||
import { SlideSwitch } from '../components/SlideSwitch';
|
||||
@@ -26,7 +27,7 @@ import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
|
||||
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
|
||||
import { mediaUrl } from '../lib/media';
|
||||
import { heroFormSchema, type HeroFormData } from '../schemas/hero';
|
||||
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
|
||||
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useSetHeroImageFocus, useUploadHeroImage } from '../services/hooks';
|
||||
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
|
||||
|
||||
const textareaClass =
|
||||
@@ -44,7 +45,7 @@ function toForm(hero: HeroAdminDto): HeroFormData {
|
||||
};
|
||||
}
|
||||
|
||||
function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusRequest>): HeroSaveRequest {
|
||||
function toRequest(values: HeroFormData): HeroSaveRequest {
|
||||
return {
|
||||
title: values.title,
|
||||
tagline: values.tagline || null,
|
||||
@@ -52,7 +53,6 @@ function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusReq
|
||||
display: values.display,
|
||||
buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''),
|
||||
slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })),
|
||||
imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export function HeroPage() {
|
||||
const { data: hero, isLoading, isError, refetch } = useHero();
|
||||
|
||||
return (
|
||||
<div className="space-y-6" data-testid="hero-page">
|
||||
<div className="-mb-6 space-y-6" data-testid="hero-page">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-2xl font-semibold" data-testid="hero-title">{t('hero.title')}</h1>
|
||||
{hero && (
|
||||
@@ -148,8 +148,14 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const limits = useHeroUploadLimits().data;
|
||||
const [localImages, setLocalImages] = useState<Record<string, HeroImageDto>>({});
|
||||
const [focusImageId, setFocusImageId] = useState<string | null>(null);
|
||||
// Changed focus points are kept here until the hero is saved: they are sent with the save and dropped when the page is left.
|
||||
const [focusEdits, setFocusEdits] = useState<Record<string, HeroFocusRequest>>({});
|
||||
// A new crop is applied at once (no save needed): the server cuts the new variants in the background.
|
||||
const setImageFocus = useSetHeroImageFocus();
|
||||
// The photos of the current upload batch, for the counter "x of y processed": only the photos uploaded together, not
|
||||
// every photo of the hero. A new batch starts when the previous one is finished.
|
||||
const [batch, setBatch] = useState<string[]>([]);
|
||||
const [recutIds, setRecutIds] = useState<string[]>([]);
|
||||
// The slide (by position) whose photo is being chosen from the library.
|
||||
const [adding, setAdding] = useState(false);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const {
|
||||
@@ -243,20 +249,19 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
}
|
||||
}, [images, slides.fields]);
|
||||
|
||||
// A focus change counts as unsaved only while it differs from what is saved (applying the old point again is no change).
|
||||
const samePoint = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
||||
const hasPendingFocus = Object.entries(focusEdits).some(([imageId, edit]) => {
|
||||
const saved = images[imageId];
|
||||
return !saved || !samePoint(saved.focus, edit.focus) || !samePoint(saved.wideFocus, edit.wide) || !samePoint(saved.tallFocus, edit.tall);
|
||||
});
|
||||
// The form is compared with the last saved state (react-hook-form keeps it), so a change that is undone no longer counts.
|
||||
// Photos still being prepared on the server and the background refresh are not changes of the administrator.
|
||||
const hasUnsaved = isDirty || hasPendingFocus;
|
||||
const hasUnsaved = isDirty;
|
||||
const contentChanged = Object.keys(dirtyFields).some((key) => key !== 'slides');
|
||||
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean)) || hasPendingFocus;
|
||||
const imagesChanged = Boolean(dirtyFields.slides?.some?.(Boolean));
|
||||
const contentInvalid = Object.keys(errors).some((key) => key !== 'slides');
|
||||
const imagesInvalid = Boolean(errors.slides);
|
||||
const busyCount = slides.fields.filter((f) => images[f.imageId]?.processing).length;
|
||||
// The counter above the form covers the current upload batch only. After a reload (no batch known) it covers the photos that
|
||||
// are still being prepared. A new crop is shown on its own photo, not in this counter.
|
||||
const statusImages = (batch.length > 0 ? batch.map((id) => images[id]) : slides.fields.map((f) => images[f.imageId]).filter((i) => i?.processing && !recutIds.includes(i.id))).filter(
|
||||
(image): image is HeroImageDto => image !== undefined,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!hasUnsaved) return undefined;
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
@@ -266,10 +271,34 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [hasUnsaved]);
|
||||
|
||||
// The image as the dialog shows it: the saved one with a not yet saved change of its focus applied.
|
||||
const withPendingFocus = (image: HeroImageDto | null): HeroImageDto | null => {
|
||||
const edit = image ? focusEdits[image.id] : undefined;
|
||||
return image && edit ? { ...image, focus: edit.focus, wideFocus: edit.wide, tallFocus: edit.tall } : image;
|
||||
// "Add slide": a photo chosen from the library, or uploaded in the picker (it then also lands in the library), becomes a NEW
|
||||
// slide with exactly that one photo. A slide's photo is never changed afterwards: remove the slide and add another.
|
||||
const queryClient = useQueryClient();
|
||||
const addSlideWithPhoto = async (imageId: string, uploaded?: HeroImageDto) => {
|
||||
try {
|
||||
const image: HeroImageDto = uploaded ?? ((await queryClient.fetchQuery(heroImageQuery(imageId))) as HeroImageDto);
|
||||
setLocalImages((cur) => ({ ...cur, [image.id]: image }));
|
||||
if (uploaded && image.processing) setBatch((cur) => (cur.some((id) => images[id]?.processing) ? [...cur, image.id] : [image.id]));
|
||||
slides.append({ id: null, imageId: image.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
|
||||
setAdding(false);
|
||||
} catch (error) {
|
||||
setServerError(serverMessage(error, t('errors.generic'), t('errors.network')));
|
||||
}
|
||||
};
|
||||
|
||||
// A new crop goes to the server at once; the page then shows the photo as processing until the new variants are ready.
|
||||
const applyFocus = (imageId: string, request: HeroFocusRequest) => {
|
||||
setServerError(null);
|
||||
setImageFocus.mutate(
|
||||
{ imageId, request },
|
||||
{
|
||||
onSuccess: (image) => {
|
||||
setLocalImages((current) => ({ ...current, [image.id]: image }));
|
||||
setRecutIds((current) => [...new Set([...current, image.id])]);
|
||||
},
|
||||
onError: (error) => setServerError(serverMessage(error, t('errors.generic'), t('errors.network'))),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
// Up to this many files go to the host at the same time; the variants are cut in the background, so an upload itself
|
||||
@@ -292,11 +321,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const results: (HeroImageDto | 'failed' | undefined)[] = new Array<HeroImageDto | 'failed' | undefined>(files.length).fill(undefined);
|
||||
let flushed = 0;
|
||||
let cursor = 0;
|
||||
let inBatch = batch.some((id) => images[id]?.processing);
|
||||
const flush = () => {
|
||||
while (flushed < files.length && results[flushed] !== undefined) {
|
||||
const result = results[flushed];
|
||||
if (result && result !== 'failed') {
|
||||
setLocalImages((current) => ({ ...current, [result.id]: result }));
|
||||
const joins = inBatch;
|
||||
setBatch((current) => (joins ? [...current, result.id] : [result.id]));
|
||||
inBatch = true;
|
||||
// Ready at once (the same photo was already in the CMS): the same note as after a photo that took a while.
|
||||
if (!result.processing) markDone(result.id);
|
||||
slides.append({ id: null, imageId: result.id, alt: '', decorative: false, isActive: true }, { shouldFocus: false });
|
||||
@@ -358,8 +391,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const onSubmit = async (values: HeroFormData) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
const savedHero = await save.mutateAsync(toRequest(values, focusEdits));
|
||||
setFocusEdits({});
|
||||
const savedHero = await save.mutateAsync(toRequest(values));
|
||||
// What was just saved is the new starting point: nothing is unsaved any more.
|
||||
reset(toForm(savedHero));
|
||||
toast.success(t('hero.savedToast'));
|
||||
@@ -388,8 +420,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
const heroErrors = errors;
|
||||
|
||||
return (
|
||||
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8 pb-4" noValidate data-testid="hero-form">
|
||||
<ProcessingStatus images={slides.fields.map((f) => images[f.imageId]).filter((image): image is HeroImageDto => image !== undefined)} />
|
||||
<form onSubmit={(event) => void handleSubmit(onSubmit, onInvalid)(event)} className="space-y-8" noValidate data-testid="hero-form">
|
||||
<ProcessingStatus
|
||||
images={statusImages}
|
||||
pendingUploads={uploads.filter((u) => u.status === 'waiting' || u.status === 'uploading').map((u) => (u.status === 'uploading' ? 'uploading' : 'waiting'))}
|
||||
/>
|
||||
<FormErrorBanner error={serverError !== null ? { message: serverError } : null} onDismiss={() => setServerError(null)} />
|
||||
|
||||
<HeroTabs
|
||||
@@ -493,7 +528,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
data-testid="hero-upload"
|
||||
onChange={(event) => void onFiles(event.target.files)}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="hero-upload-button">
|
||||
<Button type="button" variant="outline" disabled={uploading} onClick={() => setAdding(true)} data-testid="hero-upload-button">
|
||||
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
|
||||
{uploading ? t('hero.slides.uploading') : t('hero.slides.add')}
|
||||
</Button>
|
||||
@@ -530,7 +565,6 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<CropThumbnail
|
||||
image={image}
|
||||
savedSrc={thumbnail(image)}
|
||||
edit={focusEdits[field.imageId]}
|
||||
onClick={() => setFocusImageId(field.imageId)}
|
||||
testId={`hero-slide-${index}-focus`}
|
||||
/>
|
||||
@@ -538,6 +572,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<div className="flex h-20 w-28 items-center justify-center rounded bg-muted text-xs">?</div>
|
||||
)}
|
||||
<DoneStatus done={Boolean(image && justDone[image.id] && !image.processing)} slideNumber={index + 1} testId={`hero-slide-${index}-done`} />
|
||||
{watchedSlides.some((other, otherIndex) => otherIndex !== index && other?.imageId === field.imageId) && (
|
||||
<p className="max-w-28 text-xs text-muted-foreground" data-testid={`hero-slide-${index}-shared-crop`}>
|
||||
{t('hero.library.sharedCrop')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
|
||||
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
|
||||
@@ -581,11 +620,15 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
</div>
|
||||
|
||||
<UnsavedChangesGuard dirty={hasUnsaved} />
|
||||
{/* Full width of the content area (no gap at the sides or below), opaque, with a clear top edge and a shadow; the
|
||||
bottom padding keeps clear of the home bar of a phone. */}
|
||||
{/* Flush with the bottom of the viewport and the full width of the content area, fully opaque so nothing shows
|
||||
through or below it, with a clear top edge and a shadow. A sticky box measures its offset from the CONTENT
|
||||
edge of the scrolling area (<main> has p-6), so "bottom: 0" would stop 24px above the screen edge and let
|
||||
content show below the bar (measured in Chrome); -bottom-6 undoes that padding. The page root cancels the same
|
||||
padding (-mb-6), so at the end of the page the bar is still at the very bottom and the last content is never
|
||||
hidden behind it. The bottom padding clears the home bar of a phone. */}
|
||||
<div
|
||||
className="sticky bottom-0 z-20 -mx-6 -mb-6 flex flex-wrap items-center justify-end gap-3 border-t bg-background px-6 pt-3 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
|
||||
style={{ paddingBottom: 'calc(0.75rem + env(safe-area-inset-bottom))' }}
|
||||
className="sticky -bottom-6 z-20 -mx-6 flex flex-wrap items-center justify-end gap-4 border-t bg-background px-6 pt-4 shadow-[0_-4px_8px_-4px_rgba(0,0,0,0.15)]"
|
||||
style={{ paddingBottom: 'calc(1rem + env(safe-area-inset-bottom))' }}
|
||||
data-testid="hero-save-bar"
|
||||
>
|
||||
<div role="status" aria-live="polite" className="min-h-5 flex-1 text-sm" data-testid="hero-unsaved-region">
|
||||
@@ -601,7 +644,7 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
disabled={save.isPending || !hasUnsaved}
|
||||
aria-disabled={save.isPending || !hasUnsaved}
|
||||
aria-busy={save.isPending}
|
||||
className={hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : undefined}
|
||||
className={`min-w-28 ${hasUnsaved && !save.isPending ? 'ring-2 ring-primary ring-offset-2' : ''}`}
|
||||
data-testid="hero-save"
|
||||
>
|
||||
{save.isPending ? (
|
||||
@@ -615,9 +658,16 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<LibraryPickerDialog
|
||||
open={adding}
|
||||
onOpenChange={setAdding}
|
||||
onChoose={(imageId, uploaded) => void addSlideWithPhoto(imageId, uploaded)}
|
||||
maxUploadBytes={limits?.maxUploadBytes ?? MAX_UPLOAD_BYTES}
|
||||
limitsText={limits ? t('hero.slides.limits', { formats: limits.formats.join(', '), size: Math.round(limits.maxUploadBytes / (1024 * 1024)), megapixels: limits.maxMegapixels }) : undefined}
|
||||
/>
|
||||
<FocusDialog
|
||||
image={withPendingFocus(focusImageId ? images[focusImageId] ?? null : null)}
|
||||
onApply={(imageId, edit) => setFocusEdits((current) => ({ ...current, [imageId]: edit }))}
|
||||
image={focusImageId ? images[focusImageId] ?? null : null}
|
||||
onApply={applyFocus}
|
||||
onClose={() => setFocusImageId(null)}
|
||||
/>
|
||||
</form>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { HeroAdminDto, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types';
|
||||
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest, HeroUploadLimits } from './types';
|
||||
|
||||
export const HERO_KEY = ['hero'];
|
||||
|
||||
@@ -68,3 +68,18 @@ export const heroImageQuery = (imageId: string) => ({
|
||||
refetchInterval: (query: { state: { data?: HeroImageDto } }) => (query.state.data?.processing ? 5000 : false),
|
||||
refetchIntervalInBackground: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* A new crop for an image, applied at once without saving the hero (Bryan, 2026-11-17): the server cuts the new variants
|
||||
* in the background and the image switches to them when they are complete. The answer is the image, now processing.
|
||||
*/
|
||||
export function useSetHeroImageFocus() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<HeroImageDto, Error, { imageId: string; request: HeroFocusRequest }>({
|
||||
mutationFn: ({ imageId, request }) => api.put<HeroImageDto>(`/api/v1/hero/images/${imageId}/focus`, request),
|
||||
onSuccess: (image) => {
|
||||
queryClient.setQueryData(['hero', 'image', image.id], image);
|
||||
return queryClient.invalidateQueries({ queryKey: HERO_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ export interface HeroSaveRequest {
|
||||
buttons: HeroButtonDto[];
|
||||
slides: HeroSlideRequest[];
|
||||
/** Changed focus points of images; they take effect with this save. */
|
||||
imageFocus: HeroImageFocusRequest[];
|
||||
imageFocus?: HeroImageFocusRequest[];
|
||||
}
|
||||
|
||||
export interface HeroImageFocusRequest extends HeroFocusRequest {
|
||||
|
||||
@@ -12,28 +12,26 @@ export interface BulkAction {
|
||||
run: () => void;
|
||||
}
|
||||
|
||||
interface BulkActionBarProps {
|
||||
export interface BulkActionBarProps {
|
||||
count: number;
|
||||
actions: readonly BulkAction[];
|
||||
onClear: () => void;
|
||||
/** Extra text on the bar, for example the bytes the selection takes. */
|
||||
/** Extra text next to the count, for example the bytes the selection takes. */
|
||||
summary?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions on the selected photos. The actions are data, so more of them (tags, move) can be added without touching
|
||||
* the list. It shows nothing while nothing is selected.
|
||||
* The actions on the selected photos: the count, a way to clear the selection and the actions. It sits in the header of
|
||||
* the photo list (see <c>PhotoSelectionList</c>), which is the one shared place for it. The actions are data, so more of
|
||||
* them (tags, move) can be added without touching the list. While nothing is selected it is an empty box of the same height.
|
||||
*/
|
||||
export function BulkActionBar({ count, actions, onClear, summary }: BulkActionBarProps) {
|
||||
const { t } = useTranslation();
|
||||
if (count === 0) return null;
|
||||
// The bar keeps its height while nothing is selected (an invisible placeholder), so the photos never jump when the first
|
||||
// photo is selected.
|
||||
if (count === 0) return <div aria-hidden="true" className="h-9 flex-1" data-testid="bulk-action-bar-placeholder" />;
|
||||
return (
|
||||
<div
|
||||
role="toolbar"
|
||||
aria-label={t('media.bulk.label')}
|
||||
data-testid="bulk-action-bar"
|
||||
className="sticky bottom-0 z-10 flex flex-wrap items-center gap-3 rounded-md border bg-background px-4 py-2 shadow-md"
|
||||
>
|
||||
<div role="toolbar" aria-label={t('media.bulk.label')} data-testid="bulk-action-bar" className="flex flex-1 flex-wrap items-center gap-3">
|
||||
<span className="text-sm font-medium" data-testid="bulk-count">
|
||||
{t('media.bulk.selected', { count })}
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CheckboxField } from '@/components/ui/checkbox';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import { selectAll, type Selection } from '../lib/selection';
|
||||
import { toPhotoItem } from '../lib/toPhotoItem';
|
||||
import { useCleanupPreview } from '../services/hooks';
|
||||
import { DeleteDialog } from './DeleteDialog';
|
||||
import { PhotoSelectionList } from './PhotoSelectionList';
|
||||
|
||||
const DEFAULT_DAYS = 7;
|
||||
const MIN_DAYS = 0;
|
||||
const MAX_DAYS = 365;
|
||||
|
||||
/**
|
||||
* "Clean up": the photos not used for the chosen number of days (by default 7; 0 = every unused photo now), by default only the unused ones, newest
|
||||
* first and all selected so single photos can be taken out. Confirming moves exactly the selected photos to the trash
|
||||
* (a photo in use asks for a second confirmation naming the places).
|
||||
*/
|
||||
export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [days, setDays] = useState(DEFAULT_DAYS);
|
||||
const [debouncedDays, setDebouncedDays] = useState(DEFAULT_DAYS);
|
||||
const [onlyUnused, setOnlyUnused] = useState(true);
|
||||
// Everything starts selected: the person only takes photos OUT. A new period or filter starts again with all in.
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(new Set());
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const preview = useCleanupPreview(debouncedDays, onlyUnused, open);
|
||||
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
|
||||
const changeDays = (value: number) => {
|
||||
setDays(value);
|
||||
clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => {
|
||||
setDebouncedDays(value);
|
||||
setExcluded(new Set());
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const photos = preview.data?.photos;
|
||||
const ids = useMemo(() => (photos ?? []).map((p) => p.id), [photos]);
|
||||
const selection = useMemo<Selection>(() => selectAll(ids.filter((id) => !excluded.has(id))), [ids, excluded]);
|
||||
const setSelection = (next: Selection) => setExcluded(new Set(ids.filter((id) => !next.has(id))));
|
||||
|
||||
const items = useMemo(() => (photos ?? []).map((p) => toPhotoItem(p, t)), [photos, t]);
|
||||
const selectedItems = useMemo(() => items.filter((item) => selection.has(item.id)), [items, selection]);
|
||||
const selectedBytes = (photos ?? []).filter((p) => selection.has(p.id)).reduce((sum, p) => sum + p.bytes, 0);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto" data-testid="cleanup-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('media.cleanup.title')}</DialogTitle>
|
||||
<DialogDescription>{t('media.cleanup.description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cleanup-days">{days === 0 ? t('media.cleanup.daysZero') : t('media.cleanup.days', { count: days })}</Label>
|
||||
<input
|
||||
id="cleanup-days"
|
||||
type="range"
|
||||
min={MIN_DAYS}
|
||||
max={MAX_DAYS}
|
||||
step={1}
|
||||
value={days}
|
||||
onChange={(event) => changeDays(Number(event.target.value))}
|
||||
className="w-full accent-primary"
|
||||
data-testid="cleanup-days"
|
||||
/>
|
||||
{days === 0 && (
|
||||
<p className="text-xs text-muted-foreground" data-testid="cleanup-zero-note">
|
||||
{t('media.cleanup.zeroNote')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<CheckboxField
|
||||
checked={onlyUnused}
|
||||
onChange={(event) => {
|
||||
setOnlyUnused(event.target.checked);
|
||||
setExcluded(new Set());
|
||||
}}
|
||||
label={t('media.cleanup.onlyUnused')}
|
||||
data-testid="cleanup-only-unused"
|
||||
/>
|
||||
|
||||
<p className="rounded-md border border-dashed p-3 text-sm text-muted-foreground" data-testid="cleanup-preview-note">
|
||||
{t('media.cleanup.trashNote')}
|
||||
</p>
|
||||
|
||||
{preview.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
{preview.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
|
||||
{preview.data && (
|
||||
<>
|
||||
<p className="text-sm" data-testid="cleanup-summary">
|
||||
{t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })}
|
||||
</p>
|
||||
<PhotoSelectionList
|
||||
items={items}
|
||||
selection={selection}
|
||||
onSelectionChange={setSelection}
|
||||
layout="compact"
|
||||
bulk={{
|
||||
actions: [],
|
||||
onClear: () => setSelection(new Set()),
|
||||
summary: t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) }),
|
||||
}}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="destructive" disabled={selectedItems.length === 0} onClick={() => setDeleting(true)} data-testid="cleanup-confirm">
|
||||
{t('media.cleanup.confirm', { count: selectedItems.length })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<DeleteDialog
|
||||
open={deleting}
|
||||
onOpenChange={setDeleting}
|
||||
items={selectedItems}
|
||||
onDone={() => {
|
||||
setExcluded(new Set());
|
||||
onOpenChange(false);
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { usageLabel } from '../lib/usageLabel';
|
||||
import { useTrashPhotos } from '../services/hooks';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
interface DeleteDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
items: readonly PhotoItem[];
|
||||
/** Called with the ids that were moved to the trash. */
|
||||
onDone?: (trashedIds: string[]) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting means "to the trash" (recoverable for a while). A photo that is in use needs a SECOND confirmation that names
|
||||
* the places that lose it (decision 10). A photo that went wrong is reported; the others are done.
|
||||
*/
|
||||
export function DeleteDialog({ open, onOpenChange, items, onDone }: DeleteDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent data-testid="delete-dialog">{open && <DeleteDialogBody items={items} onClose={() => onOpenChange(false)} onDone={onDone} />}</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteDialogBody({ items, onClose, onDone }: { items: readonly PhotoItem[]; onClose: () => void; onDone?: (trashedIds: string[]) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const trash = useTrashPhotos();
|
||||
const [step, setStep] = useState<'first' | 'second'>('first');
|
||||
const [failed, setFailed] = useState(0);
|
||||
const inUse = items.filter((item) => item.uses.length > 0);
|
||||
|
||||
const submit = () => {
|
||||
trash.mutate(
|
||||
{ ids: items.map((i) => i.id), confirmedInUse: inUse.length > 0 },
|
||||
{
|
||||
onSuccess: ({ results }) => {
|
||||
const trashed = results.filter((r) => r.status === 'trashed').map((r) => r.id);
|
||||
onDone?.(trashed);
|
||||
const problems = results.length - trashed.length;
|
||||
if (problems === 0) onClose();
|
||||
else setFailed(problems);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const onConfirm = () => {
|
||||
if (inUse.length > 0 && step === 'first') setStep('second');
|
||||
else submit();
|
||||
};
|
||||
|
||||
if (failed > 0) {
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('media.delete.title')}</DialogTitle>
|
||||
<DialogDescription role="alert" data-testid="delete-partial">
|
||||
{t('media.delete.partial', { count: failed })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={onClose} data-testid="delete-close">
|
||||
{t('media.delete.close')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{step === 'first' ? t('media.delete.title') : t('media.delete.secondTitle')}</DialogTitle>
|
||||
<DialogDescription data-testid="delete-text">
|
||||
{step === 'first' ? t('media.delete.confirm', { count: items.length }) : t('media.delete.secondText', { count: inUse.length })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{step === 'first' && inUse.length > 0 && (
|
||||
<p className="text-sm font-medium" data-testid="delete-inuse-count">
|
||||
{t('media.delete.inUseCount', { count: inUse.length })}
|
||||
</p>
|
||||
)}
|
||||
{step === 'second' && (
|
||||
<ul className="grid max-h-60 grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4" data-testid="delete-places">
|
||||
{inUse.map((item) => {
|
||||
const places = item.uses.map((use) => usageLabel(t, use)).join('; ');
|
||||
return (
|
||||
<li key={item.id} className="overflow-hidden rounded-md border bg-card" title={`${item.name}: ${places}`} data-testid={`delete-place-${item.id}`}>
|
||||
{item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className="aspect-square w-full object-cover" />
|
||||
) : (
|
||||
<span className="flex aspect-square w-full items-center justify-center bg-muted text-[10px] text-muted-foreground">{t('media.list.noThumbnail')}</span>
|
||||
)}
|
||||
<div className="min-w-0 px-1.5 py-1">
|
||||
<p className="truncate text-xs font-medium">{item.name}</p>
|
||||
<p className="truncate text-[11px] leading-tight">{places}</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{trash.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={trash.isPending} data-testid="delete-cancel">
|
||||
{t('media.delete.cancel')}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={onConfirm} disabled={trash.isPending || items.length === 0} data-testid="delete-confirm">
|
||||
{step === 'second' ? t('media.delete.confirmSecond') : t('media.delete.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useState } from 'react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import i18n from '@/i18n/config';
|
||||
import { validateUpload } from '../lib/validateUpload';
|
||||
import { ImagePicker } from './ImagePicker';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
const photo = (id: string, name: string): PhotoItem => ({ id, name, bytes: 1, createdAt: '2026-11-17T10:00:00Z', uses: [], thumbnailUrl: null });
|
||||
const items = [photo('a', 'Foto A'), photo('b', 'Foto B')];
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
function Harness({ onUpload, initial = null }: { onUpload?: (file: File) => Promise<PhotoItem>; initial?: string | null }) {
|
||||
const [value, setValue] = useState<string | null>(initial);
|
||||
return <ImagePicker items={items} value={value} onChange={setValue} onUpload={onUpload} maxUploadBytes={10 * MB} label="Afbeelding van slide 1" limitsText="JPEG, PNG, WebP, AVIF" />;
|
||||
}
|
||||
|
||||
const file = (name = 'x.jpg', type = 'image/jpeg', size = 1000) => new File([new Uint8Array(size)], name, { type });
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('nl');
|
||||
});
|
||||
|
||||
describe('validateUpload', () => {
|
||||
it.each([
|
||||
[{ type: 'image/jpeg', size: 100 }, null],
|
||||
[{ type: '', size: 100 }, null],
|
||||
[{ type: 'application/pdf', size: 100 }, 'notAnImage'],
|
||||
[{ type: 'image/png', size: 10 * MB + 1 }, 'tooLarge'],
|
||||
[{ type: 'image/png', size: 10 * MB }, null],
|
||||
])('%j gives %s', (f, expected) => expect(validateUpload(f, 10 * MB)).toBe(expected));
|
||||
});
|
||||
|
||||
describe('ImagePicker', () => {
|
||||
it('chooses a library photo as a radio group, with the arrow keys', async () => {
|
||||
render(<Harness initial="a" />);
|
||||
|
||||
expect(screen.getByRole('radiogroup', { name: 'Afbeelding van slide 1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('radio', { name: 'Foto A' })).toBeChecked();
|
||||
screen.getByRole('radio', { name: 'Foto A' }).focus();
|
||||
await userEvent.keyboard('{ArrowRight}');
|
||||
|
||||
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('has no upload button when the module gives no upload', () => {
|
||||
render(<Harness />);
|
||||
|
||||
expect(screen.queryByTestId('picker-upload-button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uploads on the spot, then chooses the new photo', async () => {
|
||||
const upload = vi.fn().mockResolvedValue(photo('c', 'Nieuwe foto'));
|
||||
render(<Harness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file());
|
||||
|
||||
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
|
||||
await waitFor(() => expect(screen.getByTestId('picker-upload-button')).toHaveTextContent('Afbeelding uploaden'));
|
||||
expect(screen.queryByTestId('picker-problem')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refuses what the host would refuse, without calling the upload', async () => {
|
||||
const upload = vi.fn();
|
||||
render(<Harness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file('x.pdf', 'application/pdf'), { applyAccept: false });
|
||||
expect(screen.getByTestId('picker-problem')).toHaveTextContent('geen afbeelding');
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file('big.jpg', 'image/jpeg', 10 * MB + 1));
|
||||
expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB');
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a message when the upload fails and keeps the current choice', async () => {
|
||||
render(<Harness onUpload={() => Promise.reject(new Error('nope'))} initial="b" />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file());
|
||||
|
||||
expect(await screen.findByTestId('picker-problem')).toHaveTextContent('niet gelukt');
|
||||
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('says so when the library is empty', () => {
|
||||
render(<ImagePicker items={[]} value={null} onChange={vi.fn()} maxUploadBytes={MB} label="x" />);
|
||||
|
||||
expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto');
|
||||
});
|
||||
});
|
||||
|
||||
function MultiHarness({ onUpload, initial = [] }: { onUpload?: (file: File) => Promise<PhotoItem>; initial?: string[] }) {
|
||||
const [values, setValues] = useState<string[]>(initial);
|
||||
return (
|
||||
<>
|
||||
<ImagePicker mode="multiple" items={items} values={values} onChangeMany={setValues} onUpload={onUpload} maxUploadBytes={10 * MB} label="Foto's van de galerij" />
|
||||
<output data-testid="chosen">{values.join(',')}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ImagePicker in multiple mode', () => {
|
||||
it('chooses several photos with checkboxes, in the order chosen, and unchooses one', async () => {
|
||||
render(<MultiHarness />);
|
||||
|
||||
expect(screen.getByRole('group', { name: "Foto's van de galerij" })).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' }));
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto A' }));
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('b,a');
|
||||
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' }));
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('a');
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto B' })).not.toBeChecked();
|
||||
});
|
||||
|
||||
it('uploads several files on the spot and adds them all to the choice', async () => {
|
||||
let n = 0;
|
||||
const upload = vi.fn().mockImplementation(async () => photo(`new${++n}`, `Nieuw ${n}`));
|
||||
render(<MultiHarness onUpload={upload} initial={['a']} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), [file('1.jpg'), file('2.jpg')]);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('chosen')).toHaveTextContent('a,new1,new2'));
|
||||
expect(upload).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByTestId('picker-file')).toHaveAttribute('multiple');
|
||||
});
|
||||
|
||||
it('stops at a file the host would refuse and keeps what was chosen', async () => {
|
||||
const upload = vi.fn().mockResolvedValue(photo('new1', 'Nieuw'));
|
||||
render(<MultiHarness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), [file('ok.jpg'), file('big.jpg', 'image/jpeg', 10 * MB + 1), file('later.jpg')]);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB'));
|
||||
expect(upload).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('new1');
|
||||
});
|
||||
|
||||
it('single mode still takes one file only and has no multiple attribute', () => {
|
||||
render(<Harness onUpload={vi.fn()} />);
|
||||
|
||||
expect(screen.getByTestId('picker-file')).not.toHaveAttribute('multiple');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useId, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ImagePlus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { validateUpload } from '../lib/validateUpload';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
interface ImagePickerCommon {
|
||||
/** The photos of the library to choose from, newest first. */
|
||||
items: readonly PhotoItem[];
|
||||
/**
|
||||
* Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own
|
||||
* upload and background processing); the picker only shows the state and chooses the result. Without it there is no
|
||||
* upload button.
|
||||
*/
|
||||
onUpload?: (file: File) => Promise<PhotoItem>;
|
||||
/** The largest file the host accepts, in bytes. */
|
||||
maxUploadBytes: number;
|
||||
/** A short line about formats and limits, shown under the buttons. */
|
||||
limitsText?: string;
|
||||
/** Accessible name of the group (what the image is for, for example "Image of slide 2"). */
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One photo: a radio group (the hero slides use this). */
|
||||
export interface ImagePickerSingleProps extends ImagePickerCommon {
|
||||
mode?: 'single';
|
||||
/** The id of the chosen photo, or null. */
|
||||
value: string | null;
|
||||
onChange: (id: string) => void;
|
||||
}
|
||||
|
||||
/** Several photos: checkboxes (ready for the gallery). Uploaded photos are added to the choice. */
|
||||
export interface ImagePickerMultipleProps extends ImagePickerCommon {
|
||||
mode: 'multiple';
|
||||
/** The ids of the chosen photos, in the order they were chosen. */
|
||||
values: readonly string[];
|
||||
onChangeMany: (ids: string[]) => void;
|
||||
}
|
||||
|
||||
export type ImagePickerProps = ImagePickerSingleProps | ImagePickerMultipleProps;
|
||||
|
||||
/**
|
||||
* "Choose an image or upload one", one component for every module that needs an image. In <c>single</c> mode the library
|
||||
* photos are a radio group (arrow keys move and choose); in <c>multiple</c> mode they are checkboxes and several photos can
|
||||
* be chosen. An upload button adds the new photo to the library and chooses it at once. The picker holds no data of its own
|
||||
* and calls nothing by itself: the module passes the list and the upload.
|
||||
*/
|
||||
export function ImagePicker(props: ImagePickerProps) {
|
||||
const { items, onUpload, maxUploadBytes, limitsText, label } = props;
|
||||
const multiple = props.mode === 'multiple';
|
||||
const { t } = useTranslation();
|
||||
const groupName = useId();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
|
||||
const chosen = (id: string) => (props.mode === 'multiple' ? props.values.includes(id) : props.value === id);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
if (props.mode === 'multiple') {
|
||||
props.onChangeMany(props.values.includes(id) ? props.values.filter((v) => v !== id) : [...props.values, id]);
|
||||
} else {
|
||||
props.onChange(id);
|
||||
}
|
||||
};
|
||||
|
||||
const upload = async (files: FileList | null) => {
|
||||
const list = Array.from(files ?? []);
|
||||
if (list.length === 0 || !onUpload || uploading) return;
|
||||
setProblem(null);
|
||||
setUploading(true);
|
||||
let current = props.mode === 'multiple' ? [...props.values] : [];
|
||||
try {
|
||||
for (const file of multiple ? list : list.slice(0, 1)) {
|
||||
const refused = validateUpload(file, maxUploadBytes);
|
||||
if (refused) {
|
||||
setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage'));
|
||||
break;
|
||||
}
|
||||
|
||||
const photo = await onUpload(file);
|
||||
if (props.mode === 'multiple') {
|
||||
current = [...current, photo.id];
|
||||
props.onChangeMany(current);
|
||||
} else {
|
||||
props.onChange(photo.id);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setProblem(t('media.picker.failed'));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (fileInput.current) fileInput.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-testid="image-picker">
|
||||
{onUpload && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple={multiple}
|
||||
className="sr-only"
|
||||
aria-label={t('media.picker.upload')}
|
||||
data-testid="picker-file"
|
||||
onChange={(event) => void upload(event.target.files)}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="picker-upload-button">
|
||||
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
|
||||
{uploading ? t('media.picker.uploading') : t('media.picker.upload')}
|
||||
</Button>
|
||||
{limitsText && <p className="text-xs text-muted-foreground">{limitsText}</p>}
|
||||
</div>
|
||||
)}
|
||||
{problem && (
|
||||
<p role="alert" className="text-sm text-destructive" data-testid="picker-problem">
|
||||
{problem}
|
||||
</p>
|
||||
)}
|
||||
{items.length === 0 ? (
|
||||
<p className="rounded-md border border-dashed p-4 text-sm text-muted-foreground" data-testid="picker-empty">
|
||||
{t('media.picker.empty')}
|
||||
</p>
|
||||
) : (
|
||||
<div role={multiple ? 'group' : 'radiogroup'} aria-label={label} className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="picker-grid">
|
||||
{items.map((item) => (
|
||||
<label key={item.id} className="relative block cursor-pointer" data-testid={`picker-item-${item.id}`}>
|
||||
<input
|
||||
type={multiple ? 'checkbox' : 'radio'}
|
||||
name={groupName}
|
||||
value={item.id}
|
||||
checked={chosen(item.id)}
|
||||
onChange={() => toggle(item.id)}
|
||||
aria-label={item.name}
|
||||
className="peer sr-only"
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'block overflow-hidden rounded-md border-2 border-transparent bg-muted transition-colors',
|
||||
'peer-checked:border-primary peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-focus-visible:ring-offset-2 ring-offset-background',
|
||||
'hover:border-muted-foreground forced-colors:peer-checked:border-[Highlight]',
|
||||
)}
|
||||
>
|
||||
{item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className="aspect-[3/2] w-full object-cover" />
|
||||
) : (
|
||||
<span className="flex aspect-[3/2] items-center justify-center text-xs text-muted-foreground">{t('media.list.noThumbnail')}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="mt-1 block truncate text-xs">{item.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import i18n from '@/i18n/config';
|
||||
import { emptySelection, type Selection } from '../lib/selection';
|
||||
import { BulkActionBar } from './BulkActionBar';
|
||||
import { PhotoSelectionList, type PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
const items: PhotoItem[] = [
|
||||
@@ -14,16 +13,39 @@ const items: PhotoItem[] = [
|
||||
{ id: 'p4', name: 'Foto 4', bytes: 10, createdAt: '2026-11-14T10:00:00Z', uses: [] },
|
||||
];
|
||||
|
||||
function Harness({ disabled }: { disabled?: (item: PhotoItem) => boolean }) {
|
||||
function Harness({ disabled, layout }: { disabled?: (item: PhotoItem) => boolean; layout?: 'list' | 'tiles' | 'compact' }) {
|
||||
const [selection, setSelection] = useState<Selection>(emptySelection);
|
||||
return (
|
||||
<>
|
||||
<PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} isDisabled={disabled} />
|
||||
<BulkActionBar count={selection.size} actions={[{ id: 'delete', label: 'Verwijderen', destructive: true, run: vi.fn() }]} onClear={() => setSelection(emptySelection)} />
|
||||
<PhotoSelectionList
|
||||
items={items}
|
||||
selection={selection}
|
||||
onSelectionChange={setSelection}
|
||||
isDisabled={disabled}
|
||||
layout={layout}
|
||||
bulk={{ actions: [{ id: 'delete', label: 'Verwijderen', destructive: true, run: vi.fn() }], onClear: () => setSelection(emptySelection) }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function PhotoSelectionListWithLink() {
|
||||
const [selection, setSelection] = useState<Selection>(emptySelection);
|
||||
return (
|
||||
<PhotoSelectionList
|
||||
layout="tiles"
|
||||
items={items}
|
||||
selection={selection}
|
||||
onSelectionChange={setSelection}
|
||||
renderUse={(_use, label) => (
|
||||
<a href="#x" onClick={(event) => event.preventDefault()} data-testid="use-link-p1">
|
||||
{label}
|
||||
</a>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('nl');
|
||||
});
|
||||
@@ -119,3 +141,76 @@ describe('BulkActionBar', () => {
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the bulk bar is part of the list header, above the photos', () => {
|
||||
it('sits in the sticky opaque header before the first photo, and only once something is selected', async () => {
|
||||
render(<Harness />);
|
||||
const header = screen.getByTestId('photo-list-header');
|
||||
|
||||
expect(header).toHaveClass('sticky', 'bg-background');
|
||||
expect(header.className).not.toMatch(/bg-background\//);
|
||||
expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 2' }));
|
||||
|
||||
const bar = screen.getByTestId('bulk-action-bar');
|
||||
expect(header).toContainElement(bar);
|
||||
const first = screen.getByTestId('photo-row-p1');
|
||||
expect(bar.compareDocumentPosition(first) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
it('keeps the header the same height before and after the first selection, so nothing jumps', async () => {
|
||||
render(<Harness />);
|
||||
const placeholder = screen.getByTestId('bulk-action-bar-placeholder');
|
||||
expect(placeholder).toHaveClass('h-9');
|
||||
expect(placeholder).toHaveAttribute('aria-hidden', 'true');
|
||||
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 2' }));
|
||||
|
||||
expect(screen.queryByTestId('bulk-action-bar-placeholder')).not.toBeInTheDocument();
|
||||
// The buttons of the bar are small (h-9), the same as the placeholder.
|
||||
expect(screen.getByTestId('bulk-clear')).toHaveClass('h-9');
|
||||
});
|
||||
|
||||
it('selects a tile by clicking the photo, but not when a link on the tile is clicked', async () => {
|
||||
render(
|
||||
<>
|
||||
<PhotoSelectionListWithLink />
|
||||
</>,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-row-p2'));
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked();
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-row-p2'));
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 2' })).not.toBeChecked();
|
||||
|
||||
await userEvent.click(screen.getAllByTestId('use-link-p1')[0]!);
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
|
||||
|
||||
// The box itself toggles once (the click on the box does not also toggle the tile).
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 3' }));
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 3' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('compact layout: small tiles, the whole tile selects, name and usage stay available', async () => {
|
||||
render(<Harness layout="compact" />);
|
||||
|
||||
expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'compact');
|
||||
expect(screen.getByTestId('photo-chip-p1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('photo-usage-p1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('photo-row-p1')).toHaveAttribute('title', expect.stringContaining('Foto 1'));
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-row-p1'));
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 1' })).toBeChecked();
|
||||
await userEvent.click(screen.getByTestId('photo-select-all'));
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 3' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('does not select a disabled tile by clicking it', async () => {
|
||||
render(<Harness layout="tiles" disabled={(item) => item.id === 'p1'} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-row-p1'));
|
||||
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useRef } from 'react';
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import { BulkActionBar, type BulkActionBarProps } from './BulkActionBar';
|
||||
import { usageLabel } from '../lib/usageLabel';
|
||||
import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection';
|
||||
|
||||
export interface PhotoUse {
|
||||
@@ -19,6 +23,10 @@ export interface PhotoItem {
|
||||
bytes: number;
|
||||
createdAt: string;
|
||||
uses: readonly PhotoUse[];
|
||||
/** When the photo was last detached from where it was used (null: never used). */
|
||||
unusedSince?: string | null;
|
||||
/** When the photo went to the trash (only in the trash view). */
|
||||
deletedAt?: string | null;
|
||||
}
|
||||
|
||||
interface PhotoSelectionListProps {
|
||||
@@ -27,24 +35,19 @@ interface PhotoSelectionListProps {
|
||||
onSelectionChange: (selection: Selection) => void;
|
||||
/** Photos that cannot be selected (for example in use during a clean-up). */
|
||||
isDisabled?: (item: PhotoItem) => boolean;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number, language: string) {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${units[unit]}`;
|
||||
/** How a use is shown (the page makes it a router link to the module). Default: the plain label. */
|
||||
renderUse?: (use: PhotoUse, label: string) => ReactNode;
|
||||
/** The actions on the selection. They appear in the header of the list, above the photos, once something is selected. */
|
||||
bulk?: Omit<BulkActionBarProps, 'count'>;
|
||||
/** A list of rows (default), a grid of tiles with big thumbnails, or a dense grid of small thumbnails ('compact', for the dialogs). Everything works in all. */
|
||||
layout?: 'list' | 'tiles' | 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos with a checkbox each: click or Space to toggle, shift-click for a range, a "select all" box in the header
|
||||
* (with the in-between state), and a live announcement of the count. One component for the library and the clean-up.
|
||||
*/
|
||||
export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled }: PhotoSelectionListProps) {
|
||||
export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled, renderUse, bulk, layout = 'list' }: PhotoSelectionListProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const anchor = useRef<string | null>(null);
|
||||
const selectable = items.filter((item) => !isDisabled?.(item));
|
||||
@@ -57,12 +60,6 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
anchor.current = id;
|
||||
};
|
||||
|
||||
const usageLabel = (use: PhotoUse) => {
|
||||
const place = t(`media.use.${use.kind}`, { defaultValue: use.kind });
|
||||
const where = use.position ? `${place} ${use.position}` : place;
|
||||
return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`;
|
||||
};
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<p className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground" data-testid="photo-list-empty">
|
||||
@@ -73,7 +70,10 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
|
||||
return (
|
||||
<div data-testid="photo-selection-list">
|
||||
<div className="flex items-center gap-3 border-b px-2 py-2">
|
||||
{/* The header of the list: select all, the count and the actions. Sticky and opaque so it stays in view above long
|
||||
lists without anything showing through. A sticky box measures from the content edge of the scrolling area, which
|
||||
has p-6 (the page and the dialogs), so -top-6 puts it on the edge. */}
|
||||
<div className="sticky -top-6 z-10 flex flex-wrap items-center gap-3 border-b bg-background px-2 py-2" data-testid="photo-list-header">
|
||||
<Checkbox
|
||||
aria-label={t('media.list.selectAll')}
|
||||
data-testid="photo-select-all"
|
||||
@@ -83,16 +83,29 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
onChange={() => onSelectionChange(state === 'all' ? new Set() : selectAll(selectableIds))}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">{t('media.list.selectAll')}</span>
|
||||
{bulk && <BulkActionBar count={selection.size} actions={bulk.actions} onClear={bulk.onClear} summary={bulk.summary} />}
|
||||
<span className="sr-only" role="status" aria-live="polite" data-testid="photo-selection-status">
|
||||
{t('media.bulk.selected', { count: selection.size })}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="divide-y" aria-label={t('media.list.label')}>
|
||||
<ul
|
||||
className={
|
||||
layout === 'tiles'
|
||||
? 'grid grid-cols-3 gap-3 py-3 sm:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
|
||||
: layout === 'compact'
|
||||
? 'grid grid-cols-3 gap-2 py-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8'
|
||||
: 'divide-y'
|
||||
}
|
||||
aria-label={t('media.list.label')}
|
||||
data-layout={layout}
|
||||
data-testid="photo-items"
|
||||
>
|
||||
{items.map((item) => {
|
||||
const disabled = isDisabled?.(item) ?? false;
|
||||
const labelId = `photo-${item.id}-label`;
|
||||
return (
|
||||
<li key={item.id} className="flex items-center gap-3 px-2 py-2" data-testid={`photo-row-${item.id}`}>
|
||||
const compact = layout === 'compact';
|
||||
const tiles = layout === 'tiles' || compact;
|
||||
const checkbox = (
|
||||
<Checkbox
|
||||
aria-labelledby={labelId}
|
||||
data-testid={`photo-select-${item.id}`}
|
||||
@@ -101,13 +114,45 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
onChange={() => undefined}
|
||||
onClick={(event) => onItemClick(item.id, event.currentTarget.checked, event.shiftKey)}
|
||||
/>
|
||||
{item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className="size-14 shrink-0 rounded object-cover" />
|
||||
);
|
||||
const thumbnail = item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className={cn('object-cover', compact ? 'aspect-square w-full' : tiles ? 'aspect-[3/2] w-full' : 'size-14 shrink-0 rounded')} />
|
||||
) : (
|
||||
<span className="flex size-14 shrink-0 items-center justify-center rounded bg-muted text-xs text-muted-foreground">
|
||||
<span className={cn('flex items-center justify-center bg-muted text-xs text-muted-foreground', compact ? 'aspect-square w-full text-[10px]' : tiles ? 'aspect-[3/2] w-full' : 'size-14 shrink-0 rounded')}>
|
||||
{t('media.list.noThumbnail')}
|
||||
</span>
|
||||
);
|
||||
// The compact tile keeps everything in the tooltip: the full name, date and size, and where the photo is used.
|
||||
const usageText = item.deletedAt
|
||||
? t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })
|
||||
: item.uses.length === 0
|
||||
? item.unusedSince
|
||||
? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) })
|
||||
: t('media.use.none')
|
||||
: item.uses.map((use) => usageLabel(t, use)).join('; ');
|
||||
const tooltip = `${item.name} (${dateFormat.format(new Date(item.createdAt))} · ${formatBytes(item.bytes, i18n.language)}): ${usageText}`;
|
||||
const details = compact ? (
|
||||
<div className="min-w-0">
|
||||
<p id={labelId} className="truncate text-xs font-medium" title={tooltip}>
|
||||
{item.name}
|
||||
</p>
|
||||
<p className="truncate text-[11px] leading-tight" data-testid={`photo-usage-${item.id}`} title={usageText}>
|
||||
{item.deletedAt || item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">{usageText}</span>
|
||||
) : (
|
||||
item.uses.map((use, index) => {
|
||||
const label = usageLabel(t, use);
|
||||
return (
|
||||
<span key={`${use.module}-${use.kind}-${use.position ?? index}`}>
|
||||
{index > 0 && '; '}
|
||||
{renderUse ? renderUse(use, label) : label}
|
||||
</span>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-w-0 flex-1">
|
||||
<p id={labelId} className="truncate text-sm font-medium">
|
||||
{item.name}
|
||||
@@ -116,13 +161,51 @@ export function PhotoSelectionList({ items, selection, onSelectionChange, isDisa
|
||||
{dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)}
|
||||
</p>
|
||||
<p className="text-xs" data-testid={`photo-usage-${item.id}`}>
|
||||
{item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t('media.use.none')}</span>
|
||||
{item.deletedAt ? (
|
||||
<span className="text-muted-foreground">{t('media.trash.since', { date: dateFormat.format(new Date(item.deletedAt)) })}</span>
|
||||
) : item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">
|
||||
{item.unusedSince ? t('media.use.noneSince', { date: dateFormat.format(new Date(item.unusedSince)) }) : t('media.use.none')}
|
||||
</span>
|
||||
) : (
|
||||
<span>{item.uses.map(usageLabel).join('; ')}</span>
|
||||
<span>
|
||||
{item.uses.map((use, index) => {
|
||||
const label = usageLabel(t, use);
|
||||
return (
|
||||
<span key={`${use.module}-${use.kind}-${use.position ?? index}`}>
|
||||
{index > 0 && '; '}
|
||||
{renderUse ? renderUse(use, label) : label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
return tiles ? (
|
||||
<li
|
||||
key={item.id}
|
||||
title={compact ? tooltip : undefined}
|
||||
className={cn('relative overflow-hidden rounded-md border bg-card', !disabled && 'cursor-pointer', selection.has(item.id) && 'ring-2 ring-primary')}
|
||||
data-testid={`photo-row-${item.id}`}
|
||||
// The whole tile selects (the box stays for keyboards and screen readers). A link or button on the tile
|
||||
// (the places a photo is used) does its own thing and does not select.
|
||||
onClick={(event) => {
|
||||
if (disabled || (event.target as HTMLElement).closest('a, button, input, label')) return;
|
||||
onItemClick(item.id, !selection.has(item.id), event.shiftKey);
|
||||
}}
|
||||
>
|
||||
{/* flex (not a block with an inline box inside): no line box, so no extra space under the checkbox and equal padding on all four sides */}
|
||||
<div className={cn('absolute z-[1] flex rounded bg-background/90 shadow-sm', compact ? 'left-1 top-1 p-0.5' : 'left-2 top-2 p-1')} data-testid={`photo-chip-${item.id}`}>{checkbox}</div>
|
||||
{thumbnail}
|
||||
<div className={compact ? 'px-1.5 py-1' : 'p-2'}>{details}</div>
|
||||
</li>
|
||||
) : (
|
||||
<li key={item.id} className="flex items-center gap-3 px-2 py-2" data-testid={`photo-row-${item.id}`}>
|
||||
{checkbox}
|
||||
{thumbnail}
|
||||
{details}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* THE progress pattern for everything that takes time in the library (upload, processing, a new crop): the same text
|
||||
* ("Wordt verwerkt…"), one bar from 0 to 100 percent and the percentage. No spinner and no step counts, so it reads the same
|
||||
* everywhere and works without motion. The caller decides what the percentage means (see <c>photoProgress</c>).
|
||||
*/
|
||||
export function ProcessingProgress({ percent, testId, compact = false, className }: { percent: number; testId: string; compact?: boolean; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
const value = Math.max(0, Math.min(100, Math.round(percent)));
|
||||
return (
|
||||
<div className={cn('space-y-1', compact ? 'text-xs' : 'text-sm', className)} data-testid={testId}>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span data-testid={`${testId}-text`}>{t('media.progress.working')}</span>
|
||||
<span className="tabular-nums" data-testid={`${testId}-percent`}>
|
||||
{value}%
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label={t('media.progress.working')}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={value}
|
||||
aria-valuetext={`${value}%`}
|
||||
className={cn('w-full overflow-hidden rounded bg-muted', compact ? 'h-1.5' : 'h-2')}
|
||||
data-testid={`${testId}-bar`}
|
||||
>
|
||||
<div className="h-full bg-primary transition-all motion-reduce:transition-none" style={{ width: `${value}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import { usePurgePhotos } from '../services/hooks';
|
||||
|
||||
interface PurgeDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** The photos to remove for good (ids as listed). Ignored when `all` is true. */
|
||||
ids: readonly string[];
|
||||
/** Empty the whole trash: the server removes everything that is in it. */
|
||||
all?: boolean;
|
||||
/** How many photos and how many bytes the confirmation names. */
|
||||
count: number;
|
||||
bytes: number;
|
||||
onDone?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removing photos from the trash for good cannot be undone: the confirmation says so and names the number of photos (and
|
||||
* their size when the whole trash is emptied). The server checks every photo again; a photo that went wrong is reported.
|
||||
*/
|
||||
export function PurgeDialog({ open, onOpenChange, ids, all = false, count, bytes, onDone }: PurgeDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent data-testid="purge-dialog">
|
||||
{open && <PurgeDialogBody ids={ids} all={all} count={count} bytes={bytes} onClose={() => onOpenChange(false)} onDone={onDone} />}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PurgeDialogBody({ ids, all, count, bytes, onClose, onDone }: { ids: readonly string[]; all: boolean; count: number; bytes: number; onClose: () => void; onDone?: () => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const purge = usePurgePhotos();
|
||||
const [failed, setFailed] = useState(0);
|
||||
|
||||
const submit = () =>
|
||||
purge.mutate(all ? { all: true } : { ids: [...ids] }, {
|
||||
onSuccess: ({ results }) => {
|
||||
const removed = results.filter((r) => r.status === 'purged').length;
|
||||
onDone?.();
|
||||
const problems = results.length - removed;
|
||||
if (problems === 0) onClose();
|
||||
else setFailed(problems);
|
||||
},
|
||||
});
|
||||
|
||||
if (failed > 0) {
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('media.purge.title')}</DialogTitle>
|
||||
<DialogDescription role="alert" data-testid="purge-partial">
|
||||
{t('media.purge.partial', { count: failed })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={onClose} data-testid="purge-close">
|
||||
{t('media.delete.close')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{all ? t('media.purge.emptyTitle') : t('media.purge.title')}</DialogTitle>
|
||||
<DialogDescription data-testid="purge-text">
|
||||
{all ? t('media.purge.confirmAll', { count, size: formatBytes(bytes, i18n.language) }) : t('media.purge.confirm', { count })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<p className="text-sm font-medium text-destructive" data-testid="purge-warning">
|
||||
{t('media.purge.irreversible')}
|
||||
</p>
|
||||
{purge.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={purge.isPending} data-testid="purge-cancel">
|
||||
{t('media.delete.cancel')}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={submit} disabled={purge.isPending || count === 0} data-testid="purge-confirm">
|
||||
{all ? t('media.purge.emptyConfirm') : t('media.purge.confirmButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import type { MediaStorageDto } from '../services/types';
|
||||
|
||||
/** Used space against the limit, with a warning at 80 percent and a clear message at the limit (colour plus text). */
|
||||
export function StorageMeter({ storage }: { storage: MediaStorageDto }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const hasLimit = storage.limitBytes > 0;
|
||||
const percent = hasLimit ? Math.min(100, Math.round((storage.usedBytes / storage.limitBytes) * 100)) : 0;
|
||||
const used = formatBytes(storage.usedBytes, i18n.language);
|
||||
|
||||
return (
|
||||
<section aria-labelledby="storage-title" className="space-y-2 rounded-md border p-4" data-testid="storage-meter" data-level={storage.level}>
|
||||
<h2 id="storage-title" className="text-sm font-medium">
|
||||
{t('media.storage.title')}
|
||||
</h2>
|
||||
<p className="text-sm" data-testid="storage-text">
|
||||
{hasLimit ? t('media.storage.usedOf', { used, limit: formatBytes(storage.limitBytes, i18n.language), percent }) : t('media.storage.used', { used })}
|
||||
</p>
|
||||
{hasLimit && (
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={percent}
|
||||
aria-labelledby="storage-title"
|
||||
className="h-2 w-full overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
<div
|
||||
className={cn('h-full', storage.level === 'full' ? 'bg-destructive' : storage.level === 'warning' ? 'bg-amber-500' : 'bg-primary')}
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{storage.level !== 'ok' && (
|
||||
<p role="alert" className={cn('text-sm font-medium', storage.level === 'full' ? 'text-destructive' : 'text-amber-700 dark:text-amber-400')} data-testid="storage-warning">
|
||||
{storage.level === 'full' ? t('media.storage.full') : t('media.storage.warning', { percent: storage.warningPercent })}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
|
||||
/** A size in bytes as a short, localised text (1,5 MB). */
|
||||
export function formatBytes(bytes: number, language: string): string {
|
||||
let value = Math.max(0, bytes);
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${UNITS[unit]}`;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
export type PhotoLayout = 'tiles' | 'list';
|
||||
|
||||
const KEY = 'slp.media.layout';
|
||||
|
||||
/** The layout this user chose last (tiles by default). Browser storage may be blocked, so every access is guarded. */
|
||||
export function readLayout(): PhotoLayout {
|
||||
try {
|
||||
return window.localStorage.getItem(KEY) === 'list' ? 'list' : 'tiles';
|
||||
} catch {
|
||||
return 'tiles';
|
||||
}
|
||||
}
|
||||
|
||||
/** The layout of the photos and a setter that remembers the choice per user (per browser). */
|
||||
export function useLayoutPreference(): [PhotoLayout, (layout: PhotoLayout) => void] {
|
||||
const [layout, setLayoutState] = useState<PhotoLayout>(readLayout);
|
||||
const setLayout = useCallback((next: PhotoLayout) => {
|
||||
setLayoutState(next);
|
||||
try {
|
||||
window.localStorage.setItem(KEY, next);
|
||||
} catch {
|
||||
// Blocked or full: the choice then only lasts for this visit.
|
||||
}
|
||||
}, []);
|
||||
return [layout, setLayout];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* One percentage for the whole chain of a photo that is added: the upload takes the first part, the background processing
|
||||
* (cutting the variants, step by step on the server) the rest. A new crop has no upload, so it runs over the full bar.
|
||||
*/
|
||||
export const UPLOAD_SHARE = 30;
|
||||
|
||||
export type UploadStage = 'waiting' | 'uploading' | 'done';
|
||||
|
||||
/** The processing part, 0 to 1, from the steps the server reports (no steps yet = not started). */
|
||||
export function renderFraction(renderDone?: number | null, renderTotal?: number | null): number {
|
||||
return renderTotal ? Math.max(0, Math.min(1, (renderDone ?? 0) / renderTotal)) : 0;
|
||||
}
|
||||
|
||||
/** Overall percentage (0-100) of a photo: its upload stage, then its processing steps. `ready` photos are at 100. */
|
||||
export function photoProgress(options: { ready?: boolean; upload?: UploadStage; renderDone?: number | null; renderTotal?: number | null }): number {
|
||||
if (options.ready) return 100;
|
||||
if (options.upload === 'waiting') return 0;
|
||||
if (options.upload === 'uploading') return UPLOAD_SHARE / 2;
|
||||
const processing = renderFraction(options.renderDone, options.renderTotal);
|
||||
// An upload that is done (or a photo that was uploaded before) has its upload part behind it.
|
||||
return options.upload === undefined && options.renderTotal == null && processing === 0 ? UPLOAD_SHARE : UPLOAD_SHARE + (100 - UPLOAD_SHARE) * processing;
|
||||
}
|
||||
|
||||
/** A new crop only has the processing part. */
|
||||
export function recutProgress(renderDone?: number | null, renderTotal?: number | null): number {
|
||||
return Math.round(renderFraction(renderDone, renderTotal) * 100);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { PhotoItem } from '../components/PhotoSelectionList';
|
||||
import type { MediaPhotoDto } from '../services/types';
|
||||
|
||||
/** The list shows the original file name; photos uploaded before it was stored get a neutral label (the size, assumption 21). */
|
||||
export function toPhotoItem(photo: MediaPhotoDto, t: TFunction): PhotoItem {
|
||||
return {
|
||||
id: photo.id,
|
||||
thumbnailUrl: photo.thumbnailUrl,
|
||||
name: photo.originalFileName ?? t('media.list.photoName', { width: photo.width, height: photo.height }),
|
||||
bytes: photo.bytes,
|
||||
createdAt: photo.createdAt,
|
||||
uses: photo.uses,
|
||||
unusedSince: photo.unusedSince,
|
||||
deletedAt: photo.deletedAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
export interface UsePlace {
|
||||
module: string;
|
||||
kind: string;
|
||||
position?: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
/** "Hero, slide 3" (with "(uit)" for a switched-off place). */
|
||||
export function usageLabel(t: TFunction, use: UsePlace): string {
|
||||
const place = t(`media.use.${use.kind}`, { defaultValue: use.kind });
|
||||
const where = use.position ? `${place} ${use.position}` : place;
|
||||
return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin route of the module that uses the photo (null when there is none). It is a ROUTER path: the router adds the
|
||||
* base path of the admin app (/admin) when it makes the link, so it never goes outside the admin.
|
||||
*/
|
||||
export function usageTarget(use: Pick<UsePlace, 'module'>): '/hero' | null {
|
||||
return use.module === 'hero' ? '/hero' : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hero screen opens on the tab it was left on; a use is a slide, so the link leaves it on the images tab.
|
||||
* (Storage can be blocked: then the screen simply opens on its own default.)
|
||||
*/
|
||||
export function rememberHeroImagesTab(): void {
|
||||
try {
|
||||
window.sessionStorage.setItem('cms-hero-tab', 'images');
|
||||
} catch {
|
||||
// Not available: nothing to remember.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export type UploadProblem = 'notAnImage' | 'tooLarge';
|
||||
|
||||
/**
|
||||
* The quick checks before a file is sent (the same two the hero upload makes): it must be an image and not over the
|
||||
* limit. The host checks everything again (signature, pixels, rate); this only spares sending a file it will refuse.
|
||||
*/
|
||||
export function validateUpload(file: { type: string; size: number }, maxBytes: number): UploadProblem | null {
|
||||
if (file.type !== '' && !file.type.startsWith('image/')) return 'notAnImage';
|
||||
if (file.size > maxBytes) return 'tooLarge';
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from '@/features/media/services/types';
|
||||
|
||||
const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString();
|
||||
|
||||
export const seedPhotos = (): MediaPhotoDto[] => [
|
||||
{
|
||||
id: 'hero:11111111-1111-1111-1111-111111111111',
|
||||
module: 'hero',
|
||||
bytes: 2_400_000,
|
||||
width: 3000,
|
||||
height: 2000,
|
||||
createdAt: daysAgo(1),
|
||||
thumbnailUrl: '/media/hero/0123456789abcdef/wide-480.webp',
|
||||
uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }],
|
||||
originalFileName: 'zomer.jpg',
|
||||
unusedSince: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: 'hero:22222222-2222-2222-2222-222222222222',
|
||||
module: 'hero',
|
||||
bytes: 1_800_000,
|
||||
width: 2400,
|
||||
height: 1600,
|
||||
createdAt: daysAgo(12),
|
||||
thumbnailUrl: null,
|
||||
uses: [],
|
||||
originalFileName: null,
|
||||
unusedSince: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: 'hero:33333333-3333-3333-3333-333333333333',
|
||||
module: 'hero',
|
||||
bytes: 900_000,
|
||||
width: 1600,
|
||||
height: 1067,
|
||||
createdAt: daysAgo(30),
|
||||
thumbnailUrl: null,
|
||||
uses: [{ module: 'hero', kind: 'slide', position: 2, active: false }],
|
||||
originalFileName: null,
|
||||
unusedSince: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
export const seedStorage = (): MediaStorageDto => ({ usedBytes: 100_000_000, limitBytes: 2_147_483_648, level: 'ok', warningPercent: 80 });
|
||||
|
||||
/** Stateless mocks of trash and restore: a photo in use is refused without the second confirmation. */
|
||||
export const mediaTrashHandlers = [
|
||||
http.get('*/media-library/trash', () => HttpResponse.json({ photos: [], modules: ['hero'] } satisfies MediaLibraryDto)),
|
||||
http.post('*/media-library/delete', async ({ request }) => {
|
||||
const body = (await request.json()) as MediaTrashRequest;
|
||||
const photos = seedPhotos();
|
||||
return HttpResponse.json({
|
||||
results: body.ids.map((id) => {
|
||||
const photo = photos.find((p) => p.id === id);
|
||||
if (!photo) return { id, status: 'notFound', uses: [] };
|
||||
if (photo.uses.length > 0 && !body.confirmedInUse) return { id, status: 'inUse', uses: photo.uses };
|
||||
return { id, status: 'trashed', uses: photo.uses };
|
||||
}),
|
||||
} satisfies MediaTrashResponse);
|
||||
}),
|
||||
http.post('*/media-library/restore', async ({ request }) => {
|
||||
const body = (await request.json()) as { ids: string[] };
|
||||
return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'restored', uses: [] })) } satisfies MediaTrashResponse);
|
||||
}),
|
||||
];
|
||||
|
||||
export const mediaPurgeHandlers = [
|
||||
http.post('*/media-library/purge', async ({ request }) => {
|
||||
const body = (await request.json()) as { ids?: string[]; all?: boolean };
|
||||
const ids = body.all ? ['hero:all'] : (body.ids ?? []);
|
||||
return HttpResponse.json({ results: ids.map((id) => ({ id, status: 'purged', uses: [] })) } satisfies MediaTrashResponse);
|
||||
}),
|
||||
];
|
||||
|
||||
export const mediaHandlers = [
|
||||
...mediaPurgeHandlers,
|
||||
...mediaTrashHandlers,
|
||||
http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)),
|
||||
http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())),
|
||||
http.get('*/media-library/cleanup-preview', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const days = Number(url.searchParams.get('days') ?? 7);
|
||||
const onlyUnused = url.searchParams.get('onlyUnused') !== 'false';
|
||||
const cutoff = Date.now() - days * 86_400_000;
|
||||
const photos = seedPhotos().filter((p) => new Date(p.createdAt).getTime() < cutoff && (!onlyUnused || p.uses.length === 0));
|
||||
return HttpResponse.json({
|
||||
days,
|
||||
onlyUnused,
|
||||
count: photos.length,
|
||||
bytes: photos.reduce((sum, p) => sum + p.bytes, 0),
|
||||
photos,
|
||||
} satisfies MediaCleanupPreviewDto);
|
||||
}),
|
||||
];
|
||||
@@ -0,0 +1,348 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import i18n from '@/i18n/config';
|
||||
import { server } from '@/mocks/server';
|
||||
import { renderWithProviders } from '@/test/utils';
|
||||
import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router';
|
||||
import { seedPhotos, seedStorage } from '../mocks/handlers';
|
||||
import { MediaLibraryPage } from './MediaLibraryPage';
|
||||
|
||||
/** The page inside a router with the same base path as the real admin app (/admin), and a stub hero route to land on. */
|
||||
function renderPage() {
|
||||
const root = createRootRoute();
|
||||
const media = createRoute({ getParentRoute: () => root, path: '/media', component: MediaLibraryPage });
|
||||
const hero = createRoute({ getParentRoute: () => root, path: '/hero', component: () => <p data-testid="hero-stub">hero</p> });
|
||||
const router = createRouter({
|
||||
routeTree: root.addChildren([media, hero]),
|
||||
basepath: '/admin',
|
||||
history: createMemoryHistory({ initialEntries: ['/admin/media'] }),
|
||||
});
|
||||
return renderWithProviders(<RouterProvider router={router} />);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
window.localStorage.removeItem('slp.media.layout');
|
||||
await i18n.changeLanguage('nl');
|
||||
});
|
||||
|
||||
describe('MediaLibraryPage', () => {
|
||||
it('lists the photos newest first with where each is used, and the storage', async () => {
|
||||
renderPage();
|
||||
|
||||
const list = await screen.findByTestId('photo-selection-list');
|
||||
const rows = within(list).getAllByRole('listitem');
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(within(rows[0]!).getByText('Hero, slide 1')).toBeInTheDocument();
|
||||
expect(within(rows[1]!).getByText('Niet gebruikt')).toBeInTheDocument();
|
||||
expect(within(rows[2]!).getByText('Hero, slide 2 (uit)')).toBeInTheDocument();
|
||||
expect(await screen.findByTestId('storage-text')).toHaveTextContent('van');
|
||||
expect(screen.queryByTestId('storage-warning')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('warns when the storage is nearly full and says so when it is full', async () => {
|
||||
server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 1_800_000_000, level: 'warning' })));
|
||||
const { unmount } = renderPage();
|
||||
expect(await screen.findByTestId('storage-warning')).toHaveTextContent('80%');
|
||||
unmount();
|
||||
|
||||
server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 2_147_483_648, level: 'full' })));
|
||||
renderPage();
|
||||
expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol');
|
||||
});
|
||||
|
||||
it('selects photos and shows the bulk bar with the delete action', async () => {
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' }));
|
||||
|
||||
expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd');
|
||||
expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Naar prullenbak');
|
||||
});
|
||||
|
||||
it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => {
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
expect(within(dialog).getByTestId('cleanup-only-unused')).toBeChecked();
|
||||
expect(await within(dialog).findByTestId('cleanup-summary')).toHaveTextContent('1 foto');
|
||||
expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('prullenbak');
|
||||
const boxes = within(dialog).getAllByRole('checkbox', { name: /Foto/ });
|
||||
expect(boxes).toHaveLength(1);
|
||||
await waitFor(() => expect(boxes[0]).toBeChecked());
|
||||
});
|
||||
|
||||
it('includes photos in use when "only unused" is switched off', async () => {
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
await within(dialog).findByTestId('cleanup-summary');
|
||||
|
||||
await userEvent.click(within(dialog).getByTestId('cleanup-only-unused'));
|
||||
|
||||
await waitFor(() => expect(within(dialog).getByTestId('cleanup-summary')).toHaveTextContent('2 foto'));
|
||||
expect(within(dialog).getAllByRole('checkbox', { name: /Foto/ })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('moves an unused photo to the trash after one confirmation', async () => {
|
||||
let body: { ids: string[]; confirmedInUse: boolean } | null = null;
|
||||
server.use(
|
||||
http.post('*/media-library/delete', async ({ request }) => {
|
||||
body = (await request.json()) as { ids: string[]; confirmedInUse: boolean };
|
||||
return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222'));
|
||||
await userEvent.click(screen.getByTestId('bulk-action-delete'));
|
||||
expect(await screen.findByTestId('delete-text')).toHaveTextContent('prullenbak');
|
||||
await userEvent.click(screen.getByTestId('delete-confirm'));
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('delete-dialog')).not.toBeInTheDocument());
|
||||
expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false });
|
||||
});
|
||||
|
||||
it('asks a second confirmation that names the places for a photo in use', async () => {
|
||||
let body: { ids: string[]; confirmedInUse: boolean } | null = null;
|
||||
server.use(
|
||||
http.post('*/media-library/delete', async ({ request }) => {
|
||||
body = (await request.json()) as { ids: string[]; confirmedInUse: boolean };
|
||||
return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-select-hero:11111111-1111-1111-1111-111111111111'));
|
||||
await userEvent.click(screen.getByTestId('bulk-action-delete'));
|
||||
expect(await screen.findByTestId('delete-inuse-count')).toHaveTextContent('1 foto wordt nog gebruikt');
|
||||
await userEvent.click(screen.getByTestId('delete-confirm'));
|
||||
|
||||
expect(await screen.findByTestId('delete-places')).toHaveTextContent('Hero, slide 1');
|
||||
expect(body).toBeNull();
|
||||
await userEvent.click(screen.getByTestId('delete-confirm'));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ ids: ['hero:11111111-1111-1111-1111-111111111111'], confirmedInUse: true }));
|
||||
});
|
||||
|
||||
it('reports photos that could not be deleted', async () => {
|
||||
server.use(
|
||||
http.post('*/media-library/delete', async ({ request }) => {
|
||||
const { ids } = (await request.json()) as { ids: string[] };
|
||||
return HttpResponse.json({ results: ids.map((id, i) => ({ id, status: i === 0 ? 'failed' : 'trashed', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222'));
|
||||
await userEvent.click(screen.getByTestId('photo-select-hero:33333333-3333-3333-3333-333333333333'));
|
||||
await userEvent.click(screen.getByTestId('bulk-action-delete'));
|
||||
await userEvent.click(screen.getByTestId('delete-confirm'));
|
||||
await userEvent.click(await screen.findByTestId('delete-confirm'));
|
||||
|
||||
expect(await screen.findByTestId('delete-partial')).toHaveTextContent('1 foto kon niet worden verwijderd');
|
||||
});
|
||||
|
||||
it('shows the trash and restores a photo', async () => {
|
||||
let restored: string[] = [];
|
||||
server.use(
|
||||
http.get('*/media-library/trash', () => HttpResponse.json({ photos: [{ ...seedPhotos()[1]!, deletedAt: new Date().toISOString() }], modules: ['hero'] })),
|
||||
http.post('*/media-library/restore', async ({ request }) => {
|
||||
restored = ((await request.json()) as { ids: string[] }).ids;
|
||||
return HttpResponse.json({ results: restored.map((id) => ({ id, status: 'restored', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
expect(await screen.findByTestId('trash-note')).toBeInTheDocument();
|
||||
await userEvent.click(await screen.findByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222'));
|
||||
await userEvent.click(screen.getByTestId('bulk-action-restore'));
|
||||
|
||||
await waitFor(() => expect(restored).toEqual(['hero:22222222-2222-2222-2222-222222222222']));
|
||||
});
|
||||
|
||||
it('confirming the clean-up moves exactly the selected photos to the trash', async () => {
|
||||
let body: { ids: string[]; confirmedInUse: boolean } | null = null;
|
||||
server.use(
|
||||
http.post('*/media-library/delete', async ({ request }) => {
|
||||
body = (await request.json()) as { ids: string[]; confirmedInUse: boolean };
|
||||
return HttpResponse.json({ results: body.ids.map((id) => ({ id, status: 'trashed', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
await within(dialog).findByTestId('cleanup-summary');
|
||||
|
||||
await userEvent.click(within(dialog).getByTestId('cleanup-confirm'));
|
||||
await userEvent.click(await screen.findByTestId('delete-confirm'));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ ids: ['hero:22222222-2222-2222-2222-222222222222'], confirmedInUse: false }));
|
||||
});
|
||||
|
||||
it('filters the library on used and unused photos', async () => {
|
||||
renderPage();
|
||||
const list = await screen.findByTestId('photo-selection-list');
|
||||
expect(within(list).getAllByRole('listitem')).toHaveLength(3);
|
||||
|
||||
await userEvent.click(screen.getByTestId('filter-unused'));
|
||||
expect(within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem')).toHaveLength(1);
|
||||
|
||||
await userEvent.click(screen.getByTestId('filter-used'));
|
||||
expect(within(screen.getByTestId('photo-selection-list')).getAllByRole('listitem')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('links a use to the hero under the admin base path (/admin/hero, not /hero) and opens its images tab', async () => {
|
||||
window.sessionStorage.removeItem('cms-hero-tab');
|
||||
renderPage();
|
||||
const list = await screen.findByTestId('photo-selection-list');
|
||||
const link = within(within(list).getAllByRole('listitem')[0]!).getByRole('link', { name: 'Hero, slide 1' });
|
||||
|
||||
expect(link).toHaveAttribute('href', '/admin/hero');
|
||||
|
||||
await userEvent.click(link);
|
||||
expect(await screen.findByTestId('hero-stub')).toBeInTheDocument();
|
||||
expect(window.sessionStorage.getItem('cms-hero-tab')).toBe('images');
|
||||
});
|
||||
|
||||
const trashed = (n: number) => ({ ...seedPhotos()[1]!, id: `hero:2222222${n}-2222-2222-2222-222222222222`, bytes: 1_000_000, deletedAt: new Date().toISOString() });
|
||||
|
||||
it('removes selected photos from the trash for good after a clear, irreversible confirmation that names the number', async () => {
|
||||
let body: { ids?: string[]; all?: boolean } | null = null;
|
||||
server.use(
|
||||
http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1), trashed(2)], modules: ['hero'] })),
|
||||
http.post('*/media-library/purge', async ({ request }) => {
|
||||
body = (await request.json()) as { ids?: string[]; all?: boolean };
|
||||
return HttpResponse.json({ results: (body.ids ?? []).map((id) => ({ id, status: 'purged', uses: [] })) });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
await userEvent.click(await screen.findByTestId('photo-select-hero:22222221-2222-2222-2222-222222222222'));
|
||||
await userEvent.click(await screen.findByTestId('photo-select-hero:22222222-2222-2222-2222-222222222222'));
|
||||
|
||||
expect(screen.getByTestId('bulk-action-restore')).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByTestId('bulk-action-purge'));
|
||||
|
||||
expect(await screen.findByTestId('purge-text')).toHaveTextContent('2 foto');
|
||||
expect(screen.getByTestId('purge-warning')).toHaveTextContent('niet ongedaan');
|
||||
await userEvent.click(screen.getByTestId('purge-confirm'));
|
||||
await waitFor(() => expect(body).toEqual({ ids: ['hero:22222221-2222-2222-2222-222222222222', 'hero:22222222-2222-2222-2222-222222222222'] }));
|
||||
});
|
||||
|
||||
it('empties the whole trash with one button: the confirmation names the total number and size, and the server is asked for all', async () => {
|
||||
let body: { ids?: string[]; all?: boolean } | null = null;
|
||||
server.use(
|
||||
http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1), trashed(2), trashed(3)], modules: ['hero'] })),
|
||||
http.post('*/media-library/purge', async ({ request }) => {
|
||||
body = (await request.json()) as { ids?: string[]; all?: boolean };
|
||||
return HttpResponse.json({ results: [{ id: 'a', status: 'purged', uses: [] }] });
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
await waitFor(() => expect(screen.getByTestId('trash-empty')).toBeEnabled());
|
||||
|
||||
await userEvent.click(screen.getByTestId('trash-empty'));
|
||||
|
||||
expect(await screen.findByTestId('purge-text')).toHaveTextContent(/3 foto's.*2,9 MB|3 foto's \(2,9 MB\)/);
|
||||
expect(screen.getByTestId('purge-warning')).toHaveTextContent('niet ongedaan');
|
||||
await userEvent.click(screen.getByTestId('purge-confirm'));
|
||||
await waitFor(() => expect(body).toEqual({ all: true }));
|
||||
});
|
||||
|
||||
it('disables Empty the trash when the trash is empty', async () => {
|
||||
server.use(http.get('*/media-library/trash', () => HttpResponse.json({ photos: [], modules: ['hero'] })));
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('trash-empty')).toBeDisabled());
|
||||
});
|
||||
|
||||
it('reports photos that could not be removed for good', async () => {
|
||||
server.use(
|
||||
http.get('*/media-library/trash', () => HttpResponse.json({ photos: [trashed(1)], modules: ['hero'] })),
|
||||
http.post('*/media-library/purge', () => HttpResponse.json({ results: [{ id: 'x', status: 'inUse', uses: [] }] })),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
await userEvent.click(await screen.findByTestId('photo-select-hero:22222221-2222-2222-2222-222222222222'));
|
||||
await userEvent.click(screen.getByTestId('bulk-action-purge'));
|
||||
await userEvent.click(await screen.findByTestId('purge-confirm'));
|
||||
|
||||
expect(await screen.findByTestId('purge-partial')).toHaveTextContent('1 foto kon niet worden verwijderd');
|
||||
});
|
||||
|
||||
it('shows tiles by default, switches to a list, remembers the choice and keeps every function in both', async () => {
|
||||
const first = renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'tiles');
|
||||
expect(screen.getByTestId('layout-tiles')).toHaveAttribute('aria-pressed', 'true');
|
||||
// The checkbox chip is a flex box with equal padding: no inline line box that would add space under the box.
|
||||
const chip = screen.getAllByTestId(/^photo-chip-/)[0]!;
|
||||
expect(chip).toHaveClass('flex', 'p-1');
|
||||
|
||||
// Selecting and the bulk bar work on tiles.
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'zomer.jpg' }));
|
||||
expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd');
|
||||
|
||||
// The filter works on tiles.
|
||||
await userEvent.click(screen.getByTestId('filter-unused'));
|
||||
expect(within(screen.getByTestId('photo-items')).getAllByRole('listitem')).toHaveLength(1);
|
||||
await userEvent.click(screen.getByTestId('filter-all'));
|
||||
|
||||
await userEvent.click(screen.getByTestId('layout-list'));
|
||||
expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'list');
|
||||
expect(screen.getByTestId('layout-list')).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(window.localStorage.getItem('slp.media.layout')).toBe('list');
|
||||
first.unmount();
|
||||
|
||||
// A later visit starts with the remembered layout, also in the trash view.
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
expect(screen.getByTestId('photo-items')).toHaveAttribute('data-layout', 'list');
|
||||
await userEvent.click(screen.getByTestId('view-trash'));
|
||||
await screen.findByTestId('trash-note');
|
||||
expect(screen.getByTestId('layout-list')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows 0 days in the clean-up and says what that means', async () => {
|
||||
renderPage();
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
const slider = within(dialog).getByTestId('cleanup-days');
|
||||
expect(slider).toHaveAttribute('min', '0');
|
||||
|
||||
fireEvent.change(slider, { target: { value: '0' } });
|
||||
|
||||
expect(await within(dialog).findByTestId('cleanup-zero-note')).toHaveTextContent('direct in aanmerking');
|
||||
expect(within(dialog).getByText('Direct: elke ongebruikte foto')).toBeInTheDocument();
|
||||
await waitFor(() => expect(within(dialog).getByTestId('cleanup-summary')).toBeInTheDocument());
|
||||
expect(within(dialog).getByTestId('cleanup-confirm')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error when the library cannot be loaded', async () => {
|
||||
server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 })));
|
||||
renderPage();
|
||||
|
||||
expect(await screen.findByTestId('media-error')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useMemo, useState, type ReactNode } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Eraser, LayoutGrid, List, RotateCcw, Trash2, XCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CleanupDialog } from '../components/CleanupDialog';
|
||||
import { DeleteDialog } from '../components/DeleteDialog';
|
||||
import { PurgeDialog } from '../components/PurgeDialog';
|
||||
import { PhotoSelectionList, type PhotoUse } from '../components/PhotoSelectionList';
|
||||
import { StorageMeter } from '../components/StorageMeter';
|
||||
import { useLayoutPreference } from '../lib/layoutPreference';
|
||||
import { emptySelection, prune, type Selection } from '../lib/selection';
|
||||
import { rememberHeroImagesTab, usageTarget } from '../lib/usageLabel';
|
||||
import { toPhotoItem } from '../lib/toPhotoItem';
|
||||
import { useMediaPhotos, useMediaStorage, useMediaTrash, useRestorePhotos } from '../services/hooks';
|
||||
|
||||
/** A use becomes a link to the screen of its module, made by the router (so it stays under the admin base path). */
|
||||
function renderUse(use: PhotoUse, label: string): ReactNode {
|
||||
const target = usageTarget(use);
|
||||
return target ? (
|
||||
<Link to={target} onClick={rememberHeroImagesTab} className="underline underline-offset-2 hover:text-primary" data-testid="photo-use-link">
|
||||
{label}
|
||||
</Link>
|
||||
) : (
|
||||
label
|
||||
);
|
||||
}
|
||||
|
||||
type View = 'library' | 'trash';
|
||||
type UseFilter = 'all' | 'used' | 'unused';
|
||||
|
||||
/**
|
||||
* The media library: every photo of every module, newest first, with where it is used; the storage against its limit;
|
||||
* the "Clean up" tool; bulk delete (to the trash); and the trash with restore.
|
||||
*/
|
||||
export function MediaLibraryPage() {
|
||||
const { t } = useTranslation();
|
||||
const [view, setView] = useState<View>('library');
|
||||
const photos = useMediaPhotos();
|
||||
const trash = useMediaTrash(view === 'trash');
|
||||
const storage = useMediaStorage();
|
||||
const restore = useRestorePhotos();
|
||||
const [chosen, setSelection] = useState<Selection>(emptySelection);
|
||||
const [cleanupOpen, setCleanupOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [purging, setPurging] = useState<'selected' | 'all' | null>(null);
|
||||
const [filter, setFilter] = useState<UseFilter>('all');
|
||||
const [layout, setLayout] = useLayoutPreference();
|
||||
|
||||
const source = view === 'library' ? photos : trash;
|
||||
const items = useMemo(
|
||||
() =>
|
||||
(source.data?.photos ?? [])
|
||||
.filter((p) => view === 'trash' || filter === 'all' || (filter === 'used') === p.uses.length > 0)
|
||||
.map((p) => toPhotoItem(p, t)),
|
||||
[source.data, t, view, filter],
|
||||
);
|
||||
// Photos that left the list (after a reload or a move) drop out of the selection.
|
||||
const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]);
|
||||
const selectedItems = items.filter((item) => selection.has(item.id));
|
||||
const trashBytes = (trash.data?.photos ?? []).reduce((sum, p) => sum + p.bytes, 0);
|
||||
|
||||
const switchView = (next: View) => {
|
||||
setView(next);
|
||||
setSelection(emptySelection);
|
||||
};
|
||||
|
||||
const actions =
|
||||
view === 'library'
|
||||
? [{ id: 'delete', label: t('media.delete.action'), destructive: true, icon: <Trash2 className="mr-2 size-4" aria-hidden="true" />, run: () => setDeleting(true) }]
|
||||
: [
|
||||
{
|
||||
id: 'restore',
|
||||
label: t('media.trash.restore'),
|
||||
disabled: restore.isPending,
|
||||
icon: <RotateCcw className="mr-2 size-4" aria-hidden="true" />,
|
||||
run: () => restore.mutate(selectedItems.map((i) => i.id), { onSuccess: () => setSelection(emptySelection) }),
|
||||
},
|
||||
{ id: 'purge', label: t('media.purge.action'), destructive: true, icon: <XCircle className="mr-2 size-4" aria-hidden="true" />, run: () => setPurging('selected') },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6" data-testid="media-library-page">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-2xl font-semibold">{t('media.page.title')}</h1>
|
||||
<Button type="button" variant="outline" onClick={() => setCleanupOpen(true)} data-testid="cleanup-open">
|
||||
<Eraser className="mr-2 size-4" aria-hidden="true" />
|
||||
{t('media.cleanup.open')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{storage.data && <StorageMeter storage={storage.data} />}
|
||||
|
||||
<div className="flex gap-2" role="group" aria-label={t('media.view.label')}>
|
||||
{(['library', 'trash'] as const).map((value) => (
|
||||
<Button key={value} type="button" size="sm" variant={view === value ? 'default' : 'outline'} aria-pressed={view === value} onClick={() => switchView(value)} data-testid={`view-${value}`}>
|
||||
{t(`media.view.${value}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
{view === 'library' ? (
|
||||
<div className="flex gap-2" role="group" aria-label={t('media.filter.label')}>
|
||||
{(['all', 'used', 'unused'] as const).map((value) => (
|
||||
<Button key={value} type="button" size="sm" variant={filter === value ? 'secondary' : 'ghost'} aria-pressed={filter === value} onClick={() => setFilter(value)} data-testid={`filter-${value}`}>
|
||||
{t(`media.filter.${value}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<div className="flex gap-1" role="group" aria-label={t('media.layout.label')}>
|
||||
{([['tiles', LayoutGrid], ['list', List]] as const).map(([value, Icon]) => (
|
||||
<Button key={value} type="button" size="sm" variant={layout === value ? 'secondary' : 'ghost'} aria-pressed={layout === value} onClick={() => setLayout(value)} data-testid={`layout-${value}`}>
|
||||
<Icon className="mr-1.5 size-4" aria-hidden="true" />
|
||||
{t(`media.layout.${value}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{view === 'trash' && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-sm text-muted-foreground" data-testid="trash-note">
|
||||
{t('media.trash.note')}
|
||||
</p>
|
||||
<Button type="button" variant="outline" size="sm" disabled={!trash.data || trash.data.photos.length === 0} onClick={() => setPurging('all')} data-testid="trash-empty">
|
||||
{t('media.purge.emptyButton')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{source.isError && (
|
||||
<p role="alert" className="text-sm text-destructive" data-testid="media-error">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
{source.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
|
||||
{view === 'library' && photos.data && photos.data.modules.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground" data-testid="media-no-modules">
|
||||
{t('media.page.noModules')}
|
||||
</p>
|
||||
)}
|
||||
{source.data && <PhotoSelectionList layout={layout} items={items} selection={selection} onSelectionChange={setSelection} renderUse={renderUse} bulk={{ actions, onClear: () => setSelection(emptySelection) }} />}
|
||||
|
||||
<CleanupDialog open={cleanupOpen} onOpenChange={setCleanupOpen} />
|
||||
<PurgeDialog
|
||||
open={purging !== null}
|
||||
onOpenChange={(open) => !open && setPurging(null)}
|
||||
ids={selectedItems.map((i) => i.id)}
|
||||
all={purging === 'all'}
|
||||
count={purging === 'all' ? (trash.data?.photos.length ?? 0) : selectedItems.length}
|
||||
bytes={trashBytes}
|
||||
onDone={() => setSelection(emptySelection)}
|
||||
/>
|
||||
<DeleteDialog open={deleting} onOpenChange={setDeleting} items={selectedItems} onDone={() => setSelection(emptySelection)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPurgeRequest, MediaStorageDto, MediaTrashRequest, MediaTrashResponse } from './types';
|
||||
|
||||
export const MEDIA_KEY = ['media-library'];
|
||||
|
||||
/** All photos of all modules, newest first, with where each is used. */
|
||||
export function useMediaPhotos(enabled = true) {
|
||||
return useQuery<MediaLibraryDto, Error>({
|
||||
enabled,
|
||||
queryKey: [...MEDIA_KEY, 'photos'],
|
||||
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/photos'),
|
||||
});
|
||||
}
|
||||
|
||||
/** The space the media directory takes against its limit. */
|
||||
export function useMediaStorage() {
|
||||
return useQuery<MediaStorageDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'storage'],
|
||||
queryFn: () => api.get<MediaStorageDto>('/api/v1/media-library/storage'),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** What a clean-up with these settings would select. A preview: nothing is deleted. */
|
||||
export function useCleanupPreview(days: number, onlyUnused: boolean, enabled: boolean) {
|
||||
return useQuery<MediaCleanupPreviewDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'cleanup-preview', days, onlyUnused],
|
||||
queryFn: () => api.get<MediaCleanupPreviewDto>(`/api/v1/media-library/cleanup-preview?days=${days}&onlyUnused=${onlyUnused}`),
|
||||
enabled,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
|
||||
/** The photos in the trash, most recently trashed first. */
|
||||
export function useMediaTrash(enabled = true) {
|
||||
return useQuery<MediaLibraryDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'trash'],
|
||||
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/trash'),
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
/** Moves photos to the trash. The answer says per photo what happened. */
|
||||
export function useTrashPhotos() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<MediaTrashResponse, Error, MediaTrashRequest>({
|
||||
mutationFn: (body) => api.post<MediaTrashResponse>('/api/v1/media-library/delete', body),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Takes photos out of the trash again. */
|
||||
export function useRestorePhotos() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<MediaTrashResponse, Error, string[]>({
|
||||
mutationFn: (ids) => api.post<MediaTrashResponse>('/api/v1/media-library/restore', { ids }),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Removes photos from the trash for good (not reversible); `all` empties the whole trash. */
|
||||
export function usePurgePhotos() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation<MediaTrashResponse, Error, MediaPurgeRequest>({
|
||||
mutationFn: (body) => api.post<MediaTrashResponse>('/api/v1/media-library/purge', body),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: MEDIA_KEY }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
export interface MediaUseDto {
|
||||
module: string;
|
||||
kind: string;
|
||||
position: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface MediaPhotoDto {
|
||||
/** `module:guid`, unique over all modules. */
|
||||
id: string;
|
||||
module: string;
|
||||
bytes: number;
|
||||
width: number;
|
||||
height: number;
|
||||
createdAt: string;
|
||||
thumbnailUrl: string | null;
|
||||
uses: MediaUseDto[];
|
||||
originalFileName: string | null;
|
||||
/** When the photo was last detached from where it was used; null while it was never used. */
|
||||
unusedSince: string | null;
|
||||
/** When the photo went to the trash; null for a photo in the library. */
|
||||
deletedAt: string | null;
|
||||
}
|
||||
|
||||
export interface MediaLibraryDto {
|
||||
photos: MediaPhotoDto[];
|
||||
modules: string[];
|
||||
}
|
||||
|
||||
export type MediaStorageLevel = 'ok' | 'warning' | 'full';
|
||||
|
||||
export interface MediaStorageDto {
|
||||
usedBytes: number;
|
||||
/** 0 means no limit. */
|
||||
limitBytes: number;
|
||||
level: MediaStorageLevel;
|
||||
warningPercent: number;
|
||||
}
|
||||
|
||||
export interface MediaCleanupPreviewDto {
|
||||
days: number;
|
||||
onlyUnused: boolean;
|
||||
count: number;
|
||||
bytes: number;
|
||||
photos: MediaPhotoDto[];
|
||||
}
|
||||
|
||||
export type MediaTrashStatus = 'trashed' | 'restored' | 'purged' | 'inUse' | 'notInTrash' | 'notFound' | 'failed';
|
||||
|
||||
export interface MediaTrashResultDto {
|
||||
id: string;
|
||||
status: MediaTrashStatus;
|
||||
uses: MediaUseDto[];
|
||||
}
|
||||
|
||||
export interface MediaTrashResponse {
|
||||
results: MediaTrashResultDto[];
|
||||
}
|
||||
|
||||
export interface MediaTrashRequest {
|
||||
ids: string[];
|
||||
/** True when the person confirmed a second time, knowing where the photos in use are used. */
|
||||
confirmedInUse: boolean;
|
||||
}
|
||||
|
||||
export interface MediaPurgeRequest {
|
||||
ids?: string[];
|
||||
/** Empty the whole trash (the server lists it and removes everything in batches). */
|
||||
all?: boolean;
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
"openMenu": "Open navigation",
|
||||
"closeMenu": "Close navigation",
|
||||
"hero": "Hero",
|
||||
"media": "Media library",
|
||||
"unreadMessages_one": "{{count}} new message",
|
||||
"unreadMessages_other": "{{count}} new messages"
|
||||
},
|
||||
@@ -241,7 +242,6 @@
|
||||
"changePassword": "Change password",
|
||||
"changePasswordDialog": {
|
||||
"title": "Change Password",
|
||||
"current": "Current password",
|
||||
"new": "New password",
|
||||
"confirm": "Confirm new password",
|
||||
"submit": "Change password",
|
||||
@@ -642,9 +642,15 @@
|
||||
"label": "Button {{n}}: text",
|
||||
"target": "Button {{n}}: target"
|
||||
},
|
||||
"library": {
|
||||
"title": "Add slide",
|
||||
"description": "Choose a photo from the media library or upload a new one; it then lands in the library too. Every slide has one photo. A slide's photo is not changed: remove the slide and add a new one.",
|
||||
"group": "Photo for the new slide",
|
||||
"sharedCrop": "This photo is in more slides; the crop applies to all of them."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Images",
|
||||
"add": "Add image",
|
||||
"add": "Add slide",
|
||||
"uploading": "Uploading…",
|
||||
"hint": "Choose several files at once or drag them into this box. New photos are added at the bottom of the list. Drag a photo by its handle, or use the arrows, to change the order; visitors see the first photo first. With the Focus button you show where the subject is.",
|
||||
"empty": "No images yet.",
|
||||
@@ -667,7 +673,6 @@
|
||||
"activeOn": "Active",
|
||||
"activeOff": "Not active",
|
||||
"activeFor": "show image {{n}} on the website",
|
||||
"queued": "in the queue",
|
||||
"number": "Slide {{n}}",
|
||||
"done": "Processing finished",
|
||||
"doneFor": "Slide {{n}}: processing finished",
|
||||
@@ -704,7 +709,6 @@
|
||||
"tall": "Portrait preview"
|
||||
},
|
||||
"apply": "Apply",
|
||||
"applyHint": "The change only takes effect when you save the hero. If you leave the page without saving it is dropped.",
|
||||
"previewPending": "The preview of this photo is being prepared. Close this window and try again in a few seconds."
|
||||
},
|
||||
"errors": {
|
||||
@@ -783,19 +787,120 @@
|
||||
}
|
||||
},
|
||||
"media": {
|
||||
"module": { "hero": "Hero" },
|
||||
"use": { "slide": "slide", "none": "Not used", "off": "off" },
|
||||
"layout": {
|
||||
"label": "View",
|
||||
"tiles": "Tiles",
|
||||
"list": "List"
|
||||
},
|
||||
"progress": {
|
||||
"working": "Processing…"
|
||||
},
|
||||
"module": {
|
||||
"hero": "Hero"
|
||||
},
|
||||
"use": {
|
||||
"slide": "slide",
|
||||
"none": "Not used",
|
||||
"off": "off",
|
||||
"noneSince": "Not used since {{date}}"
|
||||
},
|
||||
"list": {
|
||||
"label": "Photos",
|
||||
"empty": "There are no photos.",
|
||||
"selectAll": "Select all",
|
||||
"noThumbnail": "No preview"
|
||||
"noThumbnail": "No preview",
|
||||
"photoName": "Photo {{width}} × {{height}}"
|
||||
},
|
||||
"bulk": {
|
||||
"label": "Actions on the selection",
|
||||
"selected_one": "{{count}} photo selected",
|
||||
"selected_other": "{{count}} photos selected",
|
||||
"clear": "Clear selection"
|
||||
},
|
||||
"loading": "Loading...",
|
||||
"error": "The media library could not be loaded.",
|
||||
"page": {
|
||||
"title": "Media library",
|
||||
"noModules": "No module reports photos yet."
|
||||
},
|
||||
"storage": {
|
||||
"title": "Storage",
|
||||
"used": "{{used}} used",
|
||||
"usedOf": "{{used}} of {{limit}} used ({{percent}}%)",
|
||||
"warning": "Storage is more than {{percent}}% full. Clean up photos before the limit is reached.",
|
||||
"full": "Storage is full. No more photos can be uploaded until there is room."
|
||||
},
|
||||
"cleanup": {
|
||||
"open": "Clean up",
|
||||
"title": "Clean up",
|
||||
"description": "Photos that have not been used for a number of days (counted from the last use), newest first. Take out the photos you want to keep.",
|
||||
"days_one": "Older than {{count}} day",
|
||||
"days_other": "Older than {{count}} days",
|
||||
"onlyUnused": "Only unused photos",
|
||||
"summary_one": "{{count}} photo ({{size}}) qualifies.",
|
||||
"summary_other": "{{count}} photos ({{size}}) qualify.",
|
||||
"selectedSize": "Selected: {{size}}",
|
||||
"trashNote": "The selected photos go to the trash and can be restored for 7 days.",
|
||||
"confirm_one": "{{count}} photo to the trash",
|
||||
"confirm_other": "{{count}} photos to the trash",
|
||||
"daysZero": "Immediately: every unused photo",
|
||||
"zeroNote": "At 0 days every photo that is not used anywhere right now qualifies at once, even if it was just detached. You see the overview first and confirm yourself; the photos go to the trash."
|
||||
},
|
||||
"picker": {
|
||||
"upload": "Upload an image",
|
||||
"uploading": "Uploading...",
|
||||
"empty": "There are no photos in the library yet. Upload one.",
|
||||
"notAnImage": "This file is not an image.",
|
||||
"tooLarge": "This file is too large (at most {{max}} MB).",
|
||||
"failed": "Uploading failed. Try again."
|
||||
},
|
||||
"view": {
|
||||
"label": "View",
|
||||
"library": "Library",
|
||||
"trash": "Trash"
|
||||
},
|
||||
"trash": {
|
||||
"since": "In the trash since {{date}}",
|
||||
"restore": "Restore",
|
||||
"note": "Photos in the trash are removed for good after 7 days (default). Restore them while you can, or delete them for good now."
|
||||
},
|
||||
"delete": {
|
||||
"action": "Move to trash",
|
||||
"title": "Move photos to the trash",
|
||||
"confirm_one": "This photo goes to the trash. You can restore it for 7 days.",
|
||||
"confirm_other": "These {{count}} photos go to the trash. You can restore them for 7 days.",
|
||||
"inUseCount_one": "{{count}} photo is still in use.",
|
||||
"inUseCount_other": "{{count}} photos are still in use.",
|
||||
"secondTitle": "Delete photos that are in use?",
|
||||
"secondText_one": "This photo is still in use. If you go on, it disappears from the places below (in the Hero the slide is removed).",
|
||||
"secondText_other": "These photos are still in use. If you go on, they disappear from the places below (in the Hero the slide is removed).",
|
||||
"confirmButton": "Move to trash",
|
||||
"confirmSecond": "Yes, delete anyway",
|
||||
"cancel": "Cancel",
|
||||
"close": "Close",
|
||||
"partial_one": "{{count}} photo could not be deleted. The rest went to the trash.",
|
||||
"partial_other": "{{count}} photos could not be deleted. The rest went to the trash."
|
||||
},
|
||||
"filter": {
|
||||
"label": "Filter",
|
||||
"all": "All photos",
|
||||
"used": "Used",
|
||||
"unused": "Unused"
|
||||
},
|
||||
"purge": {
|
||||
"action": "Delete for good",
|
||||
"title": "Delete for good",
|
||||
"emptyTitle": "Empty the trash",
|
||||
"emptyButton": "Empty the trash",
|
||||
"emptyConfirm": "Empty the trash",
|
||||
"confirmButton": "Delete for good",
|
||||
"confirm_one": "This photo is deleted for good, with its files.",
|
||||
"confirm_other": "These {{count}} photos are deleted for good, with their files.",
|
||||
"confirmAll_one": "The trash is emptied: {{count}} photo ({{size}}) is deleted for good.",
|
||||
"confirmAll_other": "The trash is emptied: {{count}} photos ({{size}}) are deleted for good.",
|
||||
"irreversible": "This cannot be undone.",
|
||||
"partial_one": "{{count}} photo could not be deleted. The rest was deleted for good.",
|
||||
"partial_other": "{{count}} photos could not be deleted. The rest was deleted for good."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"openMenu": "Navigatie openen",
|
||||
"closeMenu": "Navigatie sluiten",
|
||||
"hero": "Hero",
|
||||
"media": "Mediabibliotheek",
|
||||
"unreadMessages_one": "{{count}} nieuw bericht",
|
||||
"unreadMessages_other": "{{count}} nieuwe berichten"
|
||||
},
|
||||
@@ -241,7 +242,6 @@
|
||||
"changePassword": "Wachtwoord wijzigen",
|
||||
"changePasswordDialog": {
|
||||
"title": "Wachtwoord wijzigen",
|
||||
"current": "Huidig wachtwoord",
|
||||
"new": "Nieuw wachtwoord",
|
||||
"confirm": "Nieuw wachtwoord bevestigen",
|
||||
"submit": "Wachtwoord wijzigen",
|
||||
@@ -642,9 +642,15 @@
|
||||
"label": "Knop {{n}}: tekst",
|
||||
"target": "Knop {{n}}: doel"
|
||||
},
|
||||
"library": {
|
||||
"title": "Slide toevoegen",
|
||||
"description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto; die komt dan ook in de bibliotheek. Elke slide heeft één foto. Een foto wijzig je niet op een slide: verwijder de slide en voeg een nieuwe toe.",
|
||||
"group": "Foto voor de nieuwe slide",
|
||||
"sharedCrop": "Deze foto staat in meer slides; de uitsnede geldt voor allemaal."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Afbeeldingen",
|
||||
"add": "Afbeelding toevoegen",
|
||||
"add": "Slide toevoegen",
|
||||
"uploading": "Bezig met uploaden…",
|
||||
"hint": "Kies meerdere bestanden tegelijk of sleep ze naar dit vak. Nieuwe foto’s komen onderaan de lijst. Sleep een foto aan het greepje, of gebruik de pijltjes, om de volgorde te wijzigen; de eerste foto zien bezoekers als eerste. Met de knop Focus geef je aan waar het onderwerp staat.",
|
||||
"empty": "Nog geen afbeeldingen.",
|
||||
@@ -667,7 +673,6 @@
|
||||
"activeOn": "Actief",
|
||||
"activeOff": "Niet actief",
|
||||
"activeFor": "afbeelding {{n}} tonen op de website",
|
||||
"queued": "in de wachtrij",
|
||||
"number": "Slide {{n}}",
|
||||
"done": "Verwerking afgerond",
|
||||
"doneFor": "Slide {{n}}: verwerking afgerond",
|
||||
@@ -704,7 +709,6 @@
|
||||
"tall": "Voorbeeld staand"
|
||||
},
|
||||
"apply": "Toepassen",
|
||||
"applyHint": "De wijziging geldt pas nadat je de hero opslaat. Verlaat je de pagina zonder op te slaan, dan vervalt ze.",
|
||||
"previewPending": "Het voorbeeld van deze foto wordt klaargezet. Sluit dit venster en probeer het over een paar seconden opnieuw."
|
||||
},
|
||||
"errors": {
|
||||
@@ -783,19 +787,120 @@
|
||||
}
|
||||
},
|
||||
"media": {
|
||||
"module": { "hero": "Hero" },
|
||||
"use": { "slide": "slide", "none": "Niet gebruikt", "off": "uit" },
|
||||
"layout": {
|
||||
"label": "Weergave",
|
||||
"tiles": "Tegels",
|
||||
"list": "Lijst"
|
||||
},
|
||||
"progress": {
|
||||
"working": "Wordt verwerkt…"
|
||||
},
|
||||
"module": {
|
||||
"hero": "Hero"
|
||||
},
|
||||
"use": {
|
||||
"slide": "slide",
|
||||
"none": "Niet gebruikt",
|
||||
"off": "uit",
|
||||
"noneSince": "Niet gebruikt sinds {{date}}"
|
||||
},
|
||||
"list": {
|
||||
"label": "Foto's",
|
||||
"empty": "Er zijn geen foto's.",
|
||||
"selectAll": "Alles selecteren",
|
||||
"noThumbnail": "Geen voorbeeld"
|
||||
"noThumbnail": "Geen voorbeeld",
|
||||
"photoName": "Foto {{width}} × {{height}}"
|
||||
},
|
||||
"bulk": {
|
||||
"label": "Acties op de selectie",
|
||||
"selected_one": "{{count}} foto geselecteerd",
|
||||
"selected_other": "{{count}} foto's geselecteerd",
|
||||
"clear": "Selectie wissen"
|
||||
},
|
||||
"loading": "Laden...",
|
||||
"error": "De mediabibliotheek kon niet worden geladen.",
|
||||
"page": {
|
||||
"title": "Mediabibliotheek",
|
||||
"noModules": "Er is nog geen module die foto's meldt."
|
||||
},
|
||||
"storage": {
|
||||
"title": "Opslag",
|
||||
"used": "{{used}} in gebruik",
|
||||
"usedOf": "{{used}} van {{limit}} in gebruik ({{percent}}%)",
|
||||
"warning": "De opslag is voor meer dan {{percent}}% vol. Ruim foto's op voordat de limiet bereikt is.",
|
||||
"full": "De opslag is vol. Er kunnen geen foto's meer worden geüpload tot er ruimte is."
|
||||
},
|
||||
"cleanup": {
|
||||
"open": "Opruimen",
|
||||
"title": "Opruimen",
|
||||
"description": "Foto's die al een aantal dagen niet gebruikt zijn (geteld vanaf het laatste gebruik), nieuwste eerst. Haal foto's uit de selectie die je wilt houden.",
|
||||
"days_one": "Ouder dan {{count}} dag",
|
||||
"days_other": "Ouder dan {{count}} dagen",
|
||||
"onlyUnused": "Alleen ongebruikte foto's",
|
||||
"summary_one": "{{count}} foto ({{size}}) komt in aanmerking.",
|
||||
"summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.",
|
||||
"selectedSize": "Geselecteerd: {{size}}",
|
||||
"trashNote": "De geselecteerde foto's gaan naar de prullenbak en kunnen 7 dagen worden teruggezet.",
|
||||
"confirm_one": "{{count}} foto naar de prullenbak",
|
||||
"confirm_other": "{{count}} foto's naar de prullenbak",
|
||||
"daysZero": "Direct: elke ongebruikte foto",
|
||||
"zeroNote": "Bij 0 dagen komt elke foto die op dit moment nergens wordt gebruikt direct in aanmerking, ook als hij net is losgekoppeld. Je ziet eerst het overzicht en bevestigt zelf; de foto’s gaan naar de prullenbak."
|
||||
},
|
||||
"picker": {
|
||||
"upload": "Afbeelding uploaden",
|
||||
"uploading": "Bezig met uploaden...",
|
||||
"empty": "Er staan nog geen foto's in de bibliotheek. Upload er een.",
|
||||
"notAnImage": "Dit bestand is geen afbeelding.",
|
||||
"tooLarge": "Dit bestand is te groot (maximaal {{max}} MB).",
|
||||
"failed": "Uploaden is niet gelukt. Probeer het opnieuw."
|
||||
},
|
||||
"view": {
|
||||
"label": "Weergave",
|
||||
"library": "Bibliotheek",
|
||||
"trash": "Prullenbak"
|
||||
},
|
||||
"trash": {
|
||||
"since": "In de prullenbak sinds {{date}}",
|
||||
"restore": "Terugzetten",
|
||||
"note": "Foto's in de prullenbak worden na 7 dagen definitief verwijderd (standaard). Zet ze terug zolang het kan, of verwijder ze nu definitief."
|
||||
},
|
||||
"delete": {
|
||||
"action": "Naar prullenbak",
|
||||
"title": "Foto's naar de prullenbak",
|
||||
"confirm_one": "Deze foto gaat naar de prullenbak. Je kunt hem 7 dagen terugzetten.",
|
||||
"confirm_other": "Deze {{count}} foto's gaan naar de prullenbak. Je kunt ze 7 dagen terugzetten.",
|
||||
"inUseCount_one": "{{count}} foto wordt nog gebruikt.",
|
||||
"inUseCount_other": "{{count}} foto's worden nog gebruikt.",
|
||||
"secondTitle": "Foto's in gebruik verwijderen?",
|
||||
"secondText_one": "Deze foto wordt nog gebruikt. Als je doorgaat, verdwijnt hij van de plekken hieronder (bij de Hero verdwijnt de slide).",
|
||||
"secondText_other": "Deze foto's worden nog gebruikt. Als je doorgaat, verdwijnen ze van de plekken hieronder (bij de Hero verdwijnt de slide).",
|
||||
"confirmButton": "Naar prullenbak",
|
||||
"confirmSecond": "Ja, toch verwijderen",
|
||||
"cancel": "Annuleren",
|
||||
"close": "Sluiten",
|
||||
"partial_one": "{{count}} foto kon niet worden verwijderd. De rest is naar de prullenbak.",
|
||||
"partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is naar de prullenbak."
|
||||
},
|
||||
"filter": {
|
||||
"label": "Filter",
|
||||
"all": "Alle foto's",
|
||||
"used": "Gebruikt",
|
||||
"unused": "Ongebruikt"
|
||||
},
|
||||
"purge": {
|
||||
"action": "Definitief verwijderen",
|
||||
"title": "Definitief verwijderen",
|
||||
"emptyTitle": "Prullenbak legen",
|
||||
"emptyButton": "Prullenbak legen",
|
||||
"emptyConfirm": "Prullenbak legen",
|
||||
"confirmButton": "Definitief verwijderen",
|
||||
"confirm_one": "Deze foto wordt definitief verwijderd, met zijn bestanden.",
|
||||
"confirm_other": "Deze {{count}} foto's worden definitief verwijderd, met hun bestanden.",
|
||||
"confirmAll_one": "De prullenbak wordt geleegd: {{count}} foto ({{size}}) wordt definitief verwijderd.",
|
||||
"confirmAll_other": "De prullenbak wordt geleegd: {{count}} foto's ({{size}}) worden definitief verwijderd.",
|
||||
"irreversible": "Dit kan niet ongedaan worden gemaakt.",
|
||||
"partial_one": "{{count}} foto kon niet worden verwijderd. De rest is definitief verwijderd.",
|
||||
"partial_other": "{{count}} foto's konden niet worden verwijderd. De rest is definitief verwijderd."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@ import { systemHandlers } from '@/features/system/mocks/handlers';
|
||||
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
|
||||
import { contactHandlers } from '@/features/contact/mocks/handlers';
|
||||
import { heroHandlers } from '@/features/hero/mocks/handlers';
|
||||
import { mediaHandlers } from '@/features/media/mocks/handlers';
|
||||
|
||||
/** All default MSW handlers, composed from feature folders (Q3-B). */
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers];
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers, ...mediaHandlers];
|
||||
|
||||
export { authHandlers } from '@/features/auth/mocks/handlers';
|
||||
export { userHandlers } from '@/features/users/mocks/handlers';
|
||||
|
||||
@@ -245,6 +245,18 @@ const heroRoute = createRoute({
|
||||
),
|
||||
});
|
||||
|
||||
const mediaRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/media',
|
||||
component: () => (
|
||||
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
|
||||
<ModuleGuard requiredModule="Hero">
|
||||
{lazyPage(() => import('@/features/media/pages/MediaLibraryPage'), 'MediaLibraryPage')()}
|
||||
</ModuleGuard>
|
||||
</RoleGuard>
|
||||
),
|
||||
});
|
||||
|
||||
const offeringsRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/offerings',
|
||||
@@ -333,6 +345,7 @@ export const routeTree = rootRoute.addChildren([
|
||||
usersRoute,
|
||||
cmsRoute,
|
||||
heroRoute,
|
||||
mediaRoute,
|
||||
offeringsRoute,
|
||||
offeringsNewRoute,
|
||||
offeringsEditRoute,
|
||||
|
||||
@@ -674,6 +674,37 @@
|
||||
],
|
||||
"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": {
|
||||
"failed": {
|
||||
@@ -1060,6 +1091,306 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaCleanupPreviewDto": {
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"count": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"days": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"onlyUnused": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"photos": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaPhotoDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"days",
|
||||
"onlyUnused",
|
||||
"count",
|
||||
"bytes",
|
||||
"photos"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaLibraryDto": {
|
||||
"properties": {
|
||||
"modules": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"photos": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaPhotoDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"photos",
|
||||
"modules"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaPhotoDto": {
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"createdAt": {
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
"deletedAt": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"height": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"module": {
|
||||
"type": "string"
|
||||
},
|
||||
"originalFileName": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"thumbnailUrl": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"unusedSince": {
|
||||
"format": "date-time",
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"uses": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaUseDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"width": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"module",
|
||||
"bytes",
|
||||
"width",
|
||||
"height",
|
||||
"createdAt",
|
||||
"thumbnailUrl",
|
||||
"uses"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaPurgeRequest": {
|
||||
"properties": {
|
||||
"all": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"ids": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": [
|
||||
"null",
|
||||
"array"
|
||||
]
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"MediaRestoreRequest": {
|
||||
"properties": {
|
||||
"ids": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ids"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaStorageDto": {
|
||||
"properties": {
|
||||
"level": {
|
||||
"type": "string"
|
||||
},
|
||||
"limitBytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"usedBytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"warningPercent": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"usedBytes",
|
||||
"limitBytes",
|
||||
"level",
|
||||
"warningPercent"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaTrashRequest": {
|
||||
"properties": {
|
||||
"confirmedInUse": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"ids": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ids"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaTrashResponse": {
|
||||
"properties": {
|
||||
"results": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaUseResultDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"results"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaUseDto": {
|
||||
"properties": {
|
||||
"active": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string"
|
||||
},
|
||||
"module": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"null",
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"module",
|
||||
"kind",
|
||||
"position",
|
||||
"active"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaUseResultDto": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"status": {
|
||||
"type": "string"
|
||||
},
|
||||
"uses": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaUseDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"status",
|
||||
"uses"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"OfferingBannerRequest": {
|
||||
"properties": {
|
||||
"endsAt": {
|
||||
@@ -3209,6 +3540,106 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/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"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"404": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ProblemDetails"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Not Found"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"HeroImages"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/hero/images/{id}/retry": {
|
||||
"post": {
|
||||
"parameters": [
|
||||
@@ -3252,6 +3683,352 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/cleanup-preview": {
|
||||
"get": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "days",
|
||||
"schema": {
|
||||
"default": 7,
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "onlyUnused",
|
||||
"schema": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/delete": {
|
||||
"post": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/photos": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/purge": {
|
||||
"post": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaPurgeRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaPurgeRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaPurgeRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/restore": {
|
||||
"post": {
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/*+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaRestoreRequest"
|
||||
}
|
||||
},
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaRestoreRequest"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaRestoreRequest"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaTrashResponse"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/storage": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/trash": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/offerings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -3653,6 +4430,9 @@
|
||||
{
|
||||
"name": "SlpModularCms.Api"
|
||||
},
|
||||
{
|
||||
"name": "MediaLibrary"
|
||||
},
|
||||
{
|
||||
"name": "System"
|
||||
},
|
||||
|
||||
+1
@@ -31,6 +31,7 @@
|
||||
<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.Media\SlpModularCms.Modules.Media.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
<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" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Media\SlpModularCms.Modules.Media.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -21,7 +21,7 @@ public class SiteContractTests
|
||||
public void TheMasterCms_ReferencesEveryModule()
|
||||
{
|
||||
SiteFiles.Modules("SlpModularCms.Api").Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Hero", "Identity", "Master", "Offerings"],
|
||||
["Availability", "Contact", "Hero", "Identity", "Master", "Media", "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", "Hero", "Identity", "Master", "Offerings"]);
|
||||
["Availability", "Contact", "Hero", "Identity", "Master", "Media", "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", "Hero", "Identity", "Offerings"]);
|
||||
["Availability", "Contact", "Hero", "Identity", "Media", "Offerings"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
<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" />
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Media\SlpModularCms.Modules.Media.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaLibraryControllerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
private static MediaLibraryItem Item(int daysOld, bool used)
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1000, 1600, 1067, Now.AddDays(-daysOld), "/media/hero/0123456789abcdef/wide-480.webp");
|
||||
return new MediaLibraryItem(photo, used ? [new MediaUse("hero", photo.Id, "slide", 2, true)] : []);
|
||||
}
|
||||
|
||||
private static MediaLibraryController Controller(params MediaLibraryItem[] items)
|
||||
{
|
||||
var library = Substitute.For<IMediaLibraryService>();
|
||||
library.ListAsync(Arg.Any<CancellationToken>()).Returns(items.OrderByDescending(i => i.Photo.CreatedAt).ToList());
|
||||
library.Modules.Returns(["hero"]);
|
||||
return new MediaLibraryController(library, new Clock());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_administrators_may_use_it()
|
||||
{
|
||||
typeof(MediaLibraryController).GetCustomAttributes(typeof(AuthorizeAttribute), true)
|
||||
.Cast<AuthorizeAttribute>().Should().ContainSingle(a => a.Policy == "AdminOnly");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Photos_lists_each_photo_with_its_uses_and_a_module_prefixed_id()
|
||||
{
|
||||
var used = Item(2, used: true);
|
||||
var result = (OkObjectResult)await Controller(used, Item(9, used: false)).Photos(CancellationToken.None);
|
||||
|
||||
var dto = result.Value.Should().BeOfType<MediaLibraryDto>().Subject;
|
||||
dto.Photos.Should().HaveCount(2);
|
||||
dto.Photos[0].Id.Should().Be($"hero:{used.Photo.Id}");
|
||||
dto.Photos[0].Uses.Should().ContainSingle().Which.Should().Be(new MediaUseDto("hero", "slide", 2, true));
|
||||
dto.Modules.Should().Equal("hero");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_selects_old_unused_photos_and_deletes_nothing()
|
||||
{
|
||||
var oldUnused = Item(20, used: false);
|
||||
var controller = Controller(Item(3, used: false), Item(20, used: true), oldUnused);
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, true, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Count.Should().Be(1);
|
||||
preview.Photos.Single().Id.Should().Be($"hero:{oldUnused.Photo.Id}");
|
||||
preview.Bytes.Should().Be(1000);
|
||||
preview.OnlyUnused.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_can_include_photos_in_use_and_keeps_the_period_in_range()
|
||||
{
|
||||
var controller = Controller(Item(20, used: true), Item(20, used: false));
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(99999, false, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Days.Should().Be(365);
|
||||
preview.Count.Should().Be(0);
|
||||
var shorter = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, false, CancellationToken.None)).Value!;
|
||||
shorter.Count.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purge_names_the_ids_or_empties_the_whole_trash_and_refuses_an_empty_or_oversized_request()
|
||||
{
|
||||
var library = Substitute.For<IMediaLibraryService>();
|
||||
library.PurgeAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => ci.Arg<IReadOnlyCollection<string>>().Select(id => new MediaTrashResult(id, "purged", [])).ToList());
|
||||
library.PurgeAllAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns([new MediaTrashResult("hero:a", "purged", []), new MediaTrashResult("hero:b", "purged", [])]);
|
||||
var controller = new MediaLibraryController(library, new Clock());
|
||||
|
||||
var some = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(["hero:x"]), CancellationToken.None)).Value!;
|
||||
var all = (MediaTrashResponse)((OkObjectResult)await controller.Purge(new MediaPurgeRequest(null, All: true), CancellationToken.None)).Value!;
|
||||
|
||||
some.Results.Should().ContainSingle().Which.Status.Should().Be("purged");
|
||||
all.Results.Should().HaveCount(2);
|
||||
(await controller.Purge(new MediaPurgeRequest([]), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
|
||||
(await controller.Purge(new MediaPurgeRequest(null), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
|
||||
(await controller.Purge(new MediaPurgeRequest(Enumerable.Range(0, 101).Select(i => $"hero:{i}").ToList()), CancellationToken.None)).Should().BeOfType<BadRequestResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Storage_without_a_media_store_reports_zero_and_ok()
|
||||
{
|
||||
var result = (MediaStorageDto)((OkObjectResult)await Controller().Storage(CancellationToken.None)).Value!;
|
||||
|
||||
result.Should().Be(new MediaStorageDto(0, 0, "ok", 80));
|
||||
}
|
||||
}
|
||||
@@ -45,13 +45,23 @@ public class MediaLibraryTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-5, 1)]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(-5, 0)]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(7, 7)]
|
||||
[InlineData(365, 365)]
|
||||
[InlineData(4000, 365)]
|
||||
public void The_period_stays_inside_the_slider_range(int days, int expected) => CleanupSelection.ClampDays(days).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public void Zero_days_selects_every_unused_photo_at_once_and_keeps_those_in_use_out_unless_asked()
|
||||
{
|
||||
var used = Item(0, used: true);
|
||||
var unused = Item(0);
|
||||
|
||||
CleanupSelection.Select([used, unused], Now.AddMinutes(1), 0, onlyUnused: true).Should().ContainSingle().Which.Should().Be(unused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_photo_exactly_at_the_boundary_is_not_selected_yet()
|
||||
{
|
||||
@@ -79,10 +89,177 @@ public class MediaLibraryTests
|
||||
library.Modules.Should().Equal("gallery", "hero");
|
||||
}
|
||||
|
||||
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses) : IMediaUsageProvider
|
||||
[Fact]
|
||||
public async Task Trash_refuses_a_photo_in_use_until_the_person_confirmed_and_then_names_the_places()
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-40), null);
|
||||
var use = new MediaUse("hero", photo.Id, "slide", 3, true);
|
||||
var provider = new FakeProvider("hero", [photo], [use]);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var refused = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: false, Guid.Empty, CancellationToken.None);
|
||||
var done = await library.TrashAsync([$"hero:{photo.Id}"], confirmedInUse: true, Guid.Empty, CancellationToken.None);
|
||||
|
||||
refused.Should().ContainSingle().Which.Status.Should().Be("inUse");
|
||||
refused.Single().Uses.Should().Equal(use);
|
||||
provider.Trashed.Should().Equal(photo.Id);
|
||||
done.Single().Status.Should().Be("trashed");
|
||||
done.Single().Uses.Should().Equal(use);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trash_reports_every_photo_on_its_own_and_one_failure_does_not_stop_the_others()
|
||||
{
|
||||
var ok = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
|
||||
var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
|
||||
var provider = new FakeProvider("hero", [ok, broken], []) { FailFor = broken.Id };
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var results = await library.TrashAsync([$"hero:{broken.Id}", $"hero:{ok.Id}", "hero:not-a-guid", $"other:{Guid.NewGuid()}", $"hero:{Guid.NewGuid()}"], false, Guid.Empty, CancellationToken.None);
|
||||
|
||||
results.Select(r => r.Status).Should().Equal("failed", "trashed", "notFound", "notFound", "notFound");
|
||||
provider.Trashed.Should().Equal(ok.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trash_and_restore_accept_at_most_100_photos_and_a_photo_once()
|
||||
{
|
||||
var provider = new FakeProvider("hero", [], []);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList();
|
||||
|
||||
await FluentActions.Awaiting(() => library.TrashAsync(tooMany, false, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
|
||||
await FluentActions.Awaiting(() => library.RestoreAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
|
||||
var id = $"hero:{Guid.NewGuid()}";
|
||||
(await library.TrashAsync([id, id], false, Guid.Empty, CancellationToken.None)).Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Restore_gives_the_photo_back_and_lists_the_trash_most_recent_first()
|
||||
{
|
||||
var older = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-3));
|
||||
var newer = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-9), null, DeletedAt: Now.AddDays(-1));
|
||||
var provider = new FakeProvider("hero", [], [], trash: [older, newer]);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
(await library.ListTrashAsync(CancellationToken.None)).Select(i => i.Photo.Id).Should().Equal(newer.Id, older.Id);
|
||||
(await library.RestoreAsync([$"hero:{older.Id}"], Guid.Empty, CancellationToken.None)).Single().Status.Should().Be("restored");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_clean_up_counts_from_the_last_use_and_falls_back_to_the_upload_date()
|
||||
{
|
||||
var detachedRecently = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-2));
|
||||
var detachedLongAgo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-100), null, UnusedSince: Now.AddDays(-30));
|
||||
var neverUsed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null);
|
||||
var items = new[] { detachedRecently, detachedLongAgo, neverUsed }.Select(p => new MediaLibraryItem(p, [])).ToList();
|
||||
|
||||
var selected = CleanupSelection.Select(items, Now, 7, onlyUnused: true);
|
||||
|
||||
selected.Select(i => i.Photo.Id).Should().BeEquivalentTo([detachedLongAgo.Id, neverUsed.Id]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_photo_in_use_counts_from_its_upload_date()
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-20), null, UnusedSince: Now.AddDays(-1));
|
||||
var item = new MediaLibraryItem(photo, [new MediaUse("hero", photo.Id, "slide", 1, true)]);
|
||||
|
||||
CleanupSelection.ReferenceDate(item).Should().Be(photo.CreatedAt);
|
||||
CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purge_reports_per_photo_and_only_removes_what_the_module_accepts()
|
||||
{
|
||||
var inTrash = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
|
||||
var notTrashed = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null);
|
||||
var used = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
|
||||
var broken = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now);
|
||||
var provider = new FakeProvider("hero", [notTrashed], [], trash: [inTrash, used, broken]) { InUsePurge = used.Id, FailFor = broken.Id };
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var results = await library.PurgeAsync([$"hero:{inTrash.Id}", $"hero:{notTrashed.Id}", $"hero:{used.Id}", $"hero:{broken.Id}", "nope", $"gallery:{Guid.NewGuid()}"], Guid.Empty, CancellationToken.None);
|
||||
|
||||
results.Select(r => r.Status).Should().Equal("purged", "notInTrash", "inUse", "failed", "notFound", "notFound");
|
||||
provider.Purged.Should().Equal(inTrash.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purge_all_empties_the_whole_trash_in_batches_of_100()
|
||||
{
|
||||
var trash = Enumerable.Range(0, 250).Select(_ => new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now, null, DeletedAt: Now)).ToArray();
|
||||
var provider = new FakeProvider("hero", [], [], trash: trash);
|
||||
var library = new MediaLibraryService([provider]);
|
||||
|
||||
var results = await library.PurgeAllAsync(Guid.Empty, CancellationToken.None);
|
||||
|
||||
results.Should().HaveCount(250).And.OnlyContain(r => r.Status == "purged");
|
||||
provider.Purged.Should().HaveCount(250);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purge_accepts_at_most_100_photos_in_one_request()
|
||||
{
|
||||
var library = new MediaLibraryService([new FakeProvider("hero", [], [])]);
|
||||
var tooMany = Enumerable.Range(0, 101).Select(_ => $"hero:{Guid.NewGuid()}").ToList();
|
||||
|
||||
await FluentActions.Awaiting(() => library.PurgeAsync(tooMany, Guid.Empty, CancellationToken.None)).Should().ThrowAsync<ArgumentOutOfRangeException>();
|
||||
}
|
||||
|
||||
private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses, MediaPhoto[]? trash = null) : IMediaUsageProvider
|
||||
{
|
||||
public string Module => module;
|
||||
|
||||
public List<Guid> Purged { get; } = [];
|
||||
|
||||
public Guid? InUsePurge { get; init; }
|
||||
|
||||
public Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (photoId == FailFor)
|
||||
{
|
||||
throw new InvalidOperationException("boom");
|
||||
}
|
||||
|
||||
if (photoId == InUsePurge)
|
||||
{
|
||||
return Task.FromResult(MediaPurgeOutcome.InUse);
|
||||
}
|
||||
|
||||
if (trash?.Any(p => p.Id == photoId) != true)
|
||||
{
|
||||
return Task.FromResult(MediaPurgeOutcome.NotInTrash);
|
||||
}
|
||||
|
||||
Purged.Add(photoId);
|
||||
return Task.FromResult(MediaPurgeOutcome.Purged);
|
||||
}
|
||||
|
||||
public List<Guid> Trashed { get; } = [];
|
||||
|
||||
public Guid? FailFor { get; init; }
|
||||
|
||||
public Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaPhoto>>(trash ?? []);
|
||||
|
||||
public Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (photoId == FailFor)
|
||||
{
|
||||
throw new InvalidOperationException("boom");
|
||||
}
|
||||
|
||||
if (photos.All(p => p.Id != photoId))
|
||||
{
|
||||
return Task.FromResult<int?>(null);
|
||||
}
|
||||
|
||||
Trashed.Add(photoId);
|
||||
return Task.FromResult<int?>(uses.Count(u => u.PhotoId == photoId));
|
||||
}
|
||||
|
||||
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken) => Task.FromResult(trash?.Any(p => p.Id == photoId) == true);
|
||||
|
||||
public Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaPhoto>>(photos);
|
||||
|
||||
public Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaStorageUsageTests
|
||||
{
|
||||
private sealed class Clock(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(79, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(80, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(99, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(100, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 0, MediaStorageLevel.Ok)]
|
||||
public void The_level_follows_the_share_of_the_limit(long used, long limit, MediaStorageLevel expected)
|
||||
=> MediaStorageUsage.LevelFor(used, limit).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public async Task The_measurement_is_kept_for_a_minute_and_then_taken_again()
|
||||
{
|
||||
var store = Substitute.For<IMediaStore>();
|
||||
store.GetTotalBytesAsync(Arg.Any<CancellationToken>()).Returns(850L, 900L);
|
||||
var clock = new Clock(new DateTimeOffset(2026, 11, 17, 12, 0, 0, TimeSpan.Zero));
|
||||
var usage = new MediaStorageUsage(store, Options.Create(new MediaOptions { MaxTotalBytes = 1000 }), clock);
|
||||
|
||||
var first = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(30);
|
||||
var cached = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(31);
|
||||
var later = await usage.GetAsync(CancellationToken.None);
|
||||
|
||||
first.Should().Be(new MediaStorageInfo(850, 1000, MediaStorageLevel.Warning));
|
||||
cached.Should().BeSameAs(first);
|
||||
later.UsedBytes.Should().Be(900);
|
||||
await store.Received(2).GetTotalBytesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaUseDefinitionTests
|
||||
{
|
||||
private const string Sha = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
[Fact]
|
||||
public void Every_ratio_name_and_width_fits_the_media_address_scheme()
|
||||
{
|
||||
foreach (var use in GalleryUses.All)
|
||||
{
|
||||
var plans = use.PlansFor(4000, 3000);
|
||||
var specs = VariantPlanner.Plan(4000, 3000, plans, new HashSet<ImageFormat> { ImageFormat.WebP });
|
||||
specs.Should().NotBeEmpty(use.Key);
|
||||
foreach (var spec in specs)
|
||||
{
|
||||
var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format);
|
||||
MediaPaths.TryParse($"{use.Module}/{use.SetHash(Sha)}/{name}", out _).Should().BeTrue($"{use.Key}: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_keys_are_unique() => GalleryUses.All.Select(u => u.Key).Should().OnlyHaveUniqueItems();
|
||||
|
||||
[Fact]
|
||||
public void A_mosaic_use_has_a_desktop_and_a_phone_shape_and_a_masonry_use_has_none_of_its_own()
|
||||
{
|
||||
GalleryUses.MosaicLarge.Ratios.Select(r => r.Name).Should().Equal("tilelarge", "tilelargem");
|
||||
GalleryUses.Masonry.Natural.Should().BeTrue();
|
||||
GalleryUses.Masonry.PlansFor(3000, 2000).Should().ContainSingle().Which.Ratio.Should().Be(new Ratio("natural", 3000, 2000));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_natural_use_keeps_the_photos_own_shape_without_a_crop()
|
||||
{
|
||||
var spec = VariantPlanner.Plan(3000, 2000, GalleryUses.Masonry.PlansFor(3000, 2000), new HashSet<ImageFormat> { ImageFormat.WebP })
|
||||
.Single(s => s.Width == 800);
|
||||
|
||||
(spec.Crop.Width, spec.Crop.Height).Should().Be((3000, 2000));
|
||||
spec.Height.Should().Be(533);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_crop_of_a_use_changes_its_set_hash_but_not_the_set_hash_of_another_use()
|
||||
{
|
||||
var focus = new Dictionary<string, FocusSetting> { ["tilelarge"] = new(0.2, 0.3, 1.5) };
|
||||
|
||||
GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().NotBe(GalleryUses.MosaicLarge.SetHash(Sha));
|
||||
GalleryUses.MosaicWide.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicWide.SetHash(Sha));
|
||||
GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicLarge.SetHash(Sha, focus));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_natural_use_does_not_depend_on_a_crop()
|
||||
=> GalleryUses.Masonry.SetHash(Sha, new Dictionary<string, FocusSetting> { ["natural"] = new(0.1, 0.1, 2) }).Should().Be(GalleryUses.Masonry.SetHash(Sha));
|
||||
|
||||
[Fact]
|
||||
public void The_set_hash_formula_is_the_one_the_hero_uses_today()
|
||||
{
|
||||
// Same inputs through the shared function the hero calls: the library does not invent a second scheme.
|
||||
var hero = new MediaUseDefinition("hero", "hero", [new("wide", 3, 2, [640]), new("tall", 4, 5, [480])]);
|
||||
var focus = new Dictionary<string, FocusSetting> { ["wide"] = new(0.3, 0.4, 1.2) };
|
||||
|
||||
hero.SetHash(Sha, focus).Should().Be(MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.3, 0.4, 1.2)), ("tall", FocusSetting.Centre)]));
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,8 @@ public static class ServiceCollectionExtensions
|
||||
services.AddOptions<DataProtectionTokenProviderOptions>()
|
||||
.Configure<IOptions<PasswordResetSettings>>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
// The media library reads from the usage providers of whichever modules are loaded (none is fine).
|
||||
services.TryAddScoped<Media.Library.IMediaLibraryService, Media.Library.MediaLibraryService>();
|
||||
services.TryAddSingleton(sp =>
|
||||
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
|
||||
services.AddScoped<IPasswordResetService, PasswordResetService>();
|
||||
|
||||
@@ -65,6 +65,17 @@ public sealed class MediaOptions
|
||||
public long MaxTotalBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
|
||||
public int RetentionDays { get; set; } = 7;
|
||||
|
||||
/// <summary>
|
||||
/// Whether photos that were uploaded but never used are removed automatically after <see cref="RetentionDays"/>.
|
||||
/// The media library keeps everything until a person removes it, so set this to <c>false</c> (<c>Media__AutoCleanupUnattached=false</c>)
|
||||
/// once the library can show and delete photos. Retired files of photos a person removed stay housekeeping either way.
|
||||
/// Default <c>true</c> keeps today's behaviour (assumption 3 of the media-library list).
|
||||
/// </summary>
|
||||
public bool AutoCleanupUnattached { get; set; } = true;
|
||||
|
||||
/// <summary>How long a photo stays recoverable in the trash before its files are removed.</summary>
|
||||
public int TrashDays { get; set; } = 7;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -2,12 +2,14 @@ namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>
|
||||
/// The photos a clean-up would preselect: uploaded before the period and, by default, not used anywhere. Pure, so it is
|
||||
/// easy to test. The period is measured from the upload date (assumption 8 of the media-library list).
|
||||
/// easy to test. The period counts from the LAST USE (decision 8): for a photo that is not in use the moment it was last
|
||||
/// detached, else its upload date; for a photo in use right now its upload date (assumption 29).
|
||||
/// </summary>
|
||||
public static class CleanupSelection
|
||||
{
|
||||
public const int DefaultDays = 7;
|
||||
public const int MinDays = 1;
|
||||
/// <summary>0 means: every photo that is not in use qualifies at the next clean-up (Bryan, 2026-11-17).</summary>
|
||||
public const int MinDays = 0;
|
||||
public const int MaxDays = 365;
|
||||
|
||||
/// <summary>The days kept inside the slider range.</summary>
|
||||
@@ -18,13 +20,17 @@ public static class CleanupSelection
|
||||
{
|
||||
var cutoff = now.AddDays(-ClampDays(days));
|
||||
return items
|
||||
.Where(item => item.Photo.CreatedAt < cutoff)
|
||||
.Where(item => ReferenceDate(item) < cutoff)
|
||||
.Where(item => !onlyUnused || !item.InUse)
|
||||
.OrderByDescending(item => item.Photo.CreatedAt)
|
||||
.ThenBy(item => item.Photo.Id)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>The date the period counts from.</summary>
|
||||
public static DateTimeOffset ReferenceDate(MediaLibraryItem item)
|
||||
=> item.InUse ? item.Photo.CreatedAt : item.Photo.UnusedSince ?? item.Photo.CreatedAt;
|
||||
|
||||
/// <summary>The bytes the given items take (originals; the variants are counted by the storage service).</summary>
|
||||
public static long Bytes(IEnumerable<MediaLibraryItem> items) => items.Sum(item => item.Photo.Bytes);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public sealed record MediaUseDto(string Module, string Kind, int? Position, bool Active);
|
||||
|
||||
public sealed record MediaPhotoDto(
|
||||
string Id,
|
||||
string Module,
|
||||
long Bytes,
|
||||
int Width,
|
||||
int Height,
|
||||
DateTimeOffset CreatedAt,
|
||||
string? ThumbnailUrl,
|
||||
IReadOnlyList<MediaUseDto> Uses,
|
||||
string? OriginalFileName = null,
|
||||
DateTimeOffset? UnusedSince = null,
|
||||
DateTimeOffset? DeletedAt = null);
|
||||
|
||||
public sealed record MediaLibraryDto(IReadOnlyList<MediaPhotoDto> Photos, IReadOnlyList<string> Modules);
|
||||
|
||||
public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent);
|
||||
|
||||
/// <summary>What a clean-up with these settings would select. A preview: nothing is deleted until the person confirms.</summary>
|
||||
public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList<MediaPhotoDto> Photos);
|
||||
|
||||
/// <param name="Ids">Photo ids as listed (<c>module:guid</c>), at most 100.</param>
|
||||
/// <param name="ConfirmedInUse">True when the person confirmed a second time, knowing where the photos in use are used.</param>
|
||||
public sealed record MediaTrashRequest(IReadOnlyList<string> Ids, bool ConfirmedInUse = false);
|
||||
|
||||
public sealed record MediaRestoreRequest(IReadOnlyList<string> Ids);
|
||||
|
||||
/// <param name="Ids">Photos in the trash to remove for good (at most 100). Ignored when <paramref name="All"/> is true.</param>
|
||||
/// <param name="All">Remove everything that is in the trash (the trash is emptied, in batches on the server).</param>
|
||||
public sealed record MediaPurgeRequest(IReadOnlyList<string>? Ids = null, bool All = false);
|
||||
|
||||
public sealed record MediaUseResultDto(string Id, string Status, IReadOnlyList<MediaUseDto> Uses);
|
||||
|
||||
public sealed record MediaTrashResponse(IReadOnlyList<MediaUseResultDto> Results);
|
||||
|
||||
/// <summary>
|
||||
/// The media library for administrators: the photos of all modules with where they are used, the storage against its
|
||||
/// limit, the clean-up preview, and moving photos to the trash and back. Deleting is always "to the trash": the files go
|
||||
/// after the trash period.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("media-library")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase
|
||||
{
|
||||
[HttpGet("photos")]
|
||||
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Photos(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await library.ListAsync(cancellationToken);
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("trash")]
|
||||
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Trash(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await library.ListTrashAsync(cancellationToken);
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("storage")]
|
||||
[ProducesResponseType<MediaStorageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Storage(CancellationToken cancellationToken)
|
||||
{
|
||||
// A host without media has nothing stored: zero used, no limit.
|
||||
var info = storage is null ? new MediaStorageInfo(0, 0, MediaStorageLevel.Ok) : await storage.GetAsync(cancellationToken);
|
||||
return Ok(new MediaStorageDto(info.UsedBytes, info.LimitBytes, info.Level.ToString().ToLowerInvariant(), MediaStorageUsage.WarningPercent));
|
||||
}
|
||||
|
||||
[HttpGet("cleanup-preview")]
|
||||
[ProducesResponseType<MediaCleanupPreviewDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CleanupPreview([FromQuery] int days = CleanupSelection.DefaultDays, [FromQuery] bool onlyUnused = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var clamped = CleanupSelection.ClampDays(days);
|
||||
var selected = CleanupSelection.Select(await library.ListAsync(cancellationToken), time.GetUtcNow(), clamped, onlyUnused);
|
||||
return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
/// <summary>Moves photos to the trash. A photo in use is refused (status <c>inUse</c>) unless <c>confirmedInUse</c> is true.</summary>
|
||||
[HttpPost("delete")]
|
||||
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Delete([FromBody] MediaTrashRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ValidIds(request.Ids))
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var results = await library.TrashAsync(request.Ids, request.ConfirmedInUse, CallerId(), cancellationToken);
|
||||
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
[HttpPost("restore")]
|
||||
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Restore([FromBody] MediaRestoreRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!ValidIds(request.Ids))
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var results = await library.RestoreAsync(request.Ids, CallerId(), cancellationToken);
|
||||
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
/// <summary>Removes photos from the trash for good: not reversible. Only photos in the trash that are used nowhere.</summary>
|
||||
[HttpPost("purge")]
|
||||
[ProducesResponseType<MediaTrashResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Purge([FromBody] MediaPurgeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.All)
|
||||
{
|
||||
var all = await library.PurgeAllAsync(CallerId(), cancellationToken);
|
||||
return Ok(new MediaTrashResponse(all.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
if (!ValidIds(request.Ids))
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var results = await library.PurgeAsync(request.Ids!, CallerId(), cancellationToken);
|
||||
return Ok(new MediaTrashResponse(results.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
private static bool ValidIds(IReadOnlyList<string>? ids)
|
||||
=> ids is { Count: > 0 and <= MediaLibraryService.MaxIdsPerRequest } && ids.All(id => !string.IsNullOrWhiteSpace(id) && id.Length <= 80);
|
||||
|
||||
private Guid CallerId()
|
||||
{
|
||||
var user = HttpContext?.User;
|
||||
var claim = user?.FindFirstValue(ClaimTypes.NameIdentifier) ?? user?.FindFirstValue("sub");
|
||||
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
private static MediaUseResultDto ToDto(MediaTrashResult result)
|
||||
=> new(result.Id, result.Status, result.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList());
|
||||
|
||||
private static MediaPhotoDto ToDto(MediaLibraryItem item)
|
||||
=> new(
|
||||
$"{item.Photo.Module}:{item.Photo.Id}",
|
||||
item.Photo.Module,
|
||||
item.Photo.Bytes,
|
||||
item.Photo.Width,
|
||||
item.Photo.Height,
|
||||
item.Photo.CreatedAt,
|
||||
item.Photo.ThumbnailUrl,
|
||||
item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList(),
|
||||
item.Photo.OriginalFileName,
|
||||
item.Photo.UnusedSince,
|
||||
item.Photo.DeletedAt);
|
||||
}
|
||||
@@ -1,17 +1,48 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only.</summary>
|
||||
/// <summary>The result for one photo of a trash or restore request.</summary>
|
||||
/// <param name="Id">The photo id as the caller sent it (<c>module:guid</c>).</param>
|
||||
/// <param name="Status"><c>trashed</c>, <c>restored</c>, <c>inUse</c> (not done: it is used and the caller did not confirm), <c>notFound</c> or <c>failed</c>.</param>
|
||||
/// <param name="Uses">Where the photo was used when it was refused or trashed.</param>
|
||||
public sealed record MediaTrashResult(string Id, string Status, IReadOnlyList<MediaUse> Uses);
|
||||
|
||||
/// <summary>The library over all modules that report photos: one list, newest first, each photo with its uses.</summary>
|
||||
public interface IMediaLibraryService
|
||||
{
|
||||
/// <summary>All photos of all modules with their uses, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaLibraryItem>> ListAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The photos in the trash, most recently trashed first.</summary>
|
||||
Task<IReadOnlyList<MediaLibraryItem>> ListTrashAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The modules that report photos (the screen warns about a module that is not in this list).</summary>
|
||||
IReadOnlyList<string> Modules { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Moves photos to the trash. The usage is checked again here, at the moment of deleting: a photo that is in use is
|
||||
/// only trashed when <paramref name="confirmedInUse"/> says the person confirmed it knowing where it is used.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes photos from the trash for good. Each photo is checked again by its module: only a photo that is in the trash
|
||||
/// and used nowhere is removed (statuses <c>purged</c>, <c>notInTrash</c>, <c>inUse</c>, <c>notFound</c>, <c>failed</c>).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Removes everything that is in the trash for good, in batches of <see cref="MediaLibraryService.MaxIdsPerRequest"/>.</summary>
|
||||
Task<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers) : IMediaLibraryService
|
||||
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers, ILogger<MediaLibraryService>? logger = null) : IMediaLibraryService
|
||||
{
|
||||
/// <summary>The most photos one trash or restore request may name.</summary>
|
||||
public const int MaxIdsPerRequest = 100;
|
||||
|
||||
private readonly IMediaUsageProvider[] _providers = providers.ToArray();
|
||||
|
||||
public IReadOnlyList<string> Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList();
|
||||
@@ -29,4 +60,160 @@ public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> provide
|
||||
|
||||
return items.OrderByDescending(i => i.Photo.CreatedAt).ThenBy(i => i.Photo.Id).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaLibraryItem>> ListTrashAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = new List<MediaLibraryItem>();
|
||||
foreach (var provider in _providers)
|
||||
{
|
||||
items.AddRange((await provider.ListTrashAsync(cancellationToken)).Select(photo => new MediaLibraryItem(photo, [])));
|
||||
}
|
||||
|
||||
return items.OrderByDescending(i => i.Photo.DeletedAt).ThenBy(i => i.Photo.Id).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> TrashAsync(IReadOnlyCollection<string> ids, bool confirmedInUse, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
EnsureWithinLimit(ids);
|
||||
var results = new List<MediaTrashResult>();
|
||||
foreach (var id in ids.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
if (!TryResolve(id, out var provider, out var photoId))
|
||||
{
|
||||
results.Add(new MediaTrashResult(id, "notFound", []));
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var uses = await provider.ListUsesAsync([photoId], cancellationToken);
|
||||
if (uses.Count > 0 && !confirmedInUse)
|
||||
{
|
||||
results.Add(new MediaTrashResult(id, "inUse", uses));
|
||||
continue;
|
||||
}
|
||||
|
||||
var detached = await provider.TrashAsync(photoId, callerId, cancellationToken);
|
||||
results.Add(new MediaTrashResult(id, detached is null ? "notFound" : "trashed", uses));
|
||||
if (detached is not null)
|
||||
{
|
||||
logger?.LogInformation("Media {Photo} moved to the trash by user {UserId} ({Uses} uses removed)", id, callerId, detached);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
// One photo failing never stops the others; the caller sees it per photo.
|
||||
logger?.LogWarning(exception, "Moving media {Photo} to the trash failed", id);
|
||||
results.Add(new MediaTrashResult(id, "failed", []));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> RestoreAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
EnsureWithinLimit(ids);
|
||||
var results = new List<MediaTrashResult>();
|
||||
foreach (var id in ids.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
if (!TryResolve(id, out var provider, out var photoId))
|
||||
{
|
||||
results.Add(new MediaTrashResult(id, "notFound", []));
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var restored = await provider.RestoreAsync(photoId, callerId, cancellationToken);
|
||||
results.Add(new MediaTrashResult(id, restored ? "restored" : "notFound", []));
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger?.LogWarning(exception, "Restoring media {Photo} failed", id);
|
||||
results.Add(new MediaTrashResult(id, "failed", []));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> PurgeAsync(IReadOnlyCollection<string> ids, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
EnsureWithinLimit(ids);
|
||||
var results = new List<MediaTrashResult>();
|
||||
foreach (var id in ids.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
if (!TryResolve(id, out var provider, out var photoId))
|
||||
{
|
||||
results.Add(new MediaTrashResult(id, "notFound", []));
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var outcome = await provider.PurgeAsync(photoId, callerId, cancellationToken);
|
||||
var status = outcome switch
|
||||
{
|
||||
MediaPurgeOutcome.Purged => "purged",
|
||||
MediaPurgeOutcome.InUse => "inUse",
|
||||
_ => "notInTrash",
|
||||
};
|
||||
results.Add(new MediaTrashResult(id, status, []));
|
||||
if (outcome == MediaPurgeOutcome.Purged)
|
||||
{
|
||||
logger?.LogInformation("Media {Photo} removed for good by user {UserId}", id, callerId);
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger?.LogWarning(exception, "Removing media {Photo} for good failed", id);
|
||||
results.Add(new MediaTrashResult(id, "failed", []));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MediaTrashResult>> PurgeAllAsync(Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = (await ListTrashAsync(cancellationToken)).Select(i => $"{i.Photo.Module}:{i.Photo.Id}").ToList();
|
||||
var results = new List<MediaTrashResult>();
|
||||
foreach (var batch in ids.Chunk(MaxIdsPerRequest))
|
||||
{
|
||||
results.AddRange(await PurgeAsync(batch, callerId, cancellationToken));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void EnsureWithinLimit(IReadOnlyCollection<string> ids)
|
||||
{
|
||||
if (ids.Count > MaxIdsPerRequest)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(ids), $"At most {MaxIdsPerRequest} photos per request.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Splits <c>module:guid</c> and finds the provider of that module.</summary>
|
||||
private bool TryResolve(string id, out IMediaUsageProvider provider, out Guid photoId)
|
||||
{
|
||||
provider = null!;
|
||||
photoId = Guid.Empty;
|
||||
var colon = id.IndexOf(':');
|
||||
if (colon <= 0 || !Guid.TryParse(id.AsSpan(colon + 1), out photoId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var module = id[..colon];
|
||||
var found = _providers.FirstOrDefault(p => string.Equals(p.Module, module, StringComparison.Ordinal));
|
||||
if (found is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
provider = found;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,20 @@ namespace SlpModularCms.Core.Media.Library;
|
||||
/// <summary>A photo as the library shows it. The module that owns it fills it; the library only reads.</summary>
|
||||
/// <param name="Module">The module key (for example <c>hero</c>); with <paramref name="Id"/> it names the photo.</param>
|
||||
/// <param name="ThumbnailUrl">A public address of a small variant, or null while no variant exists yet.</param>
|
||||
public sealed record MediaPhoto(string Module, Guid Id, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl);
|
||||
/// <param name="OriginalFileName">The file name as uploaded, or null for photos uploaded before it was stored.</param>
|
||||
/// <param name="UnusedSince">The moment the photo was last detached from where it was used; null when it was never used.</param>
|
||||
/// <param name="DeletedAt">When the photo was moved to the trash; null for a photo in the library.</param>
|
||||
public sealed record MediaPhoto(
|
||||
string Module,
|
||||
Guid Id,
|
||||
long Bytes,
|
||||
int Width,
|
||||
int Height,
|
||||
DateTimeOffset CreatedAt,
|
||||
string? ThumbnailUrl,
|
||||
string? OriginalFileName = null,
|
||||
DateTimeOffset? UnusedSince = null,
|
||||
DateTimeOffset? DeletedAt = null);
|
||||
|
||||
/// <summary>One place where a photo is used. The library shows it as "module, place kind, position" (for example "Hero, slide 3").</summary>
|
||||
/// <param name="PlaceKind">What kind of place (for example <c>slide</c>); the screen translates it.</param>
|
||||
@@ -18,17 +31,48 @@ public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList<MediaUse>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a module tells the media library. Read-only: the library never changes a module's data through this contract
|
||||
/// (deleting and detaching come in a later step). The answers are computed from the module's own data, never copied.
|
||||
/// What a module tells the media library and does for it. The answers are computed from the module's own data, never copied.
|
||||
/// Deleting always means "to the trash" (recoverable for a while); the module removes the files later itself.
|
||||
/// </summary>
|
||||
public interface IMediaUsageProvider
|
||||
{
|
||||
/// <summary>The module key, lower case, equal to its media area when it has one.</summary>
|
||||
string Module { get; }
|
||||
|
||||
/// <summary>The photos of this module, newest first.</summary>
|
||||
/// <summary>The photos of this module that are not in the trash, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The photos of this module in the trash, most recently trashed first.</summary>
|
||||
Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Where the given photos are used (only photos of this module).</summary>
|
||||
Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves a photo to the trash after detaching it from where it is used. Returns how many places lost it, or null when
|
||||
/// there is no such photo outside the trash.
|
||||
/// </summary>
|
||||
Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Takes a photo out of the trash. False when it is not in the trash.</summary>
|
||||
Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a photo FOR GOOD: its original and its cut sets (a set another photo still shares stays). Only a photo that is
|
||||
/// in the trash and used nowhere; the module checks this again itself.
|
||||
/// </summary>
|
||||
Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>What happened to a photo that was to be removed for good.</summary>
|
||||
public enum MediaPurgeOutcome
|
||||
{
|
||||
/// <summary>Removed: the files and the record are gone.</summary>
|
||||
Purged,
|
||||
|
||||
/// <summary>There is no such photo in the trash (not trashed, or already gone). Nothing was changed.</summary>
|
||||
NotInTrash,
|
||||
|
||||
/// <summary>The photo is used somewhere after all. Nothing was changed.</summary>
|
||||
InUse,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>One crop of a photo for a ratio (focus point and zoom).</summary>
|
||||
public sealed record MediaCropSnapshot(string Ratio, double X, double Y, double Zoom);
|
||||
|
||||
/// <summary>
|
||||
/// A photo as a module holds it today, for copying into the library's own tables. Same ids, hashes and set hashes as the
|
||||
/// module uses, so no public address changes (migration plan, decision 13).
|
||||
/// </summary>
|
||||
public sealed record MediaAssetSnapshot(
|
||||
Guid Id,
|
||||
string Module,
|
||||
string OriginalSha256,
|
||||
string OriginalKey,
|
||||
string SourceFormat,
|
||||
int Width,
|
||||
int Height,
|
||||
long Bytes,
|
||||
double FocusX,
|
||||
double FocusY,
|
||||
double Zoom,
|
||||
string SetHash,
|
||||
IReadOnlyList<MediaCropSnapshot> Crops,
|
||||
DateTimeOffset CreatedAt,
|
||||
Guid CreatedByUserId,
|
||||
string? OriginalFileName,
|
||||
DateTimeOffset? LastUsedAt,
|
||||
DateTimeOffset? DeletedAt);
|
||||
|
||||
/// <summary>One place a photo is used, as a module holds it today.</summary>
|
||||
public sealed record MediaUseSnapshot(Guid Id, Guid AssetId, string Module, string PlaceKind, int Position, bool Active, string SetHash);
|
||||
|
||||
/// <summary>
|
||||
/// What a module offers so the library can copy its photos and uses into its own tables. Read-only: the module's data is
|
||||
/// never changed by the copy.
|
||||
/// </summary>
|
||||
public interface IMediaMigrationSource
|
||||
{
|
||||
string Module { get; }
|
||||
|
||||
/// <summary>Every photo of the module, also those in the trash.</summary>
|
||||
Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public enum MediaStorageLevel
|
||||
{
|
||||
Ok,
|
||||
Warning,
|
||||
Full,
|
||||
}
|
||||
|
||||
/// <param name="UsedBytes">Everything in the media directory (originals and variants).</param>
|
||||
/// <param name="LimitBytes">The safety limit; 0 means no limit.</param>
|
||||
public sealed record MediaStorageInfo(long UsedBytes, long LimitBytes, MediaStorageLevel Level);
|
||||
|
||||
/// <summary>
|
||||
/// The space the media directory takes against its limit (<c>Media:MaxTotalBytes</c>). Measuring walks the directory, so
|
||||
/// the answer is kept for a minute (assumption 9 of the media-library list: warning at 80 percent, full at 100).
|
||||
/// </summary>
|
||||
public sealed class MediaStorageUsage(IMediaStore store, IOptions<MediaOptions> options, TimeProvider? time = null)
|
||||
{
|
||||
public const int WarningPercent = 80;
|
||||
private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(60);
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private MediaStorageInfo? _cached;
|
||||
private DateTimeOffset _measuredAt;
|
||||
|
||||
public static MediaStorageLevel LevelFor(long used, long limit)
|
||||
{
|
||||
if (limit <= 0)
|
||||
{
|
||||
return MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
if (used >= limit)
|
||||
{
|
||||
return MediaStorageLevel.Full;
|
||||
}
|
||||
|
||||
return used * 100 >= limit * WarningPercent ? MediaStorageLevel.Warning : MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
public async Task<MediaStorageInfo> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _time.GetUtcNow();
|
||||
if (_cached is { } fresh && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return fresh;
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
now = _time.GetUtcNow();
|
||||
if (_cached is { } again && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return again;
|
||||
}
|
||||
|
||||
var used = await store.GetTotalBytesAsync(cancellationToken);
|
||||
var limit = Math.Max(0, options.Value.MaxTotalBytes);
|
||||
_cached = new MediaStorageInfo(used, limit, LevelFor(used, limit));
|
||||
_measuredAt = now;
|
||||
return _cached;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>One ratio of a use: its name (part of the file name), its shape and the widths cut for it.</summary>
|
||||
public sealed record UseRatio(string Name, int Numerator, int Denominator, IReadOnlyList<int> Widths);
|
||||
|
||||
/// <summary>
|
||||
/// What a USE of a photo needs (a place on a page, not the photo itself): the ratios with their widths, or the natural
|
||||
/// shape of the photo without a crop. A photo can have several uses; each use has its own crop (focus per ratio) and so
|
||||
/// its own set. Pure data, no behaviour that moves anything.
|
||||
/// </summary>
|
||||
/// <param name="Key">For example <c>mosaic-large</c>; unique.</param>
|
||||
/// <param name="Module">The module whose pages show it (also its media area).</param>
|
||||
/// <param name="Ratios">Empty for a natural-ratio use.</param>
|
||||
/// <param name="Natural">The photo is shown in its own shape: no crop, one ratio taken from the photo itself.</param>
|
||||
public sealed record MediaUseDefinition(string Key, string Module, IReadOnlyList<UseRatio> Ratios, bool Natural = false)
|
||||
{
|
||||
public const string NaturalRatioName = "natural";
|
||||
|
||||
/// <summary>The ratio plans for a photo, given the focus per ratio name (centre when none is given).</summary>
|
||||
public IReadOnlyList<RatioPlan> PlansFor(int sourceWidth, int sourceHeight, IReadOnlyDictionary<string, FocusSetting>? focus = null)
|
||||
{
|
||||
if (Natural)
|
||||
{
|
||||
var widths = Ratios.Count > 0 ? Ratios[0].Widths : [];
|
||||
return [new RatioPlan(new Ratio(NaturalRatioName, sourceWidth, sourceHeight), FocusSetting.Centre, widths)];
|
||||
}
|
||||
|
||||
return Ratios
|
||||
.Select(r => new RatioPlan(new Ratio(r.Name, r.Numerator, r.Denominator), focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre, r.Widths))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The set hash of this use for a photo: the existing formula over the photo's hash and the crops of this use, so a
|
||||
/// photo gets the same address for the same use and crops, and another use never shares a set by accident.
|
||||
/// A natural-ratio use has no crop, so its set depends on the photo alone (and the use key).
|
||||
/// </summary>
|
||||
public string SetHash(string originalSha256, IReadOnlyDictionary<string, FocusSetting>? focus = null)
|
||||
{
|
||||
var crops = Natural
|
||||
? [(NaturalRatioName, FocusSetting.Centre)]
|
||||
: Ratios.Select(r => (r.Name, focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre)).ToList();
|
||||
return MediaPaths.SetHash(originalSha256, crops);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The uses of the gallery that the Andrea Slop Fotografie site needs (answer of the ASF session, 2026-11-17): the
|
||||
/// mosaic tiles (a shape fixed per page by the number and order of the photos, a desktop and a phone shape each) and the
|
||||
/// masonry portfolio (natural shape). Ratio names are letters only, 2 to 10 long, so they fit the address allow-list.
|
||||
/// </summary>
|
||||
public static class GalleryUses
|
||||
{
|
||||
public const string Module = "gallery";
|
||||
|
||||
private static readonly int[] Large = [480, 640, 960, 1280];
|
||||
private static readonly int[] Small = [312, 480, 640];
|
||||
|
||||
/// <summary>Photo 1 of 2 to 4: about 1:1 on desktop (max about 656 wide), 4:3 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicLarge = new("mosaic-large", Module, [new("tilelarge", 1, 1, Large), new("tilelargem", 4, 3, Large)]);
|
||||
|
||||
/// <summary>Photo 2 of 3 or 4: about 2.2:1 on desktop, 3:2 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicWide = new("mosaic-wide", Module, [new("tilewide", 11, 5, Large), new("tilewidem", 3, 2, Large)]);
|
||||
|
||||
/// <summary>Photos 3 and 4 of 4: about 1.04:1 on desktop (max about 312 wide), 1:1 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicSmall = new("mosaic-small", Module, [new("tilesmall", 26, 25, Small), new("tilesmallm", 1, 1, Small)]);
|
||||
|
||||
/// <summary>The portfolio: the photo's own shape, no crop; thumbnail widths about 480 and 800.</summary>
|
||||
public static readonly MediaUseDefinition Masonry = new("masonry", Module, [new(MediaUseDefinition.NaturalRatioName, 1, 1, [480, 800])], Natural: true);
|
||||
|
||||
public static IReadOnlyList<MediaUseDefinition> All { get; } = [MosaicLarge, MosaicWide, MosaicSmall, Masonry];
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public static class MediaServiceCollectionExtensions
|
||||
services.TryAddSingleton<MediaAreaRegistry>();
|
||||
services.TryAddSingleton<IMediaStore, FileSystemMediaStore>();
|
||||
services.TryAddSingleton<IMediaUploadGuard, MediaUploadGuard>();
|
||||
services.TryAddScoped<Library.IMediaLibraryService, Library.MediaLibraryService>();
|
||||
services.TryAddSingleton<Library.MediaStorageUsage>();
|
||||
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
|
||||
{
|
||||
services.AddHostedService<ImageProcessorSelfTest>();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroMediaMigrationSourceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Offers_every_photo_with_the_ids_hashes_and_set_hashes_the_hero_uses_and_one_use_per_slide()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var c = await rig.Upload(HeroTestRig.Photo(seed: 3));
|
||||
await rig.Service.SaveAsync(
|
||||
new HeroSaveRequest("Titel", null, null, "single", [], [new HeroSlideRequest(null, Guid.Parse(b.Id), "twee"), new HeroSlideRequest(null, Guid.Parse(a.Id), "een", IsActive: false)]),
|
||||
HeroTestRig.Admin, CancellationToken.None);
|
||||
await new HeroMediaUsageProvider(rig.Repository, rig.Images).TrashAsync(Guid.Parse(c.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
var source = new HeroMediaMigrationSource(rig.Repository);
|
||||
|
||||
var assets = await source.ListAssetsAsync(CancellationToken.None);
|
||||
var uses = await source.ListUsesAsync(CancellationToken.None);
|
||||
|
||||
source.Module.Should().Be("hero");
|
||||
assets.Select(x => x.Id).Should().BeEquivalentTo([Guid.Parse(a.Id), Guid.Parse(b.Id), Guid.Parse(c.Id)]);
|
||||
foreach (var asset in assets)
|
||||
{
|
||||
var row = rig.Db.HeroImages.Single(i => i.Id == asset.Id);
|
||||
asset.OriginalSha256.Should().Be(row.OriginalSha256);
|
||||
asset.OriginalKey.Should().Be(row.OriginalKey);
|
||||
asset.SetHash.Should().Be(row.SetHash).And.NotBeEmpty();
|
||||
asset.Crops.Select(x => x.Ratio).Should().Equal("wide", "tall");
|
||||
}
|
||||
|
||||
assets.Single(x => x.Id == Guid.Parse(c.Id)).DeletedAt.Should().NotBeNull();
|
||||
uses.Should().HaveCount(2);
|
||||
uses.Single(u => u.AssetId == Guid.Parse(b.Id)).Should().Match<SlpModularCms.Core.Media.Library.MediaUseSnapshot>(u => u.Position == 1 && u.Active && u.PlaceKind == "slide");
|
||||
uses.Single(u => u.AssetId == Guid.Parse(a.Id)).Should().Match<SlpModularCms.Core.Media.Library.MediaUseSnapshot>(u => u.Position == 2 && !u.Active);
|
||||
uses.Select(u => u.SetHash).Should().OnlyContain(h => h.Length == 16);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reading_changes_nothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
var source = new HeroMediaMigrationSource(rig.Repository);
|
||||
|
||||
await source.ListAssetsAsync(CancellationToken.None);
|
||||
await source.ListUsesAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.ChangeTracker.HasChanges().Should().BeFalse();
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,12 @@ namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroMediaUsageProviderTests
|
||||
{
|
||||
private static HeroMediaUsageProvider Provider(HeroTestRig rig) => new(rig.Repository, rig.Images);
|
||||
|
||||
private static Task<HeroSaveRequest> NoSlides() => Task.FromResult(Save([]));
|
||||
|
||||
private static HeroSaveRequest Save(params HeroSlideRequest[] slides) => new("Titel", null, null, "single", [], slides);
|
||||
|
||||
[Fact]
|
||||
public async Task Lists_the_images_newest_first_with_a_thumbnail_and_reports_one_use_per_slide_with_its_position()
|
||||
{
|
||||
@@ -18,10 +24,9 @@ public class HeroMediaUsageProviderTests
|
||||
rig.Time.Now = rig.Time.Now.AddMinutes(5);
|
||||
var unused = await rig.Upload(HeroTestRig.Photo(seed: 3));
|
||||
await rig.Service.SaveAsync(
|
||||
new HeroSaveRequest("Titel", null, null, "single", [],
|
||||
[new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)]),
|
||||
Save(new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)),
|
||||
HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = new HeroMediaUsageProvider(rig.Repository);
|
||||
var provider = Provider(rig);
|
||||
|
||||
var photos = await provider.ListPhotosAsync(CancellationToken.None);
|
||||
var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), CancellationToken.None);
|
||||
@@ -40,12 +45,225 @@ public class HeroMediaUsageProviderTests
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var provider = new HeroMediaUsageProvider(rig.Repository);
|
||||
var provider = Provider(rig);
|
||||
|
||||
await provider.ListPhotosAsync(CancellationToken.None);
|
||||
await provider.ListUsesAsync([Guid.Parse(image.Id)], CancellationToken.None);
|
||||
await provider.ListTrashAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Repository.CountImagesAsync(CancellationToken.None)).Should().Be(1);
|
||||
rig.Db.ChangeTracker.HasChanges().Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_upload_remembers_the_cleaned_original_file_name()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = HeroTestRig.Photo();
|
||||
|
||||
await rig.Images.UploadAsync(new MemoryStream(bytes), bytes.Length, HeroTestRig.Admin, CancellationToken.None, "C:\\fotos\\zomer\u0007 2026.jpg");
|
||||
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().OriginalFileName.Should().Be("zomer 2026.jpg");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData(" ", null)]
|
||||
[InlineData("../../etc/passwd", "passwd")]
|
||||
[InlineData("a/b\\c.jpg", "c.jpg")]
|
||||
public void File_names_are_cleaned_for_display_only(string? input, string? expected) => HeroFileNames.Clean(input).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public void A_very_long_file_name_is_cut() => HeroFileNames.Clean(new string('a', 500))!.Length.Should().Be(HeroFileNames.MaxLength);
|
||||
|
||||
[Fact]
|
||||
public async Task Trashing_a_photo_in_use_removes_its_slides_hides_it_and_remembers_the_last_use()
|
||||
{
|
||||
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(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")), HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = Provider(rig);
|
||||
rig.Time.Now = rig.Time.Now.AddDays(3);
|
||||
|
||||
var removed = await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
removed.Should().Be(1);
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Select(p => p.Id).Should().Equal(Guid.Parse(b.Id));
|
||||
var trashed = (await provider.ListTrashAsync(CancellationToken.None)).Single();
|
||||
trashed.Id.Should().Be(Guid.Parse(a.Id));
|
||||
trashed.DeletedAt.Should().Be(rig.Time.Now);
|
||||
trashed.UnusedSince.Should().Be(rig.Time.Now);
|
||||
(await rig.Service.GetAsync(CancellationToken.None)).Slides.Should().ContainSingle().Which.Image.Id.Should().Be(b.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_trashed_photo_cannot_be_put_in_a_slide_and_is_not_cut_in_the_background()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.UploadWithoutRendering(HeroTestRig.Photo());
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var save = () => rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await save.Should().ThrowAsync<HeroSaveRejectedException>();
|
||||
(await rig.RenderPending()).Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Trashing_an_unknown_or_already_trashed_photo_gives_null()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
var provider = Provider(rig);
|
||||
|
||||
(await provider.TrashAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
(await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Restoring_brings_the_photo_back_without_its_slides()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeTrue();
|
||||
(await provider.RestoreAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().BeFalse();
|
||||
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle();
|
||||
(await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty();
|
||||
(await provider.ListUsesAsync([Guid.Parse(a.Id)], CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Uploading_the_same_photo_again_brings_it_back_from_the_trash()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = HeroTestRig.Photo();
|
||||
var first = await rig.Upload(bytes);
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(first.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var again = await rig.Upload(bytes);
|
||||
|
||||
again.Id.Should().Be(first.Id);
|
||||
(await provider.ListTrashAsync(CancellationToken.None)).Should().BeEmpty();
|
||||
(await provider.ListPhotosAsync(CancellationToken.None)).Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_the_hero_without_a_slide_remembers_when_its_photo_was_last_used()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().BeNull();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(2);
|
||||
await rig.Service.SaveAsync(Save(), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await Provider(rig).ListPhotosAsync(CancellationToken.None)).Single().UnusedSince.Should().Be(rig.Time.Now);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purging_removes_a_photo_in_the_trash_for_good_with_its_original_and_set()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var keep = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id));
|
||||
var (set, original) = (rowA.SetHash, rowA.OriginalKey);
|
||||
var keepRow = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(keep.Id));
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var outcome = await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
outcome.Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged);
|
||||
rig.Db.HeroImages.Select(i => i.Id).Should().Equal(Guid.Parse(keep.Id));
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set).And.Contain(s => s.SetHash == keepRow.SetHash);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
(await rig.Store.ExistsAsync(keepRow.OriginalKey, CancellationToken.None)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purging_refuses_a_photo_that_is_not_in_the_trash_and_changes_nothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
var original = rig.Db.HeroImages.Single().OriginalKey;
|
||||
var provider = Provider(rig);
|
||||
|
||||
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash);
|
||||
(await provider.PurgeAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.NotInTrash);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purging_refuses_a_photo_that_a_slide_uses_after_all()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(Save(new HeroSlideRequest(null, Guid.Parse(a.Id), "foto")), HeroTestRig.Admin, CancellationToken.None);
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
// A slide that still points at the trashed photo (a race or an old row): the purge must notice.
|
||||
var hero = rig.Db.Heroes.Single();
|
||||
rig.Db.HeroSlides.Add(new Data.Entities.HeroSlide { Id = Guid.NewGuid(), HeroId = hero.Id, ImageId = Guid.Parse(a.Id), Alt = "x", SortOrder = 9 });
|
||||
await rig.Db.SaveChangesAsync();
|
||||
|
||||
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.InUse);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Purging_leaves_a_file_another_photo_still_shares()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var rowA = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(a.Id));
|
||||
var rowB = rig.Db.HeroImages.Single(i => i.Id == Guid.Parse(b.Id));
|
||||
// Two records that point at the same files (not created by the hero itself, but possible after a restore).
|
||||
rowB.SetHash = rowA.SetHash;
|
||||
rowB.OriginalKey = rowA.OriginalKey;
|
||||
await rig.Db.SaveChangesAsync();
|
||||
var provider = Provider(rig);
|
||||
await provider.TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await provider.PurgeAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None)).Should().Be(SlpModularCms.Core.Media.Library.MediaPurgeOutcome.Purged);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().Contain(s => s.SetHash == rowB.SetHash);
|
||||
(await rig.Store.ExistsAsync(rowB.OriginalKey, CancellationToken.None)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_trashed_photo_is_emptied_from_the_trash_after_the_trash_period_and_its_files_go()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
var row = rig.Db.HeroImages.Single();
|
||||
var (set, original) = (row.SetHash, row.OriginalKey);
|
||||
await Provider(rig).TrashAsync(Guid.Parse(a.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(6);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(2);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,6 +412,37 @@ public class HeroMediaCleanupTests
|
||||
again.Variants.Should().OnlyContain(v => v.Url.Contains(set));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsKept_WhenAutomaticCleanupIsOff()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.AutoCleanupUnattached = false;
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(400);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Time.Now = rig.Time.Now.AddDays(400);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APhotoAPersonRemoved_StillLeavesAfterTheRetentionTime_WhenAutomaticCleanupIsOff()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.AutoCleanupUnattached = false;
|
||||
var (set, original) = await RetireAnImage(rig);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsRetiredAndRemoved_AfterTheRetentionTime()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
/// <summary>A new crop works at once, without saving the hero (Bryan, 2026-11-17).</summary>
|
||||
public class HeroSetFocusTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task A_new_crop_starts_processing_at_once_and_goes_live_without_saving_the_hero()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var uploaded = await rig.Upload(HeroTestRig.Photo());
|
||||
var id = Guid.Parse(uploaded.Id);
|
||||
var before = rig.Db.HeroImages.Single(i => i.Id == id).SetHash;
|
||||
|
||||
var answer = await rig.Images.SetFocusAsync(id, new HeroFocusRequest(new FocusDto(0.2, 0.3, 1.5)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
answer.Should().NotBeNull();
|
||||
answer!.Processing.Should().BeTrue("the new variants still have to be cut");
|
||||
answer.Focus.Should().Be(new FocusDto(0.2, 0.3, 1.5));
|
||||
rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().Be(before, "the old set stays live until the new one is complete");
|
||||
|
||||
(await rig.RenderPending()).Should().Be(1);
|
||||
|
||||
var after = (await rig.Images.GetImageAsync(id, CancellationToken.None))!;
|
||||
after.Processing.Should().BeFalse();
|
||||
rig.Db.HeroImages.Single(i => i.Id == id).SetHash.Should().NotBe(before);
|
||||
rig.Db.Heroes.Should().BeEmpty("the hero itself was never saved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_unknown_image_gives_null_and_a_trashed_image_cannot_be_cropped()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var uploaded = await rig.Upload(HeroTestRig.Photo());
|
||||
await new HeroMediaUsageProvider(rig.Repository, rig.Images).TrashAsync(Guid.Parse(uploaded.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
var request = new HeroFocusRequest(new FocusDto(0.5, 0.5, 1));
|
||||
|
||||
(await rig.Images.SetFocusAsync(Guid.NewGuid(), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
(await rig.Images.SetFocusAsync(Guid.Parse(uploaded.Id), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken);
|
||||
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken, file.FileName);
|
||||
return Created($"/api/v1/hero/images/{image.Id}", image);
|
||||
}
|
||||
catch (ImageRejectedException rejection)
|
||||
@@ -105,6 +105,20 @@ public class HeroImagesController(IHeroImageService service, IOptions<MediaOptio
|
||||
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A new crop for an image, applied at once without saving the hero: the new variants are cut in the background and the
|
||||
/// image switches to them when they are complete. Answers with the image (processing).
|
||||
/// </summary>
|
||||
[HttpPut("{id:guid}/focus")]
|
||||
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await service.SetFocusAsync(id, request, HeroCaller.Id(User), cancellationToken);
|
||||
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
|
||||
}
|
||||
|
||||
/// <summary>The formats and limits an upload has to meet on this host (what the validation uses).</summary>
|
||||
[HttpGet("limits")]
|
||||
[ProducesResponseType<HeroUploadLimitsDto>(StatusCodes.Status200OK)]
|
||||
|
||||
@@ -65,6 +65,15 @@ public class HeroImage
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public Guid CreatedByUserId { get; set; }
|
||||
|
||||
/// <summary>The file name as uploaded (for display only, cleaned; never used as a path). Null for photos uploaded before it was stored.</summary>
|
||||
public string? OriginalFileName { get; set; }
|
||||
|
||||
/// <summary>The moment the photo was last detached from a slide; null while it was never used. The clean-up counts from here (decision 8).</summary>
|
||||
public DateTimeOffset? LastUsedAt { get; set; }
|
||||
|
||||
/// <summary>Set when the photo was moved to the trash; its files stay for <c>Media:TrashDays</c> and it is hidden from the hero.</summary>
|
||||
public DateTimeOffset? DeletedAt { get; set; }
|
||||
|
||||
public FocusSetting General => new FocusSetting(FocusX, FocusY, Zoom).Normalize();
|
||||
|
||||
public FocusSetting FocusFor(string ratio) => ratio switch
|
||||
|
||||
@@ -60,6 +60,7 @@ public class HeroDbContext(DbContextOptions<HeroDbContext> options) : DbContext(
|
||||
entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16);
|
||||
entity.Property(e => e.CreatedAt).IsRequired();
|
||||
entity.Property(e => e.CreatedByUserId).IsRequired();
|
||||
entity.Property(e => e.OriginalFileName).HasMaxLength(200);
|
||||
entity.Ignore(e => e.General);
|
||||
|
||||
// The variants of the current set: a small list that is always replaced as a whole.
|
||||
|
||||
@@ -46,6 +46,7 @@ public class HeroModule : IModule
|
||||
services.AddScoped<IPublicHeroService, PublicHeroService>();
|
||||
services.AddScoped<IHeroImageService, HeroImageService>();
|
||||
services.AddScoped<IMediaUsageProvider, HeroMediaUsageProvider>();
|
||||
services.AddScoped<IMediaMigrationSource, HeroMediaMigrationSource>();
|
||||
services.AddScoped<IHeroPageModel, HeroPageModel>();
|
||||
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
|
||||
services.AddScoped<ICmsDataBlockContributor, HeroDataContributor>();
|
||||
|
||||
Generated
+257
@@ -0,0 +1,257 @@
|
||||
// <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("20261117140509_AddMediaLibraryColumns")]
|
||||
partial class AddMediaLibraryColumns
|
||||
{
|
||||
/// <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<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<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<DateTimeOffset?>("DeletedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<double>("FocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("FocusY")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastUsedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("OriginalFileName")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
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,50 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddMediaLibraryColumns : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "DeletedAt",
|
||||
table: "HeroImages",
|
||||
type: "datetime",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "LastUsedAt",
|
||||
table: "HeroImages",
|
||||
type: "datetime",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "OriginalFileName",
|
||||
table: "HeroImages",
|
||||
type: "varchar(200)",
|
||||
maxLength: 200,
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DeletedAt",
|
||||
table: "HeroImages");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "LastUsedAt",
|
||||
table: "HeroImages");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "OriginalFileName",
|
||||
table: "HeroImages");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,9 @@ namespace SlpModularCms.Modules.Hero.Migrations
|
||||
b.Property<Guid>("CreatedByUserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTimeOffset?>("DeletedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<double>("FocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
@@ -102,6 +105,13 @@ namespace SlpModularCms.Modules.Hero.Migrations
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastUsedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("OriginalFileName")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
b.Property<string>("OriginalKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
|
||||
@@ -22,6 +22,24 @@ public interface IHeroRepository
|
||||
/// <summary>Images whose set is missing or does not match their focus, oldest first (tracked).</summary>
|
||||
Task<int> CountImagesAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Every image including those in the trash, not tracked (the media library copy).</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetAllImagesIncludingTrashedReadOnlyAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>An image whether or not it is in the trash, tracked (restore, trash).</summary>
|
||||
Task<HeroImage?> GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The photos in the trash, most recently trashed first, not tracked.</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Photos that were trashed before the cutoff, tracked (the trash is emptied for them).</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>True when an image other than the given one has this set hash or this original key (the files are shared).</summary>
|
||||
Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The slides that use an image, tracked (they are removed when the image goes to the trash).</summary>
|
||||
Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>All images, newest first, not tracked (the media library lists them).</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken);
|
||||
|
||||
@@ -70,32 +88,53 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
public void RemoveSlide(HeroSlide slide) => context.HeroSlides.Remove(slide);
|
||||
|
||||
public Task<HeroImage?> GetImageAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken);
|
||||
|
||||
public Task<HeroImage?> GetImageIncludingTrashedAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetAllImagesIncludingTrashedReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderBy(i => i.CreatedAt).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetTrashedImagesReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).OrderByDescending(i => i.DeletedAt).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetTrashedBeforeAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.Where(i => i.DeletedAt != null).ToListAsync(cancellationToken)).Where(i => i.DeletedAt < cutoff).ToList();
|
||||
|
||||
public async Task<(bool SetShared, bool OriginalShared)> FilesSharedWithOthersAsync(Guid imageId, string setHash, string originalKey, CancellationToken cancellationToken)
|
||||
{
|
||||
var others = (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).Where(i => i.Id != imageId).ToList();
|
||||
return (setHash.Length > 0 && others.Any(i => i.SetHash == setHash), others.Any(i => i.OriginalKey == originalKey));
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<HeroSlide>> GetSlidesOfImageAsync(Guid imageId, CancellationToken cancellationToken)
|
||||
=> await context.HeroSlides.Where(s => s.ImageId == imageId).ToListAsync(cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
// The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they
|
||||
// are read and filtered here.
|
||||
var wanted = ids.ToHashSet();
|
||||
return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
|
||||
return (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList();
|
||||
}
|
||||
|
||||
public Task<int> CountImagesAsync(CancellationToken cancellationToken) => context.HeroImages.CountAsync(cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
|
||||
=> (await context.HeroImages.AsNoTracking().Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<HeroSlide>> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> await context.HeroSlides.AsNoTracking().ToListAsync(cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
|
||||
=> (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList();
|
||||
=> (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList();
|
||||
|
||||
public Task<HeroImage?> GetImageFreshAsync(Guid id, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
|
||||
=> context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken);
|
||||
|
||||
public Task<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
|
||||
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
|
||||
@@ -110,7 +149,7 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
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);
|
||||
var candidates = await context.HeroImages.Where(i => !used.Contains(i.Id) && i.DeletedAt == null).ToListAsync(cancellationToken);
|
||||
return candidates.Where(i => i.CreatedAt < cutoff).ToList();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
@@ -31,7 +32,7 @@ public interface IHeroImageService
|
||||
/// image. Until its set exists the image has no variants and is not published.
|
||||
/// </summary>
|
||||
/// <exception cref="ImageRejectedException">The upload is refused; see the code.</exception>
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken);
|
||||
Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null);
|
||||
|
||||
/// <summary>How many images exist, how many wait for their variants and how many only lack the full-frame preview (for the log).</summary>
|
||||
Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken);
|
||||
@@ -46,6 +47,13 @@ public interface IHeroImageService
|
||||
/// <summary>The variant the renderer is busy with: (done, total), or null when the image is not being cut right now.</summary>
|
||||
(int Done, int Total)? RenderProgress(Guid imageId);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a new crop to an image at once, WITHOUT saving the hero (Bryan, 2026-11-17: a new crop must not need another
|
||||
/// click on Save). The new set is cut in the background and the image switches to it when it is complete, so what is live
|
||||
/// changes only then. Returns the image as the admin sees it now (processing), or null when there is no such image.
|
||||
/// </summary>
|
||||
Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image.</summary>
|
||||
Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken);
|
||||
|
||||
@@ -67,6 +75,22 @@ public interface IHeroImageService
|
||||
|
||||
/// <summary>Removes an image nothing uses; its files go after the retention time.</summary>
|
||||
Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves an image to the trash: the slides that use it are removed from the hero (and remember the moment as its last use),
|
||||
/// it disappears from the hero and its files stay for the trash period. Returns how many slides were removed.
|
||||
/// </summary>
|
||||
/// <exception cref="HeroImageNotFoundException">There is no such image outside the trash.</exception>
|
||||
Task<int> TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Takes an image out of the trash again. False when it is not in the trash.</summary>
|
||||
Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes an image that is in the trash FOR GOOD: its original and its set (a file another image shares stays) and the
|
||||
/// record. Refused when the image is not in the trash or a slide uses it after all.
|
||||
/// </summary>
|
||||
Task<MediaPurgeOutcome> PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public class HeroImageService(
|
||||
@@ -83,7 +107,7 @@ public class HeroImageService(
|
||||
{
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
|
||||
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken)
|
||||
public async Task<HeroImageDto> UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null)
|
||||
{
|
||||
using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken);
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes));
|
||||
@@ -91,8 +115,18 @@ public class HeroImageService(
|
||||
// The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload
|
||||
// repairs them from the file that was just sent.
|
||||
var existing = await repository.GetImageBySha256Async(sha, cancellationToken);
|
||||
var fileName = HeroFileNames.Clean(originalFileName);
|
||||
|
||||
// The same photo uploaded again also brings it back from the trash.
|
||||
if (existing is not null)
|
||||
{
|
||||
existing.DeletedAt = null;
|
||||
existing.OriginalFileName ??= fileName;
|
||||
}
|
||||
|
||||
if (existing is not null && await FilesExistAsync(existing, cancellationToken))
|
||||
{
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
// The same photo again also gives up the failed state: the renderer tries it again when it is still pending.
|
||||
signal?.Reset(existing.Id);
|
||||
signal?.Notify();
|
||||
@@ -118,6 +152,7 @@ public class HeroImageService(
|
||||
Bytes = original.Length,
|
||||
CreatedAt = _time.GetUtcNow(),
|
||||
CreatedByUserId = callerId,
|
||||
OriginalFileName = fileName,
|
||||
};
|
||||
|
||||
// The files first, the row last: an aborted request leaves at most an original nobody refers to (the clean-up
|
||||
@@ -167,6 +202,23 @@ public class HeroImageService(
|
||||
|
||||
public void NotifyPending() => signal?.Notify();
|
||||
|
||||
public async Task<HeroImageDto?> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken);
|
||||
if (image is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
ApplyFocus(image, request);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
signal?.Reset(imageId);
|
||||
signal?.Notify();
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} got a new crop from user {UserId}; its variants are cut in the background", imageId, callerId);
|
||||
return await GetImageAsync(imageId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<HeroImageDto?> GetImageAsync(Guid imageId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageFreshAsync(imageId, cancellationToken);
|
||||
@@ -323,6 +375,81 @@ public class HeroImageService(
|
||||
logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId);
|
||||
}
|
||||
|
||||
public async Task<int> TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
|
||||
var now = _time.GetUtcNow();
|
||||
|
||||
// A slide cannot exist without its image, so the slides that use it go with it; the moment counts as its last use.
|
||||
var slides = await repository.GetSlidesOfImageAsync(imageId, cancellationToken);
|
||||
foreach (var slide in slides)
|
||||
{
|
||||
repository.RemoveSlide(slide);
|
||||
}
|
||||
|
||||
if (slides.Count > 0)
|
||||
{
|
||||
image.LastUsedAt = now;
|
||||
}
|
||||
|
||||
image.DeletedAt = now;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
indexCache?.Invalidate();
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} moved to the trash by user {UserId} ({Slides} slides removed)", imageId, callerId, slides.Count);
|
||||
return slides.Count;
|
||||
}
|
||||
|
||||
public async Task<MediaPurgeOutcome> PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
|
||||
if (image is null || image.DeletedAt is null)
|
||||
{
|
||||
return MediaPurgeOutcome.NotInTrash;
|
||||
}
|
||||
|
||||
if (await repository.ImageInUseAsync(imageId, cancellationToken))
|
||||
{
|
||||
return MediaPurgeOutcome.InUse;
|
||||
}
|
||||
|
||||
// The row first (nothing refers to it any more), then the files; a file another image still shares stays.
|
||||
var (setShared, originalShared) = await repository.FilesSharedWithOthersAsync(imageId, image.SetHash, image.OriginalKey, cancellationToken);
|
||||
var (setHash, originalKey) = (image.SetHash, image.OriginalKey);
|
||||
repository.RemoveImage(image);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
if (setHash.Length > 0 && !setShared)
|
||||
{
|
||||
await store.DeleteSetAsync(HeroMapping.Area, setHash, cancellationToken);
|
||||
}
|
||||
|
||||
if (!originalShared)
|
||||
{
|
||||
await store.DeleteAsync(originalKey, cancellationToken);
|
||||
}
|
||||
|
||||
indexCache?.Invalidate();
|
||||
logger.LogInformation("Hero image {ImageId} removed for good by user {UserId}", imageId, callerId);
|
||||
return MediaPurgeOutcome.Purged;
|
||||
}
|
||||
|
||||
public async Task<bool> RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken);
|
||||
if (image is null || image.DeletedAt is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
image.DeletedAt = null;
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
signal?.Notify();
|
||||
|
||||
logger.LogInformation("Hero image {ImageId} restored from the trash by user {UserId}", imageId, callerId);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign)
|
||||
{
|
||||
if (value is null)
|
||||
@@ -378,3 +505,26 @@ public class HeroImageService(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The file name of an upload as it is shown in the library: cleaned, for display only, never part of a path.</summary>
|
||||
public static class HeroFileNames
|
||||
{
|
||||
public const int MaxLength = 200;
|
||||
|
||||
public static string? Clean(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var last = name[(name.LastIndexOfAny(['/', '\\']) + 1)..];
|
||||
var cleaned = new string(last.Where(c => !char.IsControl(c)).ToArray()).Trim();
|
||||
if (cleaned.Length > MaxLength)
|
||||
{
|
||||
cleaned = cleaned[..MaxLength];
|
||||
}
|
||||
|
||||
return cleaned.Length == 0 ? null : cleaned;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,20 @@ public class HeroMediaCleanup(
|
||||
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))
|
||||
// Skipped when the media library keeps every upload until a person removes it (Media:AutoCleanupUnattached = false).
|
||||
var unattached = options.Value.AutoCleanupUnattached
|
||||
? await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken)
|
||||
: [];
|
||||
foreach (var image in unattached)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
// 1b. Photos that have been in the trash for the trash period: their files go now (they are retired, immediately due).
|
||||
var trashCutoff = now.AddDays(-Math.Max(0, options.Value.TrashDays));
|
||||
foreach (var image in await repository.GetTrashedBeforeAsync(trashCutoff, 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) });
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Offers the hero's photos (also those in the trash) and slides to the media library's copy, with the same ids, hashes and
|
||||
/// set hashes the hero uses. Read-only: the hero's tables are never changed by the copy.
|
||||
/// </summary>
|
||||
public class HeroMediaMigrationSource(IHeroRepository repository) : IMediaMigrationSource
|
||||
{
|
||||
public string Module => HeroMapping.Area;
|
||||
|
||||
public async Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken)
|
||||
=> (await repository.GetAllImagesIncludingTrashedReadOnlyAsync(cancellationToken)).Select(ToSnapshot).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var images = (await repository.GetAllImagesIncludingTrashedReadOnlyAsync(cancellationToken)).ToDictionary(i => i.Id);
|
||||
var slides = await repository.GetAllSlidesReadOnlyAsync(cancellationToken);
|
||||
var uses = new List<MediaUseSnapshot>();
|
||||
foreach (var hero in slides.GroupBy(s => s.HeroId))
|
||||
{
|
||||
var ordered = hero.OrderBy(s => s.SortOrder).ThenBy(s => s.Id).ToList();
|
||||
for (var index = 0; index < ordered.Count; index++)
|
||||
{
|
||||
var slide = ordered[index];
|
||||
var setHash = images.TryGetValue(slide.ImageId, out var image) ? image.SetHash : string.Empty;
|
||||
uses.Add(new MediaUseSnapshot(slide.Id, slide.ImageId, Module, HeroMediaUsageProvider.SlideKind, index + 1, slide.IsActive, setHash));
|
||||
}
|
||||
}
|
||||
|
||||
return uses;
|
||||
}
|
||||
|
||||
private MediaAssetSnapshot ToSnapshot(HeroImage i)
|
||||
=> new(
|
||||
i.Id,
|
||||
Module,
|
||||
i.OriginalSha256,
|
||||
i.OriginalKey,
|
||||
i.SourceFormat,
|
||||
i.Width,
|
||||
i.Height,
|
||||
i.Bytes,
|
||||
i.FocusX,
|
||||
i.FocusY,
|
||||
i.Zoom,
|
||||
i.SetHash,
|
||||
[Crop("wide", i), Crop("tall", i)],
|
||||
i.CreatedAt,
|
||||
i.CreatedByUserId,
|
||||
i.OriginalFileName,
|
||||
i.LastUsedAt,
|
||||
i.DeletedAt);
|
||||
|
||||
private static MediaCropSnapshot Crop(string ratio, HeroImage image)
|
||||
{
|
||||
var focus = image.FocusFor(ratio);
|
||||
return new MediaCropSnapshot(ratio, focus.X, focus.Y, focus.Zoom);
|
||||
}
|
||||
}
|
||||
@@ -7,21 +7,19 @@ namespace SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the
|
||||
/// hero). Read-only: nothing of the hero changes through this class.
|
||||
/// hero), and moves them to the trash and back for it. The files are removed by <see cref="HeroMediaCleanup"/> after the trash period.
|
||||
/// </summary>
|
||||
public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider
|
||||
public class HeroMediaUsageProvider(IHeroRepository repository, IHeroImageService images) : IMediaUsageProvider
|
||||
{
|
||||
public const string SlideKind = "slide";
|
||||
|
||||
public string Module => HeroMapping.Area;
|
||||
|
||||
public async Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var images = await repository.GetAllImagesReadOnlyAsync(cancellationToken);
|
||||
return images
|
||||
.Select(i => new MediaPhoto(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i)))
|
||||
.ToList();
|
||||
}
|
||||
=> (await repository.GetAllImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<MediaPhoto>> ListTrashAsync(CancellationToken cancellationToken)
|
||||
=> (await repository.GetTrashedImagesReadOnlyAsync(cancellationToken)).Select(ToPhoto).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -46,6 +44,27 @@ public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsagePro
|
||||
return uses;
|
||||
}
|
||||
|
||||
public async Task<int?> TrashAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await images.TrashAsync(photoId, callerId, cancellationToken);
|
||||
}
|
||||
catch (HeroImageNotFoundException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> RestoreAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
=> images.RestoreAsync(photoId, callerId, cancellationToken);
|
||||
|
||||
public Task<MediaPurgeOutcome> PurgeAsync(Guid photoId, Guid callerId, CancellationToken cancellationToken)
|
||||
=> images.PurgeAsync(photoId, callerId, cancellationToken);
|
||||
|
||||
private MediaPhoto ToPhoto(HeroImage i)
|
||||
=> new(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i), i.OriginalFileName, i.LastUsedAt, i.DeletedAt);
|
||||
|
||||
/// <summary>The smallest published WebP of the set; null while the set is not cut yet.</summary>
|
||||
private static string? Thumbnail(HeroImage image)
|
||||
{
|
||||
|
||||
@@ -121,8 +121,15 @@ public class HeroService(
|
||||
slide.SortOrder = i;
|
||||
}
|
||||
|
||||
// A photo that no slide uses any more remembers when it was last used (the media library counts from there).
|
||||
var stillUsed = slideRequests.Select(r => r.ImageId).ToHashSet();
|
||||
foreach (var removed in hero.Slides.Where(s => !keep.Contains(s.Id)).ToList())
|
||||
{
|
||||
if (removed.Image is { } detached && !stillUsed.Contains(detached.Id))
|
||||
{
|
||||
detached.LastUsedAt = now;
|
||||
}
|
||||
|
||||
hero.Slides.Remove(removed);
|
||||
if (!created)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
using SlpModularCms.Modules.Media.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Tests;
|
||||
|
||||
public class MediaLibraryCopierTests : IDisposable
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
|
||||
private readonly MediaDbContext _db = new(new DbContextOptionsBuilder<MediaDbContext>().UseInMemoryDatabase("media-" + Guid.NewGuid()).Options);
|
||||
|
||||
public void Dispose() => _db.Dispose();
|
||||
|
||||
private sealed class Source(string module, List<MediaAssetSnapshot> assets, List<MediaUseSnapshot> uses) : IMediaMigrationSource
|
||||
{
|
||||
public string Module => module;
|
||||
|
||||
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaAssetSnapshot>>(assets.ToList());
|
||||
|
||||
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaUseSnapshot>>(uses.ToList());
|
||||
}
|
||||
|
||||
private static MediaAssetSnapshot Asset(string module = "hero", string? sha = null, string setHash = "0123456789abcdef", DateTimeOffset? deleted = null)
|
||||
=> new(Guid.NewGuid(), module, sha ?? Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"), "originals/x.jpg", "jpg", 3000, 2000, 2_000_000, 0.4, 0.6, 1.5, setHash,
|
||||
[new MediaCropSnapshot("wide", 0.4, 0.6, 1.5), new MediaCropSnapshot("tall", 0.5, 0.5, 1)], Now.AddDays(-9), Guid.NewGuid(), "zomer.jpg", Now.AddDays(-2), deleted);
|
||||
|
||||
private static MediaUseSnapshot Use(MediaAssetSnapshot asset, int position = 1, bool active = true)
|
||||
=> new(Guid.NewGuid(), asset.Id, asset.Module, "slide", position, active, asset.SetHash);
|
||||
|
||||
private MediaLibraryCopier Copier(params IMediaMigrationSource[] sources) => new(_db, sources, NullLogger<MediaLibraryCopier>.Instance);
|
||||
|
||||
[Fact]
|
||||
public async Task Copies_the_photos_and_uses_with_the_same_ids_hashes_and_set_hashes()
|
||||
{
|
||||
var a = Asset();
|
||||
var b = Asset(deleted: Now.AddDays(-1));
|
||||
var use = Use(a, 3, active: false);
|
||||
|
||||
var report = await Copier(new Source("hero", [a, b], [use])).CopyAsync(CancellationToken.None);
|
||||
|
||||
report.Should().Match<MediaCopyReport>(r => r.Assets == 2 && r.Uses == 1 && r.Verified);
|
||||
var copy = await _db.MediaAssets.Include(x => x.Uses).SingleAsync(x => x.Id == a.Id);
|
||||
copy.OriginalSha256.Should().Be(a.OriginalSha256);
|
||||
copy.OriginalKey.Should().Be(a.OriginalKey);
|
||||
copy.OriginalFileName.Should().Be("zomer.jpg");
|
||||
copy.LastUsedAt.Should().Be(a.LastUsedAt);
|
||||
copy.DefaultFocusX.Should().Be(0.4);
|
||||
copy.Uses.Should().ContainSingle().Which.Should().Match<Data.Entities.MediaAssetUse>(u => u.Id == use.Id && u.SetHash == a.SetHash && u.Position == 3 && !u.Active && u.PlaceKind == "slide");
|
||||
copy.Uses[0].Crops.Should().Contain("wide").And.Contain("0.4");
|
||||
(await _db.MediaAssets.SingleAsync(x => x.Id == b.Id)).DeletedAt.Should().Be(b.DeletedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Copying_twice_gives_the_same_result()
|
||||
{
|
||||
var a = Asset();
|
||||
var copier = Copier(new Source("hero", [a], [Use(a)]));
|
||||
|
||||
await copier.CopyAsync(CancellationToken.None);
|
||||
var second = await copier.CopyAsync(CancellationToken.None);
|
||||
|
||||
second.Should().Match<MediaCopyReport>(r => r.Assets == 1 && r.Uses == 1 && r.Verified);
|
||||
(await _db.MediaAssets.CountAsync()).Should().Be(1);
|
||||
(await _db.MediaUses.CountAsync()).Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_copy_mirrors_the_source_a_changed_photo_is_updated_and_a_removed_one_leaves()
|
||||
{
|
||||
var a = Asset();
|
||||
var gone = Asset();
|
||||
var assets = new List<MediaAssetSnapshot> { a, gone };
|
||||
var uses = new List<MediaUseSnapshot> { Use(a), Use(gone) };
|
||||
var copier = Copier(new Source("hero", assets, uses));
|
||||
await copier.CopyAsync(CancellationToken.None);
|
||||
|
||||
assets.Remove(gone);
|
||||
uses.RemoveAll(u => u.AssetId == gone.Id);
|
||||
assets[0] = a with { SetHash = "fedcba9876543210", OriginalFileName = "nieuw.jpg" };
|
||||
uses[0] = uses[0] with { SetHash = "fedcba9876543210" };
|
||||
await copier.CopyAsync(CancellationToken.None);
|
||||
|
||||
(await _db.MediaAssets.ToListAsync()).Should().ContainSingle().Which.OriginalFileName.Should().Be("nieuw.jpg");
|
||||
(await _db.MediaUses.ToListAsync()).Should().ContainSingle().Which.SetHash.Should().Be("fedcba9876543210");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Photos_of_a_module_without_a_source_are_left_alone()
|
||||
{
|
||||
var other = Asset(module: "gallery");
|
||||
_db.MediaAssets.Add(new Data.Entities.MediaAsset { Id = other.Id, Module = "gallery", OriginalSha256 = other.OriginalSha256, OriginalKey = "k", SourceFormat = "jpg" });
|
||||
await _db.SaveChangesAsync();
|
||||
var a = Asset();
|
||||
|
||||
await Copier(new Source("hero", [a], [])).CopyAsync(CancellationToken.None);
|
||||
|
||||
(await _db.MediaAssets.CountAsync()).Should().Be(2);
|
||||
(await _db.MediaAssets.AnyAsync(x => x.Id == other.Id)).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_sources_are_copied_together()
|
||||
{
|
||||
var hero = Asset();
|
||||
var gallery = Asset(module: "gallery");
|
||||
|
||||
var report = await Copier(new Source("hero", [hero], [Use(hero)]), new Source("gallery", [gallery], [])).CopyAsync(CancellationToken.None);
|
||||
|
||||
report.Assets.Should().Be(2);
|
||||
report.Uses.Should().Be(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using MySql.Data.MySqlClient;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
using SlpModularCms.Modules.Media.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The copy against a real MariaDB in a database of its own (created and dropped here): the migration, the foreign key and the
|
||||
/// rollback of a failed copy. Runs when <c>ConnectionStrings__DefaultConnection</c> is set (CI sets it); otherwise it does nothing.
|
||||
/// </summary>
|
||||
public class MediaLibraryMariaDbTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static string? ConnectionString()
|
||||
{
|
||||
var baseString = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
|
||||
if (string.IsNullOrWhiteSpace(baseString))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var builder = new MySqlConnectionStringBuilder(baseString) { Database = "media_library_test_" + Guid.NewGuid().ToString("N")[..12] };
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
|
||||
private static MediaDbContext Open(string connectionString)
|
||||
=> new(new DbContextOptionsBuilder<MediaDbContext>().UseMySQL(connectionString).ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>().Options);
|
||||
|
||||
private sealed class Source(List<MediaAssetSnapshot> assets, List<MediaUseSnapshot> uses) : IMediaMigrationSource
|
||||
{
|
||||
public string Module => "hero";
|
||||
|
||||
public Task<IReadOnlyList<MediaAssetSnapshot>> ListAssetsAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaAssetSnapshot>>(assets);
|
||||
|
||||
public Task<IReadOnlyList<MediaUseSnapshot>> ListUsesAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaUseSnapshot>>(uses);
|
||||
}
|
||||
|
||||
private static MediaAssetSnapshot Asset(string sha)
|
||||
=> new(Guid.NewGuid(), "hero", sha, "originals/x.jpg", "jpg", 3000, 2000, 2_000_000, 0.4, 0.6, 1.5, "0123456789abcdef",
|
||||
[new MediaCropSnapshot("wide", 0.4, 0.6, 1.5)], Now.AddDays(-9), Guid.NewGuid(), "zomer.jpg", Now.AddDays(-2), null);
|
||||
|
||||
[Fact]
|
||||
public async Task The_migration_creates_the_tables_and_a_verified_copy_survives_a_second_run()
|
||||
{
|
||||
var connection = ConnectionString();
|
||||
if (connection is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var db = Open(connection);
|
||||
try
|
||||
{
|
||||
await db.Database.MigrateAsync();
|
||||
var a = Asset(new string('a', 64));
|
||||
var b = Asset(new string('b', 64));
|
||||
var uses = new List<MediaUseSnapshot> { new(Guid.NewGuid(), a.Id, "hero", "slide", 1, true, a.SetHash) };
|
||||
var copier = new MediaLibraryCopier(db, [new Source([a, b], uses)], NullLogger<MediaLibraryCopier>.Instance);
|
||||
|
||||
var first = await copier.CopyAsync(CancellationToken.None);
|
||||
var second = await copier.CopyAsync(CancellationToken.None);
|
||||
|
||||
first.Should().Match<MediaCopyReport>(r => r.Assets == 2 && r.Uses == 1 && r.Verified);
|
||||
second.Verified.Should().BeTrue();
|
||||
(await db.MediaAssets.CountAsync()).Should().Be(2);
|
||||
(await db.MediaUses.CountAsync()).Should().Be(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.Database.EnsureDeletedAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_failed_copy_is_rolled_back_completely()
|
||||
{
|
||||
var connection = ConnectionString();
|
||||
if (connection is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var db = Open(connection);
|
||||
try
|
||||
{
|
||||
await db.Database.MigrateAsync();
|
||||
var good = Asset(new string('c', 64));
|
||||
await new MediaLibraryCopier(db, [new Source([good], [])], NullLogger<MediaLibraryCopier>.Instance).CopyAsync(CancellationToken.None);
|
||||
|
||||
// Two photos with the same hash break the unique index: the whole copy must be undone, the earlier copy stays.
|
||||
var one = Asset(new string('d', 64));
|
||||
var two = Asset(new string('d', 64));
|
||||
var failing = new MediaLibraryCopier(db, [new Source([good, one, two], [])], NullLogger<MediaLibraryCopier>.Instance);
|
||||
|
||||
var act = () => failing.CopyAsync(CancellationToken.None);
|
||||
|
||||
await act.Should().ThrowAsync<Exception>();
|
||||
await using var check = Open(connection);
|
||||
(await check.MediaAssets.Select(x => x.Id).ToListAsync()).Should().Equal(good.Id);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.Database.EnsureDeletedAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.Media\SlpModularCms.Modules.Media.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace SlpModularCms.Modules.Media.Data.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// A photo in the library: the original (never served), its default focus and when it was last used or trashed. The ids,
|
||||
/// hashes and keys are the ones the owning module already uses, so public addresses stay as they are.
|
||||
/// </summary>
|
||||
public class MediaAsset
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>The module that uploaded it (for example <c>hero</c>); the library is shared, this only says where it came from.</summary>
|
||||
public string Module { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>SHA-256 of the file as uploaded (hex); the same photo uploaded twice is one record.</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 DefaultFocusX { get; set; } = 0.5;
|
||||
public double DefaultFocusY { get; set; } = 0.5;
|
||||
public double DefaultZoom { get; set; } = 1.0;
|
||||
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public Guid CreatedByUserId { get; set; }
|
||||
public string? OriginalFileName { get; set; }
|
||||
public DateTimeOffset? LastUsedAt { get; set; }
|
||||
public DateTimeOffset? DeletedAt { get; set; }
|
||||
|
||||
public List<MediaAssetUse> Uses { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One place where a photo is used, with its own crops. The set hash is computed by the module with the existing formula
|
||||
/// over the photo's hash and these crops.
|
||||
/// </summary>
|
||||
public class MediaAssetUse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid AssetId { get; set; }
|
||||
public MediaAsset? Asset { get; set; }
|
||||
|
||||
public string Module { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>For example <c>slide</c>.</summary>
|
||||
public string PlaceKind { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The 1-based position in the place (display order).</summary>
|
||||
public int Position { get; set; }
|
||||
|
||||
public bool Active { get; set; } = true;
|
||||
public string SetHash { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The crops of this use as JSON: <c>[{ratio, x, y, zoom}]</c>. Empty for a natural-ratio use.</summary>
|
||||
public string Crops { get; set; } = "[]";
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SlpModularCms.Modules.Media.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Data;
|
||||
|
||||
public class MediaDbContext(DbContextOptions<MediaDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<MediaAsset> MediaAssets => Set<MediaAsset>();
|
||||
public DbSet<MediaAssetUse> MediaUses => Set<MediaAssetUse>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<MediaAsset>(entity =>
|
||||
{
|
||||
entity.ToTable("MediaAssets");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Module).IsRequired().HasMaxLength(20);
|
||||
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.OriginalFileName).HasMaxLength(200);
|
||||
entity.HasIndex(e => e.CreatedAt);
|
||||
entity.HasMany(e => e.Uses).WithOne(u => u.Asset).HasForeignKey(u => u.AssetId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<MediaAssetUse>(entity =>
|
||||
{
|
||||
entity.ToTable("MediaUses");
|
||||
entity.HasKey(e => e.Id);
|
||||
entity.Property(e => e.Module).IsRequired().HasMaxLength(20);
|
||||
entity.Property(e => e.PlaceKind).IsRequired().HasMaxLength(20);
|
||||
entity.Property(e => e.SetHash).IsRequired().HasMaxLength(16);
|
||||
entity.Property(e => e.Crops).IsRequired().HasColumnType("longtext");
|
||||
entity.HasIndex(e => e.AssetId);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SlpModularCms.Modules.Media;
|
||||
|
||||
/// <summary>Settings of the library's own tables (<c>Media:Library:*</c>). Everything is off by default: a deploy of the code alone only adds the empty tables.</summary>
|
||||
public class MediaLibraryOptions
|
||||
{
|
||||
public const string SectionName = "Media:Library";
|
||||
|
||||
/// <summary>
|
||||
/// Copy the photos and uses of the modules into the library's tables once at start-up and verify the copy
|
||||
/// (<c>Media__Library__CopyOnStartup=true</c>). Safe to repeat: the copy mirrors the source. Never touches the modules' own data.
|
||||
/// </summary>
|
||||
public bool CopyOnStartup { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Modules;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
using SlpModularCms.Modules.Media.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Media;
|
||||
|
||||
/// <summary>
|
||||
/// The library's own tables (photos and where they are used). Phase 1 of the migration plan: only the tables, and a copy
|
||||
/// of the modules' photos behind <c>Media:Library:CopyOnStartup</c> (off by default). Nothing reads from these tables yet.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaModule : IModule
|
||||
{
|
||||
public string Name => "Media";
|
||||
public string Version => "1.0.0";
|
||||
|
||||
public void RegisterServices(IServiceCollection services)
|
||||
{
|
||||
services.AddDbContext<MediaDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
var config = serviceProvider.GetRequiredService<IConfiguration>();
|
||||
options.UseMySQL(config.GetConnectionString("DefaultConnection")!);
|
||||
options.ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>();
|
||||
});
|
||||
|
||||
services.AddOptions<MediaLibraryOptions>().Configure<IConfiguration>((options, configuration) =>
|
||||
configuration.GetSection(MediaLibraryOptions.SectionName).Bind(options));
|
||||
services.AddScoped<MediaLibraryCopier>();
|
||||
services.AddHostedService<MediaLibraryCopyService>();
|
||||
}
|
||||
|
||||
public void UseModule(IApplicationBuilder app)
|
||||
{
|
||||
using var scope = app.ApplicationServices.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MediaDbContext>();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the verified copy once at start-up when <c>Media:Library:CopyOnStartup</c> is on; a failure is logged and never stops the host.</summary>
|
||||
public sealed class MediaLibraryCopyService(IServiceScopeFactory scopes, IOptions<MediaLibraryOptions> options, ILogger<MediaLibraryCopyService> logger) : IHostedService
|
||||
{
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!options.Value.CopyOnStartup)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<MediaLibraryCopier>().CopyAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(exception, "The media library copy failed and was rolled back; the modules' own data is untouched.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Migrations
|
||||
{
|
||||
[DbContext(typeof(MediaDbContext))]
|
||||
[Migration("20261117143138_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.Media.Data.Entities.MediaAsset", 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>("DefaultFocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("DefaultFocusY")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("DefaultZoom")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<DateTimeOffset?>("DeletedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastUsedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Module")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("OriginalFileName")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
b.Property<string>("OriginalKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
b.Property<string>("OriginalSha256")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<string>("SourceFormat")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("varchar(10)");
|
||||
|
||||
b.Property<int>("Width")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.HasIndex("OriginalSha256")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("MediaAssets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("Active")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<Guid>("AssetId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Crops")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Module")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("PlaceKind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<int>("Position")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("SetHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("varchar(16)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AssetId");
|
||||
|
||||
b.ToTable("MediaUses", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", "Asset")
|
||||
.WithMany("Uses")
|
||||
.HasForeignKey("AssetId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Asset");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b =>
|
||||
{
|
||||
b.Navigation("Uses");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterDatabase()
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MediaAssets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Module = table.Column<string>(type: "varchar(20)", maxLength: 20, 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),
|
||||
DefaultFocusX = table.Column<double>(type: "double", nullable: false),
|
||||
DefaultFocusY = table.Column<double>(type: "double", nullable: false),
|
||||
DefaultZoom = table.Column<double>(type: "double", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
|
||||
CreatedByUserId = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
OriginalFileName = table.Column<string>(type: "varchar(200)", maxLength: 200, nullable: true),
|
||||
LastUsedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
|
||||
DeletedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MediaAssets", x => x.Id);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MediaUses",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
AssetId = table.Column<Guid>(type: "char(36)", nullable: false),
|
||||
Module = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
|
||||
PlaceKind = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
|
||||
Position = table.Column<int>(type: "int", nullable: false),
|
||||
Active = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
SetHash = table.Column<string>(type: "varchar(16)", maxLength: 16, nullable: false),
|
||||
Crops = table.Column<string>(type: "longtext", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MediaUses", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_MediaUses_MediaAssets_AssetId",
|
||||
column: x => x.AssetId,
|
||||
principalTable: "MediaAssets",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySQL:Charset", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MediaAssets_CreatedAt",
|
||||
table: "MediaAssets",
|
||||
column: "CreatedAt");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MediaAssets_OriginalSha256",
|
||||
table: "MediaAssets",
|
||||
column: "OriginalSha256",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MediaUses_AssetId",
|
||||
table: "MediaUses",
|
||||
column: "AssetId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "MediaUses");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MediaAssets");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Migrations
|
||||
{
|
||||
[DbContext(typeof(MediaDbContext))]
|
||||
partial class MediaDbContextModelSnapshot : 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.Media.Data.Entities.MediaAsset", 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>("DefaultFocusX")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("DefaultFocusY")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<double>("DefaultZoom")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<DateTimeOffset?>("DeletedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<int>("Height")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset?>("LastUsedAt")
|
||||
.HasColumnType("datetime");
|
||||
|
||||
b.Property<string>("Module")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("OriginalFileName")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
b.Property<string>("OriginalKey")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("varchar(200)");
|
||||
|
||||
b.Property<string>("OriginalSha256")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("varchar(64)");
|
||||
|
||||
b.Property<string>("SourceFormat")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("varchar(10)");
|
||||
|
||||
b.Property<int>("Width")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.HasIndex("OriginalSha256")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("MediaAssets", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("Active")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<Guid>("AssetId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Crops")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Module")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<string>("PlaceKind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("varchar(20)");
|
||||
|
||||
b.Property<int>("Position")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("SetHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("varchar(16)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AssetId");
|
||||
|
||||
b.ToTable("MediaUses", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAssetUse", b =>
|
||||
{
|
||||
b.HasOne("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", "Asset")
|
||||
.WithMany("Uses")
|
||||
.HasForeignKey("AssetId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Asset");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SlpModularCms.Modules.Media.Data.Entities.MediaAsset", b =>
|
||||
{
|
||||
b.Navigation("Uses");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using SlpModularCms.Modules.Media.Data;
|
||||
using SlpModularCms.Modules.Media.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Media.Services;
|
||||
|
||||
/// <summary>What a copy did and what the verification found.</summary>
|
||||
public sealed record MediaCopyReport(int Assets, int Uses, IReadOnlyList<string> Differences)
|
||||
{
|
||||
public bool Verified => Differences.Count == 0;
|
||||
}
|
||||
|
||||
public sealed class MediaCopyVerificationException(MediaCopyReport report)
|
||||
: Exception($"The copy of the media library does not match its source: {string.Join("; ", report.Differences.Take(5))}")
|
||||
{
|
||||
public MediaCopyReport Report { get; } = report;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the photos and uses of every module (<see cref="IMediaMigrationSource"/>) into the library's own tables and
|
||||
/// verifies the copy against the source (migration plan, decision 13). The copy MIRRORS the source: re-running it gives
|
||||
/// the same result, rows of a module that no longer exist at the source are removed from the copy. The modules' own data
|
||||
/// is never changed. A difference after copying rolls the whole copy back and raises <see cref="MediaCopyVerificationException"/>.
|
||||
/// </summary>
|
||||
public sealed class MediaLibraryCopier(MediaDbContext db, IEnumerable<IMediaMigrationSource> sources, ILogger<MediaLibraryCopier> logger)
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public async Task<MediaCopyReport> CopyAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var assets = new List<MediaAssetSnapshot>();
|
||||
var uses = new List<MediaUseSnapshot>();
|
||||
var modules = new List<string>();
|
||||
foreach (var source in sources)
|
||||
{
|
||||
modules.Add(source.Module);
|
||||
assets.AddRange(await source.ListAssetsAsync(cancellationToken));
|
||||
uses.AddRange(await source.ListUsesAsync(cancellationToken));
|
||||
}
|
||||
|
||||
var transaction = db.Database.IsRelational() ? await db.Database.BeginTransactionAsync(cancellationToken) : null;
|
||||
try
|
||||
{
|
||||
await MirrorAsync(assets, uses, modules, cancellationToken);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var report = await VerifyAsync(assets, uses, modules, cancellationToken);
|
||||
if (!report.Verified)
|
||||
{
|
||||
throw new MediaCopyVerificationException(report);
|
||||
}
|
||||
|
||||
if (transaction is not null)
|
||||
{
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
}
|
||||
|
||||
logger.LogInformation("Media library copy verified: {Assets} photos and {Uses} uses from {Modules}.", report.Assets, report.Uses, string.Join(", ", modules));
|
||||
return report;
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (transaction is not null)
|
||||
{
|
||||
await transaction.RollbackAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
db.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (transaction is not null)
|
||||
{
|
||||
await transaction.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MirrorAsync(IReadOnlyList<MediaAssetSnapshot> assets, IReadOnlyList<MediaUseSnapshot> uses, IReadOnlyList<string> modules, CancellationToken cancellationToken)
|
||||
{
|
||||
var existingAssets = new Dictionary<Guid, MediaAsset>();
|
||||
var existingUses = new Dictionary<Guid, MediaAssetUse>();
|
||||
foreach (var module in modules)
|
||||
{
|
||||
// One equality query per module: the MySQL provider cannot translate a list parameter in an IN clause.
|
||||
foreach (var asset in await db.MediaAssets.Where(a => a.Module == module).ToListAsync(cancellationToken))
|
||||
{
|
||||
existingAssets[asset.Id] = asset;
|
||||
}
|
||||
|
||||
foreach (var use in await db.MediaUses.Where(u => u.Module == module).ToListAsync(cancellationToken))
|
||||
{
|
||||
existingUses[use.Id] = use;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var snapshot in assets)
|
||||
{
|
||||
if (!existingAssets.Remove(snapshot.Id, out var row))
|
||||
{
|
||||
row = new MediaAsset { Id = snapshot.Id };
|
||||
db.MediaAssets.Add(row);
|
||||
}
|
||||
|
||||
row.Module = snapshot.Module;
|
||||
row.OriginalSha256 = snapshot.OriginalSha256;
|
||||
row.OriginalKey = snapshot.OriginalKey;
|
||||
row.SourceFormat = snapshot.SourceFormat;
|
||||
row.Width = snapshot.Width;
|
||||
row.Height = snapshot.Height;
|
||||
row.Bytes = snapshot.Bytes;
|
||||
row.DefaultFocusX = snapshot.FocusX;
|
||||
row.DefaultFocusY = snapshot.FocusY;
|
||||
row.DefaultZoom = snapshot.Zoom;
|
||||
row.CreatedAt = snapshot.CreatedAt;
|
||||
row.CreatedByUserId = snapshot.CreatedByUserId;
|
||||
row.OriginalFileName = snapshot.OriginalFileName;
|
||||
row.LastUsedAt = snapshot.LastUsedAt;
|
||||
row.DeletedAt = snapshot.DeletedAt;
|
||||
}
|
||||
|
||||
// Uses reference their asset; the crops of a use are the crops of its photo (the hero's wide and tall).
|
||||
var cropsByAsset = assets.ToDictionary(a => a.Id, a => JsonSerializer.Serialize(a.Crops, Json));
|
||||
foreach (var snapshot in uses)
|
||||
{
|
||||
if (!existingUses.Remove(snapshot.Id, out var row))
|
||||
{
|
||||
row = new MediaAssetUse { Id = snapshot.Id };
|
||||
db.MediaUses.Add(row);
|
||||
}
|
||||
|
||||
row.AssetId = snapshot.AssetId;
|
||||
row.Module = snapshot.Module;
|
||||
row.PlaceKind = snapshot.PlaceKind;
|
||||
row.Position = snapshot.Position;
|
||||
row.Active = snapshot.Active;
|
||||
row.SetHash = snapshot.SetHash;
|
||||
row.Crops = cropsByAsset.TryGetValue(snapshot.AssetId, out var crops) ? crops : "[]";
|
||||
}
|
||||
|
||||
// What is left no longer exists at the source.
|
||||
db.MediaUses.RemoveRange(existingUses.Values);
|
||||
db.MediaAssets.RemoveRange(existingAssets.Values);
|
||||
}
|
||||
|
||||
private async Task<MediaCopyReport> VerifyAsync(IReadOnlyList<MediaAssetSnapshot> assets, IReadOnlyList<MediaUseSnapshot> uses, IReadOnlyList<string> modules, CancellationToken cancellationToken)
|
||||
{
|
||||
var differences = new List<string>();
|
||||
var copiedAssets = new Dictionary<Guid, MediaAsset>();
|
||||
var copiedUses = new Dictionary<Guid, MediaAssetUse>();
|
||||
foreach (var module in modules)
|
||||
{
|
||||
foreach (var asset in await db.MediaAssets.AsNoTracking().Where(a => a.Module == module).ToListAsync(cancellationToken))
|
||||
{
|
||||
copiedAssets[asset.Id] = asset;
|
||||
}
|
||||
|
||||
foreach (var use in await db.MediaUses.AsNoTracking().Where(u => u.Module == module).ToListAsync(cancellationToken))
|
||||
{
|
||||
copiedUses[use.Id] = use;
|
||||
}
|
||||
}
|
||||
|
||||
if (copiedAssets.Count != assets.Count)
|
||||
{
|
||||
differences.Add($"photos: source {assets.Count}, copy {copiedAssets.Count}");
|
||||
}
|
||||
|
||||
if (copiedUses.Count != uses.Count)
|
||||
{
|
||||
differences.Add($"uses: source {uses.Count}, copy {copiedUses.Count}");
|
||||
}
|
||||
|
||||
foreach (var asset in assets)
|
||||
{
|
||||
if (!copiedAssets.TryGetValue(asset.Id, out var copy))
|
||||
{
|
||||
differences.Add($"photo {asset.Id} is missing in the copy");
|
||||
}
|
||||
else if (copy.OriginalSha256 != asset.OriginalSha256 || copy.OriginalKey != asset.OriginalKey || copy.Bytes != asset.Bytes)
|
||||
{
|
||||
differences.Add($"photo {asset.Id}: hash, key or size differs");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var use in uses)
|
||||
{
|
||||
if (!copiedUses.TryGetValue(use.Id, out var copy))
|
||||
{
|
||||
differences.Add($"use {use.Id} is missing in the copy");
|
||||
}
|
||||
else if (copy.SetHash != use.SetHash || copy.AssetId != use.AssetId)
|
||||
{
|
||||
differences.Add($"use {use.Id}: set hash or photo differs");
|
||||
}
|
||||
}
|
||||
|
||||
return new MediaCopyReport(copiedAssets.Count, copiedUses.Count, differences);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<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.Media.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user