diff --git a/.gitea/workflows/continuous_integration.yaml b/.gitea/workflows/continuous_integration.yaml index f894507..19eac84 100644 --- a/.gitea/workflows/continuous_integration.yaml +++ b/.gitea/workflows/continuous_integration.yaml @@ -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 diff --git a/.gitea/workflows/deploy-scp.yaml b/.gitea/workflows/deploy-scp.yaml index 7bb47a1..9b5c873 100644 --- a/.gitea/workflows/deploy-scp.yaml +++ b/.gitea/workflows/deploy-scp.yaml @@ -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 diff --git a/SlpModularCms.Ci.slnf b/SlpModularCms.Ci.slnf index 1265755..ac3ee04 100644 --- a/SlpModularCms.Ci.slnf +++ b/SlpModularCms.Ci.slnf @@ -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" ] diff --git a/SlpModularCms.sln b/SlpModularCms.sln index 836c7b3..e1ed2e1 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -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 diff --git a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md index b67b3c4..0c84186 100644 --- a/aidlc-docs/features/hero-module/assumptions-and-open-questions.md +++ b/aidlc-docs/features/hero-module/assumptions-and-open-questions.md @@ -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`. diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md index e4d56f5..511d9b2 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/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//...`) 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//...`) 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 `/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`) | diff --git a/aidlc-docs/features/media-library/inception/application-design/application-design.md b/aidlc-docs/features/media-library/inception/application-design/application-design.md index 24fb79e..cc190e8 100644 --- a/aidlc-docs/features/media-library/inception/application-design/application-design.md +++ b/aidlc-docs/features/media-library/inception/application-design/application-design.md @@ -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`, 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). diff --git a/aidlc-docs/features/media-library/inception/application-design/migration-plan.md b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md new file mode 100644 index 0000000..d8f126d --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/migration-plan.md @@ -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//...` 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 > 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 -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//`) 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//...` 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. diff --git a/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md b/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md new file mode 100644 index 0000000..2d1fd45 --- /dev/null +++ b/aidlc-docs/features/media-library/inception/application-design/per-use-crop.md @@ -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). diff --git a/aidlc-docs/features/media-library/inception/requirements/requirements.md b/aidlc-docs/features/media-library/inception/requirements/requirements.md index 0ab42a7..6632683 100644 --- a/aidlc-docs/features/media-library/inception/requirements/requirements.md +++ b/aidlc-docs/features/media-library/inception/requirements/requirements.md @@ -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//-.` 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`. | diff --git a/docs/hero-module.md b/docs/hero-module.md index 02e46c6..a5fca83 100644 --- a/docs/hero-module.md +++ b/docs/hero-module.md @@ -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 (``), 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. | diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index ca75982..e5c84c4 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -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', diff --git a/frontend/src/features/hero/components/FocusDialog.tsx b/frontend/src/features/hero/components/FocusDialog.tsx index 2c47ab8..5e7a4de 100644 --- a/frontend/src/features/hero/components/FocusDialog.tsx +++ b/frontend/src/features/hero/components/FocusDialog.tsx @@ -98,7 +98,6 @@ function FocusEditor({ image, onApply, onClose }: { image: HeroImageDto; onApply return (

{t('hero.focus.intro')}

-

{t('hero.focus.applyHint')}

{t('hero.focus.targetLegend')} diff --git a/frontend/src/features/hero/components/LibraryPickerDialog.tsx b/frontend/src/features/hero/components/LibraryPickerDialog.tsx new file mode 100644 index 0000000..7586574 --- /dev/null +++ b/frontend/src/features/hero/components/LibraryPickerDialog.tsx @@ -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()); + const items = (library.data?.photos ?? []).filter((p) => p.module === MODULE).map((p) => toPhotoItem(p, t)); + + const uploadHere = async (file: File): Promise => { + 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 ( + + + + {t('hero.library.title')} + {t('hero.library.description')} + + {library.isError && ( +

+ {t('media.error')} +

+ )} + {library.isPending ? ( +

{t('media.loading')}

+ ) : ( + { + const imageId = id.slice(MODULE.length + 1); + onChoose(imageId, uploaded.current.get(imageId)); + }} + onUpload={uploadHere} + maxUploadBytes={maxUploadBytes} + limitsText={limitsText} + label={t('hero.library.group')} + /> + )} +
+
+ ); +} diff --git a/frontend/src/features/hero/components/ProcessingStatus.tsx b/frontend/src/features/hero/components/ProcessingStatus.tsx index 9b0c11d..cb0bd91 100644 --- a/frontend/src/features/hero/components/ProcessingStatus.tsx +++ b/frontend/src/features/hero/components/ProcessingStatus.tsx @@ -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 (
{working > 0 && (
-

- - {t('hero.processing.count', { done, total })} +

+ {t('hero.processing.count', { done, total })}

-
-
-
- {busy && ( -

- {t('hero.processing.current', { n: done + 1, total, step: busy.renderDone ?? 0, steps: busy.renderTotal })} -

- )} +

{t('hero.processing.explain')}

{t('hero.processing.stuck')}{' '} @@ -97,40 +85,38 @@ export function PhotoPlaceholder({ failed, testId, step }: { failed: boolean; te const { t } = useTranslation(); return (

- {failed ? null : } - {failed ? t('hero.slides.failed') : t('hero.slides.processing')} - {!failed && step ? {step.done}/{step.total} : null} - {!failed && !step ? {t('hero.slides.queued')} : null} + {failed ? ( + {t('hero.slides.failed')} + ) : ( + + )}
); } /** - * 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 ( -
+
- - {failed ? null : } - {failed ? t('hero.slides.failed') : t('hero.slides.recut')} - {!failed && step ? {step.done}/{step.total} : null} - +
+ {failed ? {t('hero.slides.failed')} : } +
); } diff --git a/frontend/src/features/hero/components/UploadProgress.tsx b/frontend/src/features/hero/components/UploadProgress.tsx index 13a8ded..ca0afb0 100644 --- a/frontend/src/features/hero/components/UploadProgress.tsx +++ b/frontend/src/features/hero/components/UploadProgress.tsx @@ -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) => (
  • - {item.status === 'uploading' && } + {item.status === 'uploading' &&