# Application design (draft on assumptions): media-library Status: draft, built on `assumptions-and-open-questions.md`. Nothing here moves data or changes public addresses. ## 1. Components ```mermaid graph TD UI[Admin: Media library screen] --> API[MediaLibraryController] UI --> SEL[Selection + BulkActionBar components] API --> LIB[MediaLibraryService] LIB --> USE[MediaUsageService] LIB --> STO[MediaStorageUsage] LIB --> STORE[IMediaStore] USE --> PH[Hero IMediaUsageProvider] USE --> PG[Gallery IMediaUsageProvider, later] PH --> HERO[(HeroImages / HeroSlides)] HOST[Public /media endpoint] --> STORE classDef ui fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef core fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; classDef mod fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; classDef data fill:#fbb6ce,stroke:#b83280,stroke-width:1px,color:#000; class UI,SEL ui; class API,LIB,USE,STO,STORE,HOST core; class PH,PG mod; class HERO data; ``` Text alternative: the admin screen calls the library service in Core, which asks each module's usage provider where a photo is used and reads files and sizes through `IMediaStore`; the public media endpoint is unchanged. | Component | Where | Responsibility | |---|---|---| | `IMediaUsageProvider` | Core (contract), implemented per module | `ListUsesAsync(photoKey[])`, `DetachAsync(photoKey)`, `ListPhotosAsync(paging)` (phase A read-through) | | `MediaUsageService` | Core | Fans out to all providers, merges uses, knows which modules have no provider | | `MediaLibraryService` | Core | Listing (newest first), delete orchestration, clean-up preview | | `MediaStorageUsage` | Core | Bytes of originals plus variants, cached 60 s, warning level | | `CleanupSelection` | Core, pure | Given photos, uses, now, days and the unused flag: the preselected set | | `MediaLibraryController` | Core or new module (see 7) | `GET /api/v1/media`, `GET /api/v1/media/storage`, `POST /api/v1/media/cleanup/preview`, `POST /api/v1/media/delete` | | Frontend `features/media` | frontend | Screen, `PhotoSelectionList`, `BulkActionBar`, `CleanupDialog`, `StorageMeter`, React Query hooks | ## 2. Data (target, phase B and later; phase A uses Hero data read-only) ```mermaid erDiagram MediaAsset ||--o{ MediaUse : "is used by" MediaAsset { guid Id string OriginalSha256 string OriginalKey int Width int Height long Bytes double DefaultFocusX double DefaultFocusY double DefaultZoom datetime CreatedAt guid CreatedByUserId } MediaUse { guid Id guid AssetId string Module string Place string RatioSet double FocusX double FocusY double Zoom string SetHash } ``` Text alternative: one photo (`MediaAsset`) has many uses (`MediaUse`); each use has its module, place, ratio set, its own crop and the set hash derived from the photo hash plus that crop. - `SetHash` of a use is computed by the existing `MediaPaths.SetHash(OriginalSha256, crops)`; for a Hero slide this equals today's value (verified by a test in phase A against current golden data). - Variants stay files in the store (`/media/{area}/{setHash}/...`); no variants table is needed (the Hero `Variants` list is derived from the planner and the files). - A use is `Module` + `Place` (for Hero "slide 3", id of the slide), not a free text. ## 3. Usage contract ```csharp public interface IMediaUsageProvider { string Module { get; } // "hero" Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken ct); Task> ListPhotosAsync(MediaPaging paging, CancellationToken ct); // phase A read-through Task DetachAsync(Guid photoId, CancellationToken ct); // before the library deletes the photo Task DeleteAsync(Guid photoId, CancellationToken ct); // phase A: the module deletes its own photo } ``` A `MediaUse` carries `Module`, `PlaceLabel` (for display, translated by the module, for example "Hero, slide 3"), `PlaceId` and `Active`. In phase A the Hero provider implements all four members over `HeroImages` and `HeroSlides`; from phase B the library owns the photos and `ListPhotosAsync`/`DeleteAsync` fall away. ## 4. Uses and crops ```mermaid flowchart LR P[Photo + default focus] --> U1[Use: hero wide] P --> U2[Use: hero tall] P --> U3[Use: mosaic tile 4:5] P --> U4[Use: masonry natural] U1 --> S1[set hash A] U2 --> S1 U3 --> S2[set hash B] U4 --> S3[set hash C] classDef p fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; classDef u fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; classDef s fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; class P p; class U1,U2,U3,U4 u; class S1,S2,S3 s; ``` Text alternative: one photo has uses in Hero (wide and tall share one set), a mosaic tile and a masonry gallery; each set has its own hash and address. - `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 ```mermaid sequenceDiagram box rgba(246,224,94,0.4) Admin participant U as Person end box rgba(99,179,237,0.4) Core participant L as MediaLibraryService participant S as MediaUsageService end box rgba(154,230,180,0.4) Module participant P as Usage provider end U->>L: Clean-up preview (days, only unused) L->>S: Uses of all photos in the period S->>P: ListUsesAsync P-->>S: Uses L-->>U: Newest first, all selected, bytes to free U->>L: Confirm selected ids L->>S: Re-check uses L->>P: DetachAsync / DeleteAsync L->>L: Delete files in the store L-->>U: Result per photo ``` Text alternative: the person previews, the service re-checks usage at confirmation time (a photo used since the preview is skipped), the module detaches and deletes, the service removes files and reports per photo. - The re-check at confirmation protects against a photo that became used after the preview. - Bulk delete is limited (100 photos per request), idempotent and reports per photo. ## 6. Migration outline (phase C, designed only) 1. Back-up the database and the media directory. 2. Create `MediaAsset` and `MediaUse` (additive migration). No existing table changes. 3. Copy: one asset per `HeroImage` with the **same id, hash, key and set hash**; one use per slide that references it. A verification query compares counts, ids and set hashes and aborts on any difference. 4. Switch Hero reads to the library behind a setting; keep the old columns written for one release (expand), then drop them (contract). 5. Rollback until step 4: delete the new tables (no consumer changed). ## 7. Module placement (assumed) The model and services live in **Core** (`SlpModularCms.Core.Media`, next to the store) so Hero and the gallery module depend on Core only; the controller and the EF tables (phase B) go in a new module `SlpModularCms.Modules.Media` with its own `DbContext` and migrations, like the other modules, and a test project under `Tests/Modules`. Phase A needs no new tables, so the first controller can ship in the Hero-independent Core registration. ## 8. Frontend - `PhotoSelectionList`: virtualised or incremental list of cards (thumbnail, name, size, date, usage chips), with the shared `Checkbox`, shift-click range, select all and clear, `aria-live` count. - `BulkActionBar`: sticky, shows the count and the actions; actions are data (`{id, label, destructive, run}`) so tags or move can be added. - `CleanupDialog`: slider (days), `CheckboxField` "Only unused photos" (default on), the same `PhotoSelectionList` preselected, summary of count and bytes, confirm. - `StorageMeter`: used, limit, warning colour plus text. - Sidebar entry "Mediabibliotheek" for Owner and Administrator. ## 9. Test strategy - Pure: `CleanupSelection` (age, unused flag, ordering), range selection, set-hash per use equals the Hero value (property tests). - Service: delete re-check, partial failure, limit of 100, in-use rules, storage warning thresholds. - 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).