Mediabibliotheek: endpoints (foto's, opslag, opruimvoorbeeld) en scherm; ASF-verhoudingen in ontwerp en aannamelijst
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / config-sls (pull_request) Successful in 7s
Continuous Integration / changes (pull_request) Successful in 11s
Continuous Integration / compile-sites (pull_request) Successful in 1m44s
Continuous Integration / backend-build (pull_request) Successful in 1m49s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m51s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m2s
Continuous Integration / frontend-build (pull_request) Successful in 42s
Continuous Integration / backend-test (pull_request) Failing after 3m56s
Continuous Integration / frontend-lint (pull_request) Successful in 39s
Continuous Integration / frontend-test (pull_request) Successful in 2m33s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,4 +27,4 @@ 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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,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,51 @@
|
||||
}
|
||||
},
|
||||
"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}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,51 @@
|
||||
}
|
||||
},
|
||||
"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}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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>());
|
||||
}
|
||||
}
|
||||
@@ -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>();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>();
|
||||
|
||||
Reference in New Issue
Block a user