Mediabibliotheek: scherm, opruimvoorbeeld, gebruiksdefinities en ImagePicker #26
@@ -6,7 +6,7 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
|
||||
|---|---|---|---|---|
|
||||
| 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` |
|
||||
| 3 | The **7-day automatic clean-up** of unattached Hero images until the library is built. | **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? | One shared library for Owner and Administrator (like Hero and Offerings). No per-module visibility yet. | Per-module visibility needs an owner field on a photo and a filter; the contract has room for it (`ModuleKey` on a use). | `[Authorize(Policy = "AdminOnly")]`, `MediaUse.Module` |
|
||||
| 5 | **Public addresses**: per module (`/media/<module>/...`) or a shared path? | Keep `/media/{area}/{setHash}/{name}`; `area` stays the module (`hero`; a gallery would use `gallery`). The set hash still comes from the original's hash plus the crops of that **use**. A photo used in two modules is two sets (two addresses), cached separately. | A shared path would change addresses and golden files: not allowed without alignment. | `MediaPaths`, `MediaEndpoint` |
|
||||
| 6 | **Usage register**: do modules report, or does the library keep it centrally? | Modules report: `IMediaUsageProvider` per module answers "where is this photo used" and "detach this photo" from the module's own data. Computed, never copied, so it cannot go stale. The library warns when a module has no provider. | A central register table keeps the answer fast but must be kept in step on every module save (risk of drift); can be added later as a cache. | Application design section 3, `IMediaUsageProvider` |
|
||||
@@ -27,4 +27,8 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
|
||||
| 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 |
|
||||
| 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? | 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? | 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. | 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` |
|
||||
|
||||
@@ -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,34 @@ The model and services live in **Core** (`SlpModularCms.Core.Media`, next to the
|
||||
- Hero provider: uses per slide, detach.
|
||||
- Regression: golden files and the host-injection tests unchanged; a set made before the library is still served.
|
||||
- Frontend: selection by mouse and keyboard, announcements, dialog flow, i18n nl and en.
|
||||
|
||||
## 10. Choose or upload (ML-17)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M[Module screen, for example a hero slide] --> P[ImagePicker]
|
||||
P -->|choose| L[Library photos]
|
||||
P -->|upload on the spot| U[Module upload callback]
|
||||
U --> S[Upload service: guard, limits, store]
|
||||
S --> R[Background renderer]
|
||||
S --> L
|
||||
L --> P
|
||||
classDef m fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
|
||||
classDef c fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
|
||||
classDef s fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
|
||||
class M m;
|
||||
class P,L c;
|
||||
class U,S,R s;
|
||||
```
|
||||
|
||||
Text alternative: a module screen uses the picker, which either chooses a library photo or uploads through the module's upload callback; the upload service validates and stores, the renderer cuts variants in the background, and the new photo is in the library and is chosen at once.
|
||||
|
||||
- **Component**: `features/media/components/ImagePicker` (frontend, built as a pure component, not wired anywhere yet). Props: the library photos, the chosen id, `onChange`, an optional `onUpload(file) => Promise<photo>`, the upload limit and a short limits text. It is a radio group of thumbnails (arrow keys), plus an upload button; after a successful upload it chooses the new photo. It holds no data and calls nothing by itself, so each module decides what an upload does.
|
||||
- **Same checks as the Hero**: the quick client checks are one shared function (`validateUpload`: an image, not over the limit); the host repeats and extends them (signature, pixel limit, rate limit, total storage) through the one `IMediaUploadGuard`. A multi-file upload and drag and drop stay module screens' choice (Hero keeps its own).
|
||||
- **Background processing**: unchanged. An upload stores the original and returns at once; `HeroRenderService` (later a shared renderer) cuts variants. The picker shows a photo without a thumbnail ("no preview") until its set exists, and the library list refreshes while photos are processing.
|
||||
- **How the Hero upload relates to the library**:
|
||||
- Now (phase A): the Hero keeps its own upload (`POST /hero/images`) and its `HeroImages` table. Hero photos already appear in the library through the usage provider, so a photo uploaded in the Hero is visible and clean-up-able in the library. The Hero screen does not use the picker yet, and no behaviour changes.
|
||||
- Phase B: one upload service in Core; **every upload creates exactly one library record** (`MediaAsset`), whichever module's screen it came from; the same file is one record (hash). The Hero's slide then refers to the library photo instead of its own image row.
|
||||
- Phase C: the existing `HeroImages` are copied as library records with the same ids, hashes and set hashes (design section 6), after which the Hero screen switches to the picker.
|
||||
- **Other modules** (gallery, mosaic, masonry) use the picker from the start, with their own use definition (`GalleryUses`) deciding the ratios and crops of the chosen photo.
|
||||
- **Rights and limits**: the same Owner and Administrator rights as the library; the hero upload rate limit (100 per user per hour) applies to the shared upload service.
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
| ML-13 | **Usage register for modules.** A module reports where it uses photos and can be asked to detach a photo. | Contract in the design (section 3 of the application design); Hero is the first provider; a module without a provider counts as "uses nothing" and the library shows a warning that its uses are unknown (so a photo is not silently deleted). |
|
||||
| ML-14 | **Public addresses unchanged.** `/media/hero/<setHash>/<ratio>-<width>.<ext>` and every existing set hash stay valid. | Golden files and the host-injection tests stay green without edits; a regression test serves a set created before the library. |
|
||||
| ML-15 | **Permissions.** Owner and Administrator may use the library (like Hero and Offerings). | `[Authorize(Policy = "AdminOnly")]`; rate limits on upload and bulk delete. |
|
||||
| ML-17 | **Choose or upload, in every part that needs an image** (new requirement of Bryan, 2026-11-17). In every module that needs an image (Hero, later gallery, mosaic, masonry) the person can upload on the spot, also when the library holds no suitable image yet, and can choose from the existing library photos. An image uploaded on the spot is added to the library automatically and can be chosen everywhere afterwards. | One shared component "choose or upload" (a picker of the library photos plus an upload button) is reused by every module; it applies the same validation, limits and background processing as the Hero upload today; after an upload the new photo is chosen at once; the module keeps its own use (place, crop) of the chosen photo; a photo uploaded in one module is listed and choosable in the others. Until the library owns uploads (phase B) the Hero upload flow stays as it is. |
|
||||
| ML-16 | **Audit.** Each deletion (single, bulk, clean-up) is logged with user, photo ids and count. | Structured log entry per action; no photo content in the log. |
|
||||
|
||||
## 5. Non-functional requirements
|
||||
@@ -87,8 +88,8 @@
|
||||
|
||||
| Phase | Content | Moves data? | Build now? |
|
||||
|---|---|---|---|
|
||||
| A. Foundations (safe, reversible) | Usage contract in Core (`IMediaUsageProvider`), Hero provider (read only), library read model over `HeroImages`, storage usage service, selection and bulk-action components (frontend), clean-up selection logic, library screen (list, usage, selection, bulk delete through the Hero service), Hero retention setting | No (delete uses existing Hero delete path) | After Bryan acknowledges the assumptions; pure and read-only parts can start earlier |
|
||||
| B. Own tables | `MediaAsset` and `MediaUse` tables, upload into the library, default focus | New tables only | Needs alignment |
|
||||
| A. Foundations (safe, reversible) | The shared `ImagePicker` component (pure, not wired), usage contract in Core (`IMediaUsageProvider`), Hero provider (read only), library read model over `HeroImages`, storage usage service, selection and bulk-action components (frontend), clean-up selection logic, library screen (list, usage, selection, bulk delete through the Hero service), Hero retention setting | No (delete uses existing Hero delete path) | After Bryan acknowledges the assumptions; pure and read-only parts can start earlier |
|
||||
| B. Own tables | `MediaAsset` and `MediaUse` tables, upload into the library (one library record per upload, ML-17), default focus | New tables only | Needs alignment |
|
||||
| C. Migration of Hero | Copy `HeroImages` into `MediaAsset` plus `MediaUse` (one use per slide), keep set hashes and addresses, switch Hero to the library, drop old columns later (expand then contract) | Yes | Needs alignment and a back-up |
|
||||
| D. Gallery module | First other consumer (mosaic, masonry) | Own data | Separate feature |
|
||||
|
||||
@@ -101,5 +102,6 @@
|
||||
| 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 |
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ De admin toont alleen een badge Live of Niet live.
|
||||
| Instelling | Betekenis |
|
||||
|---|---|
|
||||
| `Media__Directory` | De map voor de afbeeldingen, **buiten de release** en buiten de webroot. Zonder deze instelling (of als de map niet beschrijfbaar is) staan uploads uit; bestaande bestanden en de publieke hero blijven werken. Niet in een committed appsettings-bestand. |
|
||||
| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. |
|
||||
| `Media__MaxUploadBytes` (10 MB), `Media__MaxPixels` (64 miljoen), `Media__MaxParallelJobs` (2), `Media__DecodeTimeoutSeconds` (20), `Media__MaxTotalBytes` (2 GB), `Media__RetentionDays` (7), `Media__AutoCleanupUnattached` (standaard `true`; `false` bewaart ongebruikte uploads tot iemand ze verwijdert, voor de mediabibliotheek) | Grenzen en bewaartijd; standaardwaarden zijn bedoeld om te blijven. |
|
||||
| `Hero__TextOnlyRegion` | `true` voor een site waarvan de hero geen afbeeldingen heeft (SLP Software; staat in de committed instellingen van die site): een hero zonder slides wordt dan als tekst (titelregels, lead, knoppen) in de eerste HTML geschreven. Uit (standaard, ook voor ASF): een hero zonder slides laat de pagina ongemoeid. |
|
||||
| `Hero__TitlePrefix` | Merktekst die in de tekst-only-regio als eerste, visueel te verbergen deel van de h1 wordt geschreven (`<span class="cms-hero-title-prefix">`), zodat crawlers en schermlezers de volledige titel lezen. SLP Software: `"SLP Software: "` (committed instelling); leeg (standaard, ook ASF) schrijft niets. De site verbergt de klasse zelf visueel. |
|
||||
| `Media__RenderSetTimeoutSeconds` (600), `Media__StripTimeoutSeconds` (60) | De tijd die het knippen van alle varianten van één foto in de achtergrond mag duren, en het verwijderen van metadata bij een upload. Ruim gekozen: een grote foto op een Raspberry Pi kost minuten. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react';
|
||||
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon, Images } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
@@ -38,6 +38,14 @@ const NAV_ITEMS: NavItem[] = [
|
||||
roles: ['Owner', 'Administrator'],
|
||||
requiredModule: 'Hero',
|
||||
},
|
||||
{
|
||||
to: '/media',
|
||||
labelKey: 'nav.media',
|
||||
icon: Images,
|
||||
testId: 'nav-media',
|
||||
roles: ['Owner', 'Administrator'],
|
||||
requiredModule: 'Hero',
|
||||
},
|
||||
{
|
||||
to: '/offerings',
|
||||
labelKey: 'nav.offerings',
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CheckboxField } from '@/components/ui/checkbox';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import { selectAll, type Selection } from '../lib/selection';
|
||||
import { toPhotoItem } from '../lib/toPhotoItem';
|
||||
import { useCleanupPreview } from '../services/hooks';
|
||||
import { BulkActionBar } from './BulkActionBar';
|
||||
import { PhotoSelectionList } from './PhotoSelectionList';
|
||||
|
||||
const DEFAULT_DAYS = 7;
|
||||
const MIN_DAYS = 1;
|
||||
const MAX_DAYS = 365;
|
||||
|
||||
/**
|
||||
* "Clean up": the photos older than the chosen number of days (by default 7), by default only the unused ones, newest
|
||||
* first and all selected so single photos can be taken out. This step is a PREVIEW: nothing is deleted yet (deleting
|
||||
* comes after the assumptions have been checked).
|
||||
*/
|
||||
export function CleanupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [days, setDays] = useState(DEFAULT_DAYS);
|
||||
const [debouncedDays, setDebouncedDays] = useState(DEFAULT_DAYS);
|
||||
const [onlyUnused, setOnlyUnused] = useState(true);
|
||||
// Everything starts selected: the person only takes photos OUT. A new period or filter starts again with all in.
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(new Set());
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const preview = useCleanupPreview(debouncedDays, onlyUnused, open);
|
||||
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
|
||||
const changeDays = (value: number) => {
|
||||
setDays(value);
|
||||
clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => {
|
||||
setDebouncedDays(value);
|
||||
setExcluded(new Set());
|
||||
}, 300);
|
||||
};
|
||||
|
||||
const photos = preview.data?.photos;
|
||||
const ids = useMemo(() => (photos ?? []).map((p) => p.id), [photos]);
|
||||
const selection = useMemo<Selection>(() => selectAll(ids.filter((id) => !excluded.has(id))), [ids, excluded]);
|
||||
const setSelection = (next: Selection) => setExcluded(new Set(ids.filter((id) => !next.has(id))));
|
||||
|
||||
const items = useMemo(() => (photos ?? []).map((p) => toPhotoItem(p, t)), [photos, t]);
|
||||
const selectedBytes = (photos ?? []).filter((p) => selection.has(p.id)).reduce((sum, p) => sum + p.bytes, 0);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto" data-testid="cleanup-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('media.cleanup.title')}</DialogTitle>
|
||||
<DialogDescription>{t('media.cleanup.description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cleanup-days">{t('media.cleanup.days', { count: days })}</Label>
|
||||
<input
|
||||
id="cleanup-days"
|
||||
type="range"
|
||||
min={MIN_DAYS}
|
||||
max={MAX_DAYS}
|
||||
step={1}
|
||||
value={days}
|
||||
onChange={(event) => changeDays(Number(event.target.value))}
|
||||
className="w-full accent-primary"
|
||||
data-testid="cleanup-days"
|
||||
/>
|
||||
</div>
|
||||
<CheckboxField
|
||||
checked={onlyUnused}
|
||||
onChange={(event) => {
|
||||
setOnlyUnused(event.target.checked);
|
||||
setExcluded(new Set());
|
||||
}}
|
||||
label={t('media.cleanup.onlyUnused')}
|
||||
data-testid="cleanup-only-unused"
|
||||
/>
|
||||
|
||||
<p className="rounded-md border border-dashed p-3 text-sm text-muted-foreground" data-testid="cleanup-preview-note">
|
||||
{t('media.cleanup.previewNote')}
|
||||
</p>
|
||||
|
||||
{preview.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
{preview.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
|
||||
{preview.data && (
|
||||
<>
|
||||
<p className="text-sm" data-testid="cleanup-summary">
|
||||
{t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })}
|
||||
</p>
|
||||
<PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} />
|
||||
<BulkActionBar
|
||||
count={selection.size}
|
||||
actions={[]}
|
||||
onClear={() => setSelection(new Set())}
|
||||
summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useState } from 'react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import i18n from '@/i18n/config';
|
||||
import { validateUpload } from '../lib/validateUpload';
|
||||
import { ImagePicker } from './ImagePicker';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
const photo = (id: string, name: string): PhotoItem => ({ id, name, bytes: 1, createdAt: '2026-11-17T10:00:00Z', uses: [], thumbnailUrl: null });
|
||||
const items = [photo('a', 'Foto A'), photo('b', 'Foto B')];
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
function Harness({ onUpload, initial = null }: { onUpload?: (file: File) => Promise<PhotoItem>; initial?: string | null }) {
|
||||
const [value, setValue] = useState<string | null>(initial);
|
||||
return <ImagePicker items={items} value={value} onChange={setValue} onUpload={onUpload} maxUploadBytes={10 * MB} label="Afbeelding van slide 1" limitsText="JPEG, PNG, WebP, AVIF" />;
|
||||
}
|
||||
|
||||
const file = (name = 'x.jpg', type = 'image/jpeg', size = 1000) => new File([new Uint8Array(size)], name, { type });
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('nl');
|
||||
});
|
||||
|
||||
describe('validateUpload', () => {
|
||||
it.each([
|
||||
[{ type: 'image/jpeg', size: 100 }, null],
|
||||
[{ type: '', size: 100 }, null],
|
||||
[{ type: 'application/pdf', size: 100 }, 'notAnImage'],
|
||||
[{ type: 'image/png', size: 10 * MB + 1 }, 'tooLarge'],
|
||||
[{ type: 'image/png', size: 10 * MB }, null],
|
||||
])('%j gives %s', (f, expected) => expect(validateUpload(f, 10 * MB)).toBe(expected));
|
||||
});
|
||||
|
||||
describe('ImagePicker', () => {
|
||||
it('chooses a library photo as a radio group, with the arrow keys', async () => {
|
||||
render(<Harness initial="a" />);
|
||||
|
||||
expect(screen.getByRole('radiogroup', { name: 'Afbeelding van slide 1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('radio', { name: 'Foto A' })).toBeChecked();
|
||||
screen.getByRole('radio', { name: 'Foto A' }).focus();
|
||||
await userEvent.keyboard('{ArrowRight}');
|
||||
|
||||
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('has no upload button when the module gives no upload', () => {
|
||||
render(<Harness />);
|
||||
|
||||
expect(screen.queryByTestId('picker-upload-button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uploads on the spot, then chooses the new photo', async () => {
|
||||
const upload = vi.fn().mockResolvedValue(photo('c', 'Nieuwe foto'));
|
||||
render(<Harness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file());
|
||||
|
||||
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
|
||||
await waitFor(() => expect(screen.getByTestId('picker-upload-button')).toHaveTextContent('Afbeelding uploaden'));
|
||||
expect(screen.queryByTestId('picker-problem')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('refuses what the host would refuse, without calling the upload', async () => {
|
||||
const upload = vi.fn();
|
||||
render(<Harness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file('x.pdf', 'application/pdf'), { applyAccept: false });
|
||||
expect(screen.getByTestId('picker-problem')).toHaveTextContent('geen afbeelding');
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file('big.jpg', 'image/jpeg', 10 * MB + 1));
|
||||
expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB');
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a message when the upload fails and keeps the current choice', async () => {
|
||||
render(<Harness onUpload={() => Promise.reject(new Error('nope'))} initial="b" />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), file());
|
||||
|
||||
expect(await screen.findByTestId('picker-problem')).toHaveTextContent('niet gelukt');
|
||||
expect(screen.getByRole('radio', { name: 'Foto B' })).toBeChecked();
|
||||
});
|
||||
|
||||
it('says so when the library is empty', () => {
|
||||
render(<ImagePicker items={[]} value={null} onChange={vi.fn()} maxUploadBytes={MB} label="x" />);
|
||||
|
||||
expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useId, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ImagePlus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { validateUpload } from '../lib/validateUpload';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
interface ImagePickerProps {
|
||||
/** The photos of the library to choose from, newest first. */
|
||||
items: readonly PhotoItem[];
|
||||
/** The id of the chosen photo, or null. */
|
||||
value: string | null;
|
||||
onChange: (id: string) => void;
|
||||
/**
|
||||
* Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own
|
||||
* upload and background processing); the picker only shows the state and chooses the result. Without it there is no
|
||||
* upload button.
|
||||
*/
|
||||
onUpload?: (file: File) => Promise<PhotoItem>;
|
||||
/** The largest file the host accepts, in bytes. */
|
||||
maxUploadBytes: number;
|
||||
/** A short line about formats and limits, shown under the buttons. */
|
||||
limitsText?: string;
|
||||
/** Accessible name of the group (what the image is for, for example "Image of slide 2"). */
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Choose an image or upload one": the photos of the library as a group of radio buttons (arrow keys move and choose)
|
||||
* and an upload button that adds the new photo to the library and chooses it at once. One component for every module that
|
||||
* needs an image. It holds no data of its own and calls nothing by itself: the module passes the list and the upload.
|
||||
*/
|
||||
export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, limitsText, label }: ImagePickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const groupName = useId();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
|
||||
const upload = async (file: File | undefined) => {
|
||||
if (!file || !onUpload || uploading) return;
|
||||
const refused = validateUpload(file, maxUploadBytes);
|
||||
if (refused) {
|
||||
setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage'));
|
||||
return;
|
||||
}
|
||||
setProblem(null);
|
||||
setUploading(true);
|
||||
try {
|
||||
const photo = await onUpload(file);
|
||||
onChange(photo.id);
|
||||
} catch {
|
||||
setProblem(t('media.picker.failed'));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (fileInput.current) fileInput.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-testid="image-picker">
|
||||
{onUpload && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="sr-only"
|
||||
aria-label={t('media.picker.upload')}
|
||||
data-testid="picker-file"
|
||||
onChange={(event) => void upload(event.target.files?.[0])}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="picker-upload-button">
|
||||
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
|
||||
{uploading ? t('media.picker.uploading') : t('media.picker.upload')}
|
||||
</Button>
|
||||
{limitsText && <p className="text-xs text-muted-foreground">{limitsText}</p>}
|
||||
</div>
|
||||
)}
|
||||
{problem && (
|
||||
<p role="alert" className="text-sm text-destructive" data-testid="picker-problem">
|
||||
{problem}
|
||||
</p>
|
||||
)}
|
||||
{items.length === 0 ? (
|
||||
<p className="rounded-md border border-dashed p-4 text-sm text-muted-foreground" data-testid="picker-empty">
|
||||
{t('media.picker.empty')}
|
||||
</p>
|
||||
) : (
|
||||
<div role="radiogroup" aria-label={label} className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="picker-grid">
|
||||
{items.map((item) => (
|
||||
<label key={item.id} className="relative block cursor-pointer" data-testid={`picker-item-${item.id}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name={groupName}
|
||||
value={item.id}
|
||||
checked={value === item.id}
|
||||
onChange={() => onChange(item.id)}
|
||||
aria-label={item.name}
|
||||
className="peer sr-only"
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'block overflow-hidden rounded-md border-2 border-transparent bg-muted transition-colors',
|
||||
'peer-checked:border-primary peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-focus-visible:ring-offset-2 ring-offset-background',
|
||||
'hover:border-muted-foreground forced-colors:peer-checked:border-[Highlight]',
|
||||
)}
|
||||
>
|
||||
{item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className="aspect-[3/2] w-full object-cover" />
|
||||
) : (
|
||||
<span className="flex aspect-[3/2] items-center justify-center text-xs text-muted-foreground">{t('media.list.noThumbnail')}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="mt-1 block truncate text-xs">{item.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection';
|
||||
|
||||
export interface PhotoUse {
|
||||
@@ -29,17 +30,6 @@ interface PhotoSelectionListProps {
|
||||
isDisabled?: (item: PhotoItem) => boolean;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number, language: string) {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let value = bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos with a checkbox each: click or Space to toggle, shift-click for a range, a "select all" box in the header
|
||||
* (with the in-between state), and a live announcement of the count. One component for the library and the clean-up.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatBytes } from '../lib/format';
|
||||
import type { MediaStorageDto } from '../services/types';
|
||||
|
||||
/** Used space against the limit, with a warning at 80 percent and a clear message at the limit (colour plus text). */
|
||||
export function StorageMeter({ storage }: { storage: MediaStorageDto }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const hasLimit = storage.limitBytes > 0;
|
||||
const percent = hasLimit ? Math.min(100, Math.round((storage.usedBytes / storage.limitBytes) * 100)) : 0;
|
||||
const used = formatBytes(storage.usedBytes, i18n.language);
|
||||
|
||||
return (
|
||||
<section aria-labelledby="storage-title" className="space-y-2 rounded-md border p-4" data-testid="storage-meter" data-level={storage.level}>
|
||||
<h2 id="storage-title" className="text-sm font-medium">
|
||||
{t('media.storage.title')}
|
||||
</h2>
|
||||
<p className="text-sm" data-testid="storage-text">
|
||||
{hasLimit ? t('media.storage.usedOf', { used, limit: formatBytes(storage.limitBytes, i18n.language), percent }) : t('media.storage.used', { used })}
|
||||
</p>
|
||||
{hasLimit && (
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={percent}
|
||||
aria-labelledby="storage-title"
|
||||
className="h-2 w-full overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
<div
|
||||
className={cn('h-full', storage.level === 'full' ? 'bg-destructive' : storage.level === 'warning' ? 'bg-amber-500' : 'bg-primary')}
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{storage.level !== 'ok' && (
|
||||
<p role="alert" className={cn('text-sm font-medium', storage.level === 'full' ? 'text-destructive' : 'text-amber-700 dark:text-amber-400')} data-testid="storage-warning">
|
||||
{storage.level === 'full' ? t('media.storage.full') : t('media.storage.warning', { percent: storage.warningPercent })}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
|
||||
/** A size in bytes as a short, localised text (1,5 MB). */
|
||||
export function formatBytes(bytes: number, language: string): string {
|
||||
let value = Math.max(0, bytes);
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < UNITS.length - 1) {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
}
|
||||
return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${UNITS[unit]}`;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { PhotoItem } from '../components/PhotoSelectionList';
|
||||
import type { MediaPhotoDto } from '../services/types';
|
||||
|
||||
/** The list shows a neutral name (the size of the photo): photos do not store a file name yet (assumption 21). */
|
||||
export function toPhotoItem(photo: MediaPhotoDto, t: TFunction): PhotoItem {
|
||||
return {
|
||||
id: photo.id,
|
||||
thumbnailUrl: photo.thumbnailUrl,
|
||||
name: t('media.list.photoName', { width: photo.width, height: photo.height }),
|
||||
bytes: photo.bytes,
|
||||
createdAt: photo.createdAt,
|
||||
uses: photo.uses,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export type UploadProblem = 'notAnImage' | 'tooLarge';
|
||||
|
||||
/**
|
||||
* The quick checks before a file is sent (the same two the hero upload makes): it must be an image and not over the
|
||||
* limit. The host checks everything again (signature, pixels, rate); this only spares sending a file it will refuse.
|
||||
*/
|
||||
export function validateUpload(file: { type: string; size: number }, maxBytes: number): UploadProblem | null {
|
||||
if (file.type !== '' && !file.type.startsWith('image/')) return 'notAnImage';
|
||||
if (file.size > maxBytes) return 'tooLarge';
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaPhotoDto, MediaStorageDto } from '@/features/media/services/types';
|
||||
|
||||
const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000).toISOString();
|
||||
|
||||
export const seedPhotos = (): MediaPhotoDto[] => [
|
||||
{
|
||||
id: 'hero:11111111-1111-1111-1111-111111111111',
|
||||
module: 'hero',
|
||||
bytes: 2_400_000,
|
||||
width: 3000,
|
||||
height: 2000,
|
||||
createdAt: daysAgo(1),
|
||||
thumbnailUrl: '/media/hero/0123456789abcdef/wide-480.webp',
|
||||
uses: [{ module: 'hero', kind: 'slide', position: 1, active: true }],
|
||||
},
|
||||
{
|
||||
id: 'hero:22222222-2222-2222-2222-222222222222',
|
||||
module: 'hero',
|
||||
bytes: 1_800_000,
|
||||
width: 2400,
|
||||
height: 1600,
|
||||
createdAt: daysAgo(12),
|
||||
thumbnailUrl: null,
|
||||
uses: [],
|
||||
},
|
||||
{
|
||||
id: 'hero:33333333-3333-3333-3333-333333333333',
|
||||
module: 'hero',
|
||||
bytes: 900_000,
|
||||
width: 1600,
|
||||
height: 1067,
|
||||
createdAt: daysAgo(30),
|
||||
thumbnailUrl: null,
|
||||
uses: [{ module: 'hero', kind: 'slide', position: 2, active: false }],
|
||||
},
|
||||
];
|
||||
|
||||
export const seedStorage = (): MediaStorageDto => ({ usedBytes: 100_000_000, limitBytes: 2_147_483_648, level: 'ok', warningPercent: 80 });
|
||||
|
||||
export const mediaHandlers = [
|
||||
http.get('*/media-library/photos', () => HttpResponse.json({ photos: seedPhotos(), modules: ['hero'] } satisfies MediaLibraryDto)),
|
||||
http.get('*/media-library/storage', () => HttpResponse.json(seedStorage())),
|
||||
http.get('*/media-library/cleanup-preview', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const days = Number(url.searchParams.get('days') ?? 7);
|
||||
const onlyUnused = url.searchParams.get('onlyUnused') !== 'false';
|
||||
const cutoff = Date.now() - days * 86_400_000;
|
||||
const photos = seedPhotos().filter((p) => new Date(p.createdAt).getTime() < cutoff && (!onlyUnused || p.uses.length === 0));
|
||||
return HttpResponse.json({
|
||||
days,
|
||||
onlyUnused,
|
||||
count: photos.length,
|
||||
bytes: photos.reduce((sum, p) => sum + p.bytes, 0),
|
||||
photos,
|
||||
} satisfies MediaCleanupPreviewDto);
|
||||
}),
|
||||
];
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import i18n from '@/i18n/config';
|
||||
import { server } from '@/mocks/server';
|
||||
import { renderWithProviders } from '@/test/utils';
|
||||
import { seedStorage } from '../mocks/handlers';
|
||||
import { MediaLibraryPage } from './MediaLibraryPage';
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('nl');
|
||||
});
|
||||
|
||||
describe('MediaLibraryPage', () => {
|
||||
it('lists the photos newest first with where each is used, and the storage', async () => {
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
|
||||
const list = await screen.findByTestId('photo-selection-list');
|
||||
const rows = within(list).getAllByRole('listitem');
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(within(rows[0]!).getByText('Hero, slide 1')).toBeInTheDocument();
|
||||
expect(within(rows[1]!).getByText('Niet gebruikt')).toBeInTheDocument();
|
||||
expect(within(rows[2]!).getByText('Hero, slide 2 (uit)')).toBeInTheDocument();
|
||||
expect(await screen.findByTestId('storage-text')).toHaveTextContent('van');
|
||||
expect(screen.queryByTestId('storage-warning')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('warns when the storage is nearly full and says so when it is full', async () => {
|
||||
server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 1_800_000_000, level: 'warning' })));
|
||||
const { unmount } = renderWithProviders(<MediaLibraryPage />);
|
||||
expect(await screen.findByTestId('storage-warning')).toHaveTextContent('80%');
|
||||
unmount();
|
||||
|
||||
server.use(http.get('*/media-library/storage', () => HttpResponse.json({ ...seedStorage(), usedBytes: 2_147_483_648, level: 'full' })));
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol');
|
||||
});
|
||||
|
||||
it('selects photos and shows the bulk bar without any delete action yet', async () => {
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getAllByRole('checkbox', { name: /Foto 3000/ })[0]!);
|
||||
|
||||
expect(await screen.findByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd');
|
||||
expect(screen.queryByTestId('bulk-action-delete')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the clean-up: older than 7 days, only unused, all selected, newest first, and nothing is deleted', async () => {
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
expect(within(dialog).getByTestId('cleanup-only-unused')).toBeChecked();
|
||||
expect(await within(dialog).findByTestId('cleanup-summary')).toHaveTextContent('1 foto');
|
||||
expect(within(dialog).getByTestId('cleanup-preview-note')).toHaveTextContent('nog niets verwijderd');
|
||||
const boxes = within(dialog).getAllByRole('checkbox', { name: /Foto/ });
|
||||
expect(boxes).toHaveLength(1);
|
||||
await waitFor(() => expect(boxes[0]).toBeChecked());
|
||||
});
|
||||
|
||||
it('includes photos in use when "only unused" is switched off', async () => {
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
await screen.findByTestId('photo-selection-list');
|
||||
await userEvent.click(screen.getByTestId('cleanup-open'));
|
||||
const dialog = await screen.findByTestId('cleanup-dialog');
|
||||
await within(dialog).findByTestId('cleanup-summary');
|
||||
|
||||
await userEvent.click(within(dialog).getByTestId('cleanup-only-unused'));
|
||||
|
||||
await waitFor(() => expect(within(dialog).getByTestId('cleanup-summary')).toHaveTextContent('2 foto'));
|
||||
expect(within(dialog).getAllByRole('checkbox', { name: /Foto/ })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('shows an error when the library cannot be loaded', async () => {
|
||||
server.use(http.get('*/media-library/photos', () => new HttpResponse(null, { status: 500 })));
|
||||
renderWithProviders(<MediaLibraryPage />);
|
||||
|
||||
expect(await screen.findByTestId('media-error')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Eraser } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { BulkActionBar } from '../components/BulkActionBar';
|
||||
import { CleanupDialog } from '../components/CleanupDialog';
|
||||
import { PhotoSelectionList } from '../components/PhotoSelectionList';
|
||||
import { StorageMeter } from '../components/StorageMeter';
|
||||
import { emptySelection, prune, type Selection } from '../lib/selection';
|
||||
import { toPhotoItem } from '../lib/toPhotoItem';
|
||||
import { useMediaPhotos, useMediaStorage } from '../services/hooks';
|
||||
|
||||
/**
|
||||
* The media library: every photo of every module, newest first, with where it is used; the storage against its limit;
|
||||
* the "Clean up" preview. Selecting works already (bulk actions come with deleting, after the assumptions are checked).
|
||||
*/
|
||||
export function MediaLibraryPage() {
|
||||
const { t } = useTranslation();
|
||||
const photos = useMediaPhotos();
|
||||
const storage = useMediaStorage();
|
||||
const [chosen, setSelection] = useState<Selection>(emptySelection);
|
||||
const [cleanupOpen, setCleanupOpen] = useState(false);
|
||||
|
||||
const items = useMemo(() => (photos.data?.photos ?? []).map((p) => toPhotoItem(p, t)), [photos.data, t]);
|
||||
// Photos that left the list (after a reload) drop out of the selection.
|
||||
const selection = useMemo(() => prune(chosen, items.map((i) => i.id)), [chosen, items]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6" data-testid="media-library-page">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-2xl font-semibold">{t('media.page.title')}</h1>
|
||||
<Button type="button" variant="outline" onClick={() => setCleanupOpen(true)} data-testid="cleanup-open">
|
||||
<Eraser className="mr-2 size-4" aria-hidden="true" />
|
||||
{t('media.cleanup.open')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{storage.data && <StorageMeter storage={storage.data} />}
|
||||
|
||||
{photos.isError && (
|
||||
<p role="alert" className="text-sm text-destructive" data-testid="media-error">
|
||||
{t('media.error')}
|
||||
</p>
|
||||
)}
|
||||
{photos.isPending && <p className="text-sm text-muted-foreground">{t('media.loading')}</p>}
|
||||
{photos.data && photos.data.modules.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground" data-testid="media-no-modules">
|
||||
{t('media.page.noModules')}
|
||||
</p>
|
||||
)}
|
||||
{photos.data && <PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} />}
|
||||
<BulkActionBar count={selection.size} actions={[]} onClear={() => setSelection(emptySelection)} />
|
||||
|
||||
<CleanupDialog open={cleanupOpen} onOpenChange={setCleanupOpen} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { api } from '@/lib/api-client';
|
||||
import type { MediaCleanupPreviewDto, MediaLibraryDto, MediaStorageDto } from './types';
|
||||
|
||||
export const MEDIA_KEY = ['media-library'];
|
||||
|
||||
/** All photos of all modules, newest first, with where each is used. */
|
||||
export function useMediaPhotos() {
|
||||
return useQuery<MediaLibraryDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'photos'],
|
||||
queryFn: () => api.get<MediaLibraryDto>('/api/v1/media-library/photos'),
|
||||
});
|
||||
}
|
||||
|
||||
/** The space the media directory takes against its limit. */
|
||||
export function useMediaStorage() {
|
||||
return useQuery<MediaStorageDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'storage'],
|
||||
queryFn: () => api.get<MediaStorageDto>('/api/v1/media-library/storage'),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** What a clean-up with these settings would select. A preview: nothing is deleted. */
|
||||
export function useCleanupPreview(days: number, onlyUnused: boolean, enabled: boolean) {
|
||||
return useQuery<MediaCleanupPreviewDto, Error>({
|
||||
queryKey: [...MEDIA_KEY, 'cleanup-preview', days, onlyUnused],
|
||||
queryFn: () => api.get<MediaCleanupPreviewDto>(`/api/v1/media-library/cleanup-preview?days=${days}&onlyUnused=${onlyUnused}`),
|
||||
enabled,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
export interface MediaUseDto {
|
||||
module: string;
|
||||
kind: string;
|
||||
position: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface MediaPhotoDto {
|
||||
/** `module:guid`, unique over all modules. */
|
||||
id: string;
|
||||
module: string;
|
||||
bytes: number;
|
||||
width: number;
|
||||
height: number;
|
||||
createdAt: string;
|
||||
thumbnailUrl: string | null;
|
||||
uses: MediaUseDto[];
|
||||
}
|
||||
|
||||
export interface MediaLibraryDto {
|
||||
photos: MediaPhotoDto[];
|
||||
modules: string[];
|
||||
}
|
||||
|
||||
export type MediaStorageLevel = 'ok' | 'warning' | 'full';
|
||||
|
||||
export interface MediaStorageDto {
|
||||
usedBytes: number;
|
||||
/** 0 means no limit. */
|
||||
limitBytes: number;
|
||||
level: MediaStorageLevel;
|
||||
warningPercent: number;
|
||||
}
|
||||
|
||||
export interface MediaCleanupPreviewDto {
|
||||
days: number;
|
||||
onlyUnused: boolean;
|
||||
count: number;
|
||||
bytes: number;
|
||||
photos: MediaPhotoDto[];
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
"openMenu": "Open navigation",
|
||||
"closeMenu": "Close navigation",
|
||||
"hero": "Hero",
|
||||
"media": "Media library",
|
||||
"unreadMessages_one": "{{count}} new message",
|
||||
"unreadMessages_other": "{{count}} new messages"
|
||||
},
|
||||
@@ -783,19 +784,59 @@
|
||||
}
|
||||
},
|
||||
"media": {
|
||||
"module": { "hero": "Hero" },
|
||||
"use": { "slide": "slide", "none": "Not used", "off": "off" },
|
||||
"module": {
|
||||
"hero": "Hero"
|
||||
},
|
||||
"use": {
|
||||
"slide": "slide",
|
||||
"none": "Not used",
|
||||
"off": "off"
|
||||
},
|
||||
"list": {
|
||||
"label": "Photos",
|
||||
"empty": "There are no photos.",
|
||||
"selectAll": "Select all",
|
||||
"noThumbnail": "No preview"
|
||||
"noThumbnail": "No preview",
|
||||
"photoName": "Photo {{width}} × {{height}}"
|
||||
},
|
||||
"bulk": {
|
||||
"label": "Actions on the selection",
|
||||
"selected_one": "{{count}} photo selected",
|
||||
"selected_other": "{{count}} photos selected",
|
||||
"clear": "Clear selection"
|
||||
},
|
||||
"loading": "Loading...",
|
||||
"error": "The media library could not be loaded.",
|
||||
"page": {
|
||||
"title": "Media library",
|
||||
"noModules": "No module reports photos yet."
|
||||
},
|
||||
"storage": {
|
||||
"title": "Storage",
|
||||
"used": "{{used}} used",
|
||||
"usedOf": "{{used}} of {{limit}} used ({{percent}}%)",
|
||||
"warning": "Storage is more than {{percent}}% full. Clean up photos before the limit is reached.",
|
||||
"full": "Storage is full. No more photos can be uploaded until there is room."
|
||||
},
|
||||
"cleanup": {
|
||||
"open": "Clean up",
|
||||
"title": "Clean up",
|
||||
"description": "Photos older than the number of days below, newest first. Take out the photos you want to keep.",
|
||||
"days_one": "Older than {{count}} day",
|
||||
"days_other": "Older than {{count}} days",
|
||||
"onlyUnused": "Only unused photos",
|
||||
"previewNote": "This is a preview: nothing is deleted yet.",
|
||||
"summary_one": "{{count}} photo ({{size}}) qualifies.",
|
||||
"summary_other": "{{count}} photos ({{size}}) qualify.",
|
||||
"selectedSize": "Selected: {{size}}"
|
||||
},
|
||||
"picker": {
|
||||
"upload": "Upload an image",
|
||||
"uploading": "Uploading...",
|
||||
"empty": "There are no photos in the library yet. Upload one.",
|
||||
"notAnImage": "This file is not an image.",
|
||||
"tooLarge": "This file is too large (at most {{max}} MB).",
|
||||
"failed": "Uploading failed. Try again."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"openMenu": "Navigatie openen",
|
||||
"closeMenu": "Navigatie sluiten",
|
||||
"hero": "Hero",
|
||||
"media": "Mediabibliotheek",
|
||||
"unreadMessages_one": "{{count}} nieuw bericht",
|
||||
"unreadMessages_other": "{{count}} nieuwe berichten"
|
||||
},
|
||||
@@ -783,19 +784,59 @@
|
||||
}
|
||||
},
|
||||
"media": {
|
||||
"module": { "hero": "Hero" },
|
||||
"use": { "slide": "slide", "none": "Niet gebruikt", "off": "uit" },
|
||||
"module": {
|
||||
"hero": "Hero"
|
||||
},
|
||||
"use": {
|
||||
"slide": "slide",
|
||||
"none": "Niet gebruikt",
|
||||
"off": "uit"
|
||||
},
|
||||
"list": {
|
||||
"label": "Foto's",
|
||||
"empty": "Er zijn geen foto's.",
|
||||
"selectAll": "Alles selecteren",
|
||||
"noThumbnail": "Geen voorbeeld"
|
||||
"noThumbnail": "Geen voorbeeld",
|
||||
"photoName": "Foto {{width}} × {{height}}"
|
||||
},
|
||||
"bulk": {
|
||||
"label": "Acties op de selectie",
|
||||
"selected_one": "{{count}} foto geselecteerd",
|
||||
"selected_other": "{{count}} foto's geselecteerd",
|
||||
"clear": "Selectie wissen"
|
||||
},
|
||||
"loading": "Laden...",
|
||||
"error": "De mediabibliotheek kon niet worden geladen.",
|
||||
"page": {
|
||||
"title": "Mediabibliotheek",
|
||||
"noModules": "Er is nog geen module die foto's meldt."
|
||||
},
|
||||
"storage": {
|
||||
"title": "Opslag",
|
||||
"used": "{{used}} in gebruik",
|
||||
"usedOf": "{{used}} van {{limit}} in gebruik ({{percent}}%)",
|
||||
"warning": "De opslag is voor meer dan {{percent}}% vol. Ruim foto's op voordat de limiet bereikt is.",
|
||||
"full": "De opslag is vol. Er kunnen geen foto's meer worden geüpload tot er ruimte is."
|
||||
},
|
||||
"cleanup": {
|
||||
"open": "Opruimen",
|
||||
"title": "Opruimen",
|
||||
"description": "Foto's die ouder zijn dan het aantal dagen hieronder, nieuwste eerst. Haal foto's uit de selectie die je wilt houden.",
|
||||
"days_one": "Ouder dan {{count}} dag",
|
||||
"days_other": "Ouder dan {{count}} dagen",
|
||||
"onlyUnused": "Alleen ongebruikte foto's",
|
||||
"previewNote": "Dit is een voorbeeld: er wordt nog niets verwijderd.",
|
||||
"summary_one": "{{count}} foto ({{size}}) komt in aanmerking.",
|
||||
"summary_other": "{{count}} foto's ({{size}}) komen in aanmerking.",
|
||||
"selectedSize": "Geselecteerd: {{size}}"
|
||||
},
|
||||
"picker": {
|
||||
"upload": "Afbeelding uploaden",
|
||||
"uploading": "Bezig met uploaden...",
|
||||
"empty": "Er staan nog geen foto's in de bibliotheek. Upload er een.",
|
||||
"notAnImage": "Dit bestand is geen afbeelding.",
|
||||
"tooLarge": "Dit bestand is te groot (maximaal {{max}} MB).",
|
||||
"failed": "Uploaden is niet gelukt. Probeer het opnieuw."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@ import { systemHandlers } from '@/features/system/mocks/handlers';
|
||||
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
|
||||
import { contactHandlers } from '@/features/contact/mocks/handlers';
|
||||
import { heroHandlers } from '@/features/hero/mocks/handlers';
|
||||
import { mediaHandlers } from '@/features/media/mocks/handlers';
|
||||
|
||||
/** All default MSW handlers, composed from feature folders (Q3-B). */
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers];
|
||||
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers, ...heroHandlers, ...mediaHandlers];
|
||||
|
||||
export { authHandlers } from '@/features/auth/mocks/handlers';
|
||||
export { userHandlers } from '@/features/users/mocks/handlers';
|
||||
|
||||
@@ -245,6 +245,18 @@ const heroRoute = createRoute({
|
||||
),
|
||||
});
|
||||
|
||||
const mediaRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/media',
|
||||
component: () => (
|
||||
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
|
||||
<ModuleGuard requiredModule="Hero">
|
||||
{lazyPage(() => import('@/features/media/pages/MediaLibraryPage'), 'MediaLibraryPage')()}
|
||||
</ModuleGuard>
|
||||
</RoleGuard>
|
||||
),
|
||||
});
|
||||
|
||||
const offeringsRoute = createRoute({
|
||||
getParentRoute: () => authenticatedRoute,
|
||||
path: '/offerings',
|
||||
@@ -333,6 +345,7 @@ export const routeTree = rootRoute.addChildren([
|
||||
usersRoute,
|
||||
cmsRoute,
|
||||
heroRoute,
|
||||
mediaRoute,
|
||||
offeringsRoute,
|
||||
offeringsNewRoute,
|
||||
offeringsEditRoute,
|
||||
|
||||
@@ -1060,6 +1060,200 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaCleanupPreviewDto": {
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"count": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"days": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"onlyUnused": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"photos": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaPhotoDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"days",
|
||||
"onlyUnused",
|
||||
"count",
|
||||
"bytes",
|
||||
"photos"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaLibraryDto": {
|
||||
"properties": {
|
||||
"modules": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"photos": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaPhotoDto"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"photos",
|
||||
"modules"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaPhotoDto": {
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"createdAt": {
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
"height": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"module": {
|
||||
"type": "string"
|
||||
},
|
||||
"thumbnailUrl": {
|
||||
"type": [
|
||||
"null",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"uses": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MediaUseDto"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"width": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"module",
|
||||
"bytes",
|
||||
"width",
|
||||
"height",
|
||||
"createdAt",
|
||||
"thumbnailUrl",
|
||||
"uses"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaStorageDto": {
|
||||
"properties": {
|
||||
"level": {
|
||||
"type": "string"
|
||||
},
|
||||
"limitBytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"usedBytes": {
|
||||
"format": "int64",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"warningPercent": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"usedBytes",
|
||||
"limitBytes",
|
||||
"level",
|
||||
"warningPercent"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"MediaUseDto": {
|
||||
"properties": {
|
||||
"active": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"kind": {
|
||||
"type": "string"
|
||||
},
|
||||
"module": {
|
||||
"type": "string"
|
||||
},
|
||||
"position": {
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"null",
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"module",
|
||||
"kind",
|
||||
"position",
|
||||
"active"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"OfferingBannerRequest": {
|
||||
"properties": {
|
||||
"endsAt": {
|
||||
@@ -3252,6 +3446,116 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/cleanup-preview": {
|
||||
"get": {
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "days",
|
||||
"schema": {
|
||||
"default": 7,
|
||||
"format": "int32",
|
||||
"pattern": "^-?(?:0|[1-9]\\d*)$",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "onlyUnused",
|
||||
"schema": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaCleanupPreviewDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/photos": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaLibraryDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/media-library/storage": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
},
|
||||
"text/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
},
|
||||
"text/plain": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MediaStorageDto"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "OK"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"MediaLibrary"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/api/v1/offerings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
@@ -3653,6 +3957,9 @@
|
||||
{
|
||||
"name": "SlpModularCms.Api"
|
||||
},
|
||||
{
|
||||
"name": "MediaLibrary"
|
||||
},
|
||||
{
|
||||
"name": "System"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaLibraryControllerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
private static MediaLibraryItem Item(int daysOld, bool used)
|
||||
{
|
||||
var photo = new MediaPhoto("hero", Guid.NewGuid(), 1000, 1600, 1067, Now.AddDays(-daysOld), "/media/hero/0123456789abcdef/wide-480.webp");
|
||||
return new MediaLibraryItem(photo, used ? [new MediaUse("hero", photo.Id, "slide", 2, true)] : []);
|
||||
}
|
||||
|
||||
private static MediaLibraryController Controller(params MediaLibraryItem[] items)
|
||||
{
|
||||
var library = Substitute.For<IMediaLibraryService>();
|
||||
library.ListAsync(Arg.Any<CancellationToken>()).Returns(items.OrderByDescending(i => i.Photo.CreatedAt).ToList());
|
||||
library.Modules.Returns(["hero"]);
|
||||
return new MediaLibraryController(library, new Clock());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_administrators_may_use_it()
|
||||
{
|
||||
typeof(MediaLibraryController).GetCustomAttributes(typeof(AuthorizeAttribute), true)
|
||||
.Cast<AuthorizeAttribute>().Should().ContainSingle(a => a.Policy == "AdminOnly");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Photos_lists_each_photo_with_its_uses_and_a_module_prefixed_id()
|
||||
{
|
||||
var used = Item(2, used: true);
|
||||
var result = (OkObjectResult)await Controller(used, Item(9, used: false)).Photos(CancellationToken.None);
|
||||
|
||||
var dto = result.Value.Should().BeOfType<MediaLibraryDto>().Subject;
|
||||
dto.Photos.Should().HaveCount(2);
|
||||
dto.Photos[0].Id.Should().Be($"hero:{used.Photo.Id}");
|
||||
dto.Photos[0].Uses.Should().ContainSingle().Which.Should().Be(new MediaUseDto("hero", "slide", 2, true));
|
||||
dto.Modules.Should().Equal("hero");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_selects_old_unused_photos_and_deletes_nothing()
|
||||
{
|
||||
var oldUnused = Item(20, used: false);
|
||||
var controller = Controller(Item(3, used: false), Item(20, used: true), oldUnused);
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, true, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Count.Should().Be(1);
|
||||
preview.Photos.Single().Id.Should().Be($"hero:{oldUnused.Photo.Id}");
|
||||
preview.Bytes.Should().Be(1000);
|
||||
preview.OnlyUnused.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cleanup_preview_can_include_photos_in_use_and_keeps_the_period_in_range()
|
||||
{
|
||||
var controller = Controller(Item(20, used: true), Item(20, used: false));
|
||||
|
||||
var preview = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(99999, false, CancellationToken.None)).Value!;
|
||||
|
||||
preview.Days.Should().Be(365);
|
||||
preview.Count.Should().Be(0);
|
||||
var shorter = (MediaCleanupPreviewDto)((OkObjectResult)await controller.CleanupPreview(7, false, CancellationToken.None)).Value!;
|
||||
shorter.Count.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Storage_without_a_media_store_reports_zero_and_ok()
|
||||
{
|
||||
var result = (MediaStorageDto)((OkObjectResult)await Controller().Storage(CancellationToken.None)).Value!;
|
||||
|
||||
result.Should().Be(new MediaStorageDto(0, 0, "ok", 80));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaStorageUsageTests
|
||||
{
|
||||
private sealed class Clock(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(79, 100, MediaStorageLevel.Ok)]
|
||||
[InlineData(80, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(99, 100, MediaStorageLevel.Warning)]
|
||||
[InlineData(100, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 100, MediaStorageLevel.Full)]
|
||||
[InlineData(500, 0, MediaStorageLevel.Ok)]
|
||||
public void The_level_follows_the_share_of_the_limit(long used, long limit, MediaStorageLevel expected)
|
||||
=> MediaStorageUsage.LevelFor(used, limit).Should().Be(expected);
|
||||
|
||||
[Fact]
|
||||
public async Task The_measurement_is_kept_for_a_minute_and_then_taken_again()
|
||||
{
|
||||
var store = Substitute.For<IMediaStore>();
|
||||
store.GetTotalBytesAsync(Arg.Any<CancellationToken>()).Returns(850L, 900L);
|
||||
var clock = new Clock(new DateTimeOffset(2026, 11, 17, 12, 0, 0, TimeSpan.Zero));
|
||||
var usage = new MediaStorageUsage(store, Options.Create(new MediaOptions { MaxTotalBytes = 1000 }), clock);
|
||||
|
||||
var first = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(30);
|
||||
var cached = await usage.GetAsync(CancellationToken.None);
|
||||
clock.Now = clock.Now.AddSeconds(31);
|
||||
var later = await usage.GetAsync(CancellationToken.None);
|
||||
|
||||
first.Should().Be(new MediaStorageInfo(850, 1000, MediaStorageLevel.Warning));
|
||||
cached.Should().BeSameAs(first);
|
||||
later.UsedBytes.Should().Be(900);
|
||||
await store.Received(2).GetTotalBytesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Library;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Media;
|
||||
|
||||
public class MediaUseDefinitionTests
|
||||
{
|
||||
private const string Sha = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
[Fact]
|
||||
public void Every_ratio_name_and_width_fits_the_media_address_scheme()
|
||||
{
|
||||
foreach (var use in GalleryUses.All)
|
||||
{
|
||||
var plans = use.PlansFor(4000, 3000);
|
||||
var specs = VariantPlanner.Plan(4000, 3000, plans, new HashSet<ImageFormat> { ImageFormat.WebP });
|
||||
specs.Should().NotBeEmpty(use.Key);
|
||||
foreach (var spec in specs)
|
||||
{
|
||||
var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format);
|
||||
MediaPaths.TryParse($"{use.Module}/{use.SetHash(Sha)}/{name}", out _).Should().BeTrue($"{use.Key}: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_keys_are_unique() => GalleryUses.All.Select(u => u.Key).Should().OnlyHaveUniqueItems();
|
||||
|
||||
[Fact]
|
||||
public void A_mosaic_use_has_a_desktop_and_a_phone_shape_and_a_masonry_use_has_none_of_its_own()
|
||||
{
|
||||
GalleryUses.MosaicLarge.Ratios.Select(r => r.Name).Should().Equal("tilelarge", "tilelargem");
|
||||
GalleryUses.Masonry.Natural.Should().BeTrue();
|
||||
GalleryUses.Masonry.PlansFor(3000, 2000).Should().ContainSingle().Which.Ratio.Should().Be(new Ratio("natural", 3000, 2000));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_natural_use_keeps_the_photos_own_shape_without_a_crop()
|
||||
{
|
||||
var spec = VariantPlanner.Plan(3000, 2000, GalleryUses.Masonry.PlansFor(3000, 2000), new HashSet<ImageFormat> { ImageFormat.WebP })
|
||||
.Single(s => s.Width == 800);
|
||||
|
||||
(spec.Crop.Width, spec.Crop.Height).Should().Be((3000, 2000));
|
||||
spec.Height.Should().Be(533);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_crop_of_a_use_changes_its_set_hash_but_not_the_set_hash_of_another_use()
|
||||
{
|
||||
var focus = new Dictionary<string, FocusSetting> { ["tilelarge"] = new(0.2, 0.3, 1.5) };
|
||||
|
||||
GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().NotBe(GalleryUses.MosaicLarge.SetHash(Sha));
|
||||
GalleryUses.MosaicWide.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicWide.SetHash(Sha));
|
||||
GalleryUses.MosaicLarge.SetHash(Sha, focus).Should().Be(GalleryUses.MosaicLarge.SetHash(Sha, focus));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_natural_use_does_not_depend_on_a_crop()
|
||||
=> GalleryUses.Masonry.SetHash(Sha, new Dictionary<string, FocusSetting> { ["natural"] = new(0.1, 0.1, 2) }).Should().Be(GalleryUses.Masonry.SetHash(Sha));
|
||||
|
||||
[Fact]
|
||||
public void The_set_hash_formula_is_the_one_the_hero_uses_today()
|
||||
{
|
||||
// Same inputs through the shared function the hero calls: the library does not invent a second scheme.
|
||||
var hero = new MediaUseDefinition("hero", "hero", [new("wide", 3, 2, [640]), new("tall", 4, 5, [480])]);
|
||||
var focus = new Dictionary<string, FocusSetting> { ["wide"] = new(0.3, 0.4, 1.2) };
|
||||
|
||||
hero.SetHash(Sha, focus).Should().Be(MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.3, 0.4, 1.2)), ("tall", FocusSetting.Centre)]));
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,8 @@ public static class ServiceCollectionExtensions
|
||||
services.AddOptions<DataProtectionTokenProviderOptions>()
|
||||
.Configure<IOptions<PasswordResetSettings>>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
// The media library reads from the usage providers of whichever modules are loaded (none is fine).
|
||||
services.TryAddScoped<Media.Library.IMediaLibraryService, Media.Library.MediaLibraryService>();
|
||||
services.TryAddSingleton(sp =>
|
||||
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
|
||||
services.AddScoped<IPasswordResetService, PasswordResetService>();
|
||||
|
||||
@@ -65,6 +65,14 @@ public sealed class MediaOptions
|
||||
public long MaxTotalBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
|
||||
public int RetentionDays { get; set; } = 7;
|
||||
|
||||
/// <summary>
|
||||
/// Whether photos that were uploaded but never used are removed automatically after <see cref="RetentionDays"/>.
|
||||
/// The media library keeps everything until a person removes it, so set this to <c>false</c> (<c>Media__AutoCleanupUnattached=false</c>)
|
||||
/// once the library can show and delete photos. Retired files of photos a person removed stay housekeeping either way.
|
||||
/// Default <c>true</c> keeps today's behaviour (assumption 3 of the media-library list).
|
||||
/// </summary>
|
||||
public bool AutoCleanupUnattached { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public sealed record MediaUseDto(string Module, string Kind, int? Position, bool Active);
|
||||
|
||||
public sealed record MediaPhotoDto(string Id, string Module, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl, IReadOnlyList<MediaUseDto> Uses);
|
||||
|
||||
public sealed record MediaLibraryDto(IReadOnlyList<MediaPhotoDto> Photos, IReadOnlyList<string> Modules);
|
||||
|
||||
public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent);
|
||||
|
||||
/// <summary>What a clean-up with these settings would select. A preview only: nothing is deleted.</summary>
|
||||
public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList<MediaPhotoDto> Photos);
|
||||
|
||||
/// <summary>
|
||||
/// The media library for administrators: the photos of all modules with where they are used, the storage against its
|
||||
/// limit, and a preview of the clean-up. Read-only: deleting comes after the assumptions are checked.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("media-library")]
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase
|
||||
{
|
||||
[HttpGet("photos")]
|
||||
[ProducesResponseType<MediaLibraryDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Photos(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await library.ListAsync(cancellationToken);
|
||||
return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules));
|
||||
}
|
||||
|
||||
[HttpGet("storage")]
|
||||
[ProducesResponseType<MediaStorageDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Storage(CancellationToken cancellationToken)
|
||||
{
|
||||
// A host without media has nothing stored: zero used, no limit.
|
||||
var info = storage is null ? new MediaStorageInfo(0, 0, MediaStorageLevel.Ok) : await storage.GetAsync(cancellationToken);
|
||||
return Ok(new MediaStorageDto(info.UsedBytes, info.LimitBytes, info.Level.ToString().ToLowerInvariant(), MediaStorageUsage.WarningPercent));
|
||||
}
|
||||
|
||||
[HttpGet("cleanup-preview")]
|
||||
[ProducesResponseType<MediaCleanupPreviewDto>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CleanupPreview([FromQuery] int days = CleanupSelection.DefaultDays, [FromQuery] bool onlyUnused = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var clamped = CleanupSelection.ClampDays(days);
|
||||
var selected = CleanupSelection.Select(await library.ListAsync(cancellationToken), time.GetUtcNow(), clamped, onlyUnused);
|
||||
return Ok(new MediaCleanupPreviewDto(clamped, onlyUnused, selected.Count, CleanupSelection.Bytes(selected), selected.Select(ToDto).ToList()));
|
||||
}
|
||||
|
||||
private static MediaPhotoDto ToDto(MediaLibraryItem item)
|
||||
=> new(
|
||||
$"{item.Photo.Module}:{item.Photo.Id}",
|
||||
item.Photo.Module,
|
||||
item.Photo.Bytes,
|
||||
item.Photo.Width,
|
||||
item.Photo.Height,
|
||||
item.Photo.CreatedAt,
|
||||
item.Photo.ThumbnailUrl,
|
||||
item.Uses.Select(u => new MediaUseDto(u.Module, u.PlaceKind, u.Position, u.Active)).ToList());
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
public enum MediaStorageLevel
|
||||
{
|
||||
Ok,
|
||||
Warning,
|
||||
Full,
|
||||
}
|
||||
|
||||
/// <param name="UsedBytes">Everything in the media directory (originals and variants).</param>
|
||||
/// <param name="LimitBytes">The safety limit; 0 means no limit.</param>
|
||||
public sealed record MediaStorageInfo(long UsedBytes, long LimitBytes, MediaStorageLevel Level);
|
||||
|
||||
/// <summary>
|
||||
/// The space the media directory takes against its limit (<c>Media:MaxTotalBytes</c>). Measuring walks the directory, so
|
||||
/// the answer is kept for a minute (assumption 9 of the media-library list: warning at 80 percent, full at 100).
|
||||
/// </summary>
|
||||
public sealed class MediaStorageUsage(IMediaStore store, IOptions<MediaOptions> options, TimeProvider? time = null)
|
||||
{
|
||||
public const int WarningPercent = 80;
|
||||
private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(60);
|
||||
private readonly TimeProvider _time = time ?? TimeProvider.System;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private MediaStorageInfo? _cached;
|
||||
private DateTimeOffset _measuredAt;
|
||||
|
||||
public static MediaStorageLevel LevelFor(long used, long limit)
|
||||
{
|
||||
if (limit <= 0)
|
||||
{
|
||||
return MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
if (used >= limit)
|
||||
{
|
||||
return MediaStorageLevel.Full;
|
||||
}
|
||||
|
||||
return used * 100 >= limit * WarningPercent ? MediaStorageLevel.Warning : MediaStorageLevel.Ok;
|
||||
}
|
||||
|
||||
public async Task<MediaStorageInfo> GetAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = _time.GetUtcNow();
|
||||
if (_cached is { } fresh && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return fresh;
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
now = _time.GetUtcNow();
|
||||
if (_cached is { } again && now - _measuredAt < CacheFor)
|
||||
{
|
||||
return again;
|
||||
}
|
||||
|
||||
var used = await store.GetTotalBytesAsync(cancellationToken);
|
||||
var limit = Math.Max(0, options.Value.MaxTotalBytes);
|
||||
_cached = new MediaStorageInfo(used, limit, LevelFor(used, limit));
|
||||
_measuredAt = now;
|
||||
return _cached;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>One ratio of a use: its name (part of the file name), its shape and the widths cut for it.</summary>
|
||||
public sealed record UseRatio(string Name, int Numerator, int Denominator, IReadOnlyList<int> Widths);
|
||||
|
||||
/// <summary>
|
||||
/// What a USE of a photo needs (a place on a page, not the photo itself): the ratios with their widths, or the natural
|
||||
/// shape of the photo without a crop. A photo can have several uses; each use has its own crop (focus per ratio) and so
|
||||
/// its own set. Pure data, no behaviour that moves anything.
|
||||
/// </summary>
|
||||
/// <param name="Key">For example <c>mosaic-large</c>; unique.</param>
|
||||
/// <param name="Module">The module whose pages show it (also its media area).</param>
|
||||
/// <param name="Ratios">Empty for a natural-ratio use.</param>
|
||||
/// <param name="Natural">The photo is shown in its own shape: no crop, one ratio taken from the photo itself.</param>
|
||||
public sealed record MediaUseDefinition(string Key, string Module, IReadOnlyList<UseRatio> Ratios, bool Natural = false)
|
||||
{
|
||||
public const string NaturalRatioName = "natural";
|
||||
|
||||
/// <summary>The ratio plans for a photo, given the focus per ratio name (centre when none is given).</summary>
|
||||
public IReadOnlyList<RatioPlan> PlansFor(int sourceWidth, int sourceHeight, IReadOnlyDictionary<string, FocusSetting>? focus = null)
|
||||
{
|
||||
if (Natural)
|
||||
{
|
||||
var widths = Ratios.Count > 0 ? Ratios[0].Widths : [];
|
||||
return [new RatioPlan(new Ratio(NaturalRatioName, sourceWidth, sourceHeight), FocusSetting.Centre, widths)];
|
||||
}
|
||||
|
||||
return Ratios
|
||||
.Select(r => new RatioPlan(new Ratio(r.Name, r.Numerator, r.Denominator), focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre, r.Widths))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The set hash of this use for a photo: the existing formula over the photo's hash and the crops of this use, so a
|
||||
/// photo gets the same address for the same use and crops, and another use never shares a set by accident.
|
||||
/// A natural-ratio use has no crop, so its set depends on the photo alone (and the use key).
|
||||
/// </summary>
|
||||
public string SetHash(string originalSha256, IReadOnlyDictionary<string, FocusSetting>? focus = null)
|
||||
{
|
||||
var crops = Natural
|
||||
? [(NaturalRatioName, FocusSetting.Centre)]
|
||||
: Ratios.Select(r => (r.Name, focus is not null && focus.TryGetValue(r.Name, out var f) ? f : FocusSetting.Centre)).ToList();
|
||||
return MediaPaths.SetHash(originalSha256, crops);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The uses of the gallery that the Andrea Slop Fotografie site needs (answer of the ASF session, 2026-11-17): the
|
||||
/// mosaic tiles (a shape fixed per page by the number and order of the photos, a desktop and a phone shape each) and the
|
||||
/// masonry portfolio (natural shape). Ratio names are letters only, 2 to 10 long, so they fit the address allow-list.
|
||||
/// </summary>
|
||||
public static class GalleryUses
|
||||
{
|
||||
public const string Module = "gallery";
|
||||
|
||||
private static readonly int[] Large = [480, 640, 960, 1280];
|
||||
private static readonly int[] Small = [312, 480, 640];
|
||||
|
||||
/// <summary>Photo 1 of 2 to 4: about 1:1 on desktop (max about 656 wide), 4:3 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicLarge = new("mosaic-large", Module, [new("tilelarge", 1, 1, Large), new("tilelargem", 4, 3, Large)]);
|
||||
|
||||
/// <summary>Photo 2 of 3 or 4: about 2.2:1 on desktop, 3:2 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicWide = new("mosaic-wide", Module, [new("tilewide", 11, 5, Large), new("tilewidem", 3, 2, Large)]);
|
||||
|
||||
/// <summary>Photos 3 and 4 of 4: about 1.04:1 on desktop (max about 312 wide), 1:1 on a phone.</summary>
|
||||
public static readonly MediaUseDefinition MosaicSmall = new("mosaic-small", Module, [new("tilesmall", 26, 25, Small), new("tilesmallm", 1, 1, Small)]);
|
||||
|
||||
/// <summary>The portfolio: the photo's own shape, no crop; thumbnail widths about 480 and 800.</summary>
|
||||
public static readonly MediaUseDefinition Masonry = new("masonry", Module, [new(MediaUseDefinition.NaturalRatioName, 1, 1, [480, 800])], Natural: true);
|
||||
|
||||
public static IReadOnlyList<MediaUseDefinition> All { get; } = [MosaicLarge, MosaicWide, MosaicSmall, Masonry];
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public static class MediaServiceCollectionExtensions
|
||||
services.TryAddSingleton<MediaAreaRegistry>();
|
||||
services.TryAddSingleton<IMediaStore, FileSystemMediaStore>();
|
||||
services.TryAddSingleton<IMediaUploadGuard, MediaUploadGuard>();
|
||||
services.TryAddScoped<Library.IMediaLibraryService, Library.MediaLibraryService>();
|
||||
services.TryAddSingleton<Library.MediaStorageUsage>();
|
||||
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
|
||||
{
|
||||
services.AddHostedService<ImageProcessorSelfTest>();
|
||||
|
||||
@@ -412,6 +412,37 @@ public class HeroMediaCleanupTests
|
||||
again.Variants.Should().OnlyContain(v => v.Url.Contains(set));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsKept_WhenAutomaticCleanupIsOff()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.AutoCleanupUnattached = false;
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(400);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Time.Now = rig.Time.Now.AddDays(400);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APhotoAPersonRemoved_StillLeavesAfterTheRetentionTime_WhenAutomaticCleanupIsOff()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.AutoCleanupUnattached = false;
|
||||
var (set, original) = await RetireAnImage(rig);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().NotContain(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsRetiredAndRemoved_AfterTheRetentionTime()
|
||||
{
|
||||
|
||||
@@ -29,7 +29,11 @@ public class HeroMediaCleanup(
|
||||
var removed = 0;
|
||||
|
||||
// 1. Images that were uploaded but never used by a slide: retire them (their files go on a later run).
|
||||
foreach (var image in await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken))
|
||||
// Skipped when the media library keeps every upload until a person removes it (Media:AutoCleanupUnattached = false).
|
||||
var unattached = options.Value.AutoCleanupUnattached
|
||||
? await repository.GetUnattachedImagesCreatedBeforeAsync(cutoff, cancellationToken)
|
||||
: [];
|
||||
foreach (var image in unattached)
|
||||
{
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = cutoff.AddSeconds(-1) });
|
||||
repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = cutoff.AddSeconds(-1) });
|
||||
|
||||
Reference in New Issue
Block a user