From caa178a58c00d9daacbe5fcbc7196d8b23f63f23 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 17 Nov 2026 14:12:15 +0100 Subject: [PATCH] Mediabibliotheek: endpoints (foto's, opslag, opruimvoorbeeld) en scherm; ASF-verhoudingen in ontwerp en aannamelijst Co-Authored-By: Claude Sonnet 5.5 --- .../assumptions-and-open-questions.md | 2 +- .../application-design/application-design.md | 11 + frontend/src/components/layout/Sidebar.tsx | 10 +- .../media/components/CleanupDialog.tsx | 112 +++++++ .../media/components/PhotoSelectionList.tsx | 12 +- .../media/components/StorageMeter.tsx | 43 +++ frontend/src/features/media/lib/format.ts | 12 + .../src/features/media/lib/toPhotoItem.ts | 15 + frontend/src/features/media/mocks/handlers.ts | 58 ++++ .../media/pages/MediaLibraryPage.test.tsx | 84 +++++ .../features/media/pages/MediaLibraryPage.tsx | 57 ++++ frontend/src/features/media/services/hooks.ts | 32 ++ frontend/src/features/media/services/types.ts | 41 +++ frontend/src/i18n/locales/en/translation.json | 39 ++- frontend/src/i18n/locales/nl/translation.json | 39 ++- frontend/src/mocks/index.ts | 3 +- frontend/src/router.tsx | 13 + openapi/slpsoftware.v1.json | 304 ++++++++++++++++++ .../Media/MediaLibraryControllerTests.cs | 87 +++++ .../Media/MediaStorageUsageTests.cs | 49 +++ .../Hosting/ServiceCollectionExtensions.cs | 2 + .../Media/Library/MediaLibraryController.cs | 63 ++++ .../Media/Library/MediaStorageUsage.cs | 72 +++++ .../Media/MediaServiceCollectionExtensions.cs | 2 +- 24 files changed, 1141 insertions(+), 21 deletions(-) create mode 100644 frontend/src/features/media/components/CleanupDialog.tsx create mode 100644 frontend/src/features/media/components/StorageMeter.tsx create mode 100644 frontend/src/features/media/lib/format.ts create mode 100644 frontend/src/features/media/lib/toPhotoItem.ts create mode 100644 frontend/src/features/media/mocks/handlers.ts create mode 100644 frontend/src/features/media/pages/MediaLibraryPage.test.tsx create mode 100644 frontend/src/features/media/pages/MediaLibraryPage.tsx create mode 100644 frontend/src/features/media/services/hooks.ts create mode 100644 frontend/src/features/media/services/types.ts create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs create mode 100644 src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md index e4d56f5..2c0070a 100644 --- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md +++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md @@ -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 | diff --git a/aidlc-docs/features/media-library/inception/application-design/application-design.md b/aidlc-docs/features/media-library/inception/application-design/application-design.md index 24fb79e..fa83759 100644 --- a/aidlc-docs/features/media-library/inception/application-design/application-design.md +++ b/aidlc-docs/features/media-library/inception/application-design/application-design.md @@ -114,6 +114,17 @@ Text alternative: one photo has uses in Hero (wide and tall share one set), a mo - `MediaUseDefinition` (code, per module): ratio names, ratio values and widths for the variant planner. Hero's `wide` and `tall` exist today; the mosaic's tile ratios and masonry's natural ratio are added by the gallery module. - A natural-ratio use stores no crop (focus ignored); the planner produces widths only. +- **Use definitions from the ASF site (2026-11-17, see assumption 24)**: + +| Use | Ratio (desktop / phone) | Widths | Crop | +|---|---|---|---| +| `hero-wide`, `hero-tall` | 3:2 / 2:3 (as built) | as built | focus per use | +| `mosaic-large` (photo 1) | about 1:1 / 4:3 | up to 656, retina 480, 640, 960, 1280 | focus point | +| `mosaic-wide` (photo 2 of 3 or 4) | about 2.2:1 / 3:2 | up to 656, same retina set | focus point | +| `mosaic-small` (photos 3 and 4 of 4) | about 1.04:1 / 1:1 | up to 312, retina set | focus point | +| `masonry` | natural | about 480 and 800 (thumb), plus `full` for the lightbox | none | + +The mosaic tile shape is fixed per page by the number and order of the photos, so a use is `(page, tile role)`; a photo can have a different crop in each role. Phone shapes differ from desktop shapes, so a mosaic use carries two ratios (desktop and phone), like Hero's `wide` and `tall`. - The Hero sets are unchanged: one use per slide carrying the image's `wide` and `tall` crops, one set hash. ## 5. Delete and clean-up flow diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index ca75982..e5c84c4 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; -import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon } from 'lucide-react'; +import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X, Image as ImageIcon, Images } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useAuth } from '@/features/auth/context/auth-context'; @@ -38,6 +38,14 @@ const NAV_ITEMS: NavItem[] = [ roles: ['Owner', 'Administrator'], requiredModule: 'Hero', }, + { + to: '/media', + labelKey: 'nav.media', + icon: Images, + testId: 'nav-media', + roles: ['Owner', 'Administrator'], + requiredModule: 'Hero', + }, { to: '/offerings', labelKey: 'nav.offerings', diff --git a/frontend/src/features/media/components/CleanupDialog.tsx b/frontend/src/features/media/components/CleanupDialog.tsx new file mode 100644 index 0000000..11b4974 --- /dev/null +++ b/frontend/src/features/media/components/CleanupDialog.tsx @@ -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>(new Set()); + const timer = useRef | 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(() => 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 ( + + + + {t('media.cleanup.title')} + {t('media.cleanup.description')} + + +
+
+ + changeDays(Number(event.target.value))} + className="w-full accent-primary" + data-testid="cleanup-days" + /> +
+ { + setOnlyUnused(event.target.checked); + setExcluded(new Set()); + }} + label={t('media.cleanup.onlyUnused')} + data-testid="cleanup-only-unused" + /> + +

+ {t('media.cleanup.previewNote')} +

+ + {preview.isError && ( +

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

+ )} + {preview.isPending &&

{t('media.loading')}

} + {preview.data && ( + <> +

+ {t('media.cleanup.summary', { count: preview.data.count, size: formatBytes(preview.data.bytes, i18n.language) })} +

+ + setSelection(new Set())} + summary={t('media.cleanup.selectedSize', { size: formatBytes(selectedBytes, i18n.language) })} + /> + + )} +
+
+
+ ); +} diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx index cb87ab6..d9f7a46 100644 --- a/frontend/src/features/media/components/PhotoSelectionList.tsx +++ b/frontend/src/features/media/components/PhotoSelectionList.tsx @@ -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. diff --git a/frontend/src/features/media/components/StorageMeter.tsx b/frontend/src/features/media/components/StorageMeter.tsx new file mode 100644 index 0000000..a9509b8 --- /dev/null +++ b/frontend/src/features/media/components/StorageMeter.tsx @@ -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 ( +
+

+ {t('media.storage.title')} +

+

+ {hasLimit ? t('media.storage.usedOf', { used, limit: formatBytes(storage.limitBytes, i18n.language), percent }) : t('media.storage.used', { used })} +

+ {hasLimit && ( +
+
+
+ )} + {storage.level !== 'ok' && ( +

+ {storage.level === 'full' ? t('media.storage.full') : t('media.storage.warning', { percent: storage.warningPercent })} +

+ )} +
+ ); +} diff --git a/frontend/src/features/media/lib/format.ts b/frontend/src/features/media/lib/format.ts new file mode 100644 index 0000000..095d155 --- /dev/null +++ b/frontend/src/features/media/lib/format.ts @@ -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]}`; +} diff --git a/frontend/src/features/media/lib/toPhotoItem.ts b/frontend/src/features/media/lib/toPhotoItem.ts new file mode 100644 index 0000000..8607e91 --- /dev/null +++ b/frontend/src/features/media/lib/toPhotoItem.ts @@ -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, + }; +} diff --git a/frontend/src/features/media/mocks/handlers.ts b/frontend/src/features/media/mocks/handlers.ts new file mode 100644 index 0000000..4db340b --- /dev/null +++ b/frontend/src/features/media/mocks/handlers.ts @@ -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); + }), +]; diff --git a/frontend/src/features/media/pages/MediaLibraryPage.test.tsx b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx new file mode 100644 index 0000000..b8a4ffb --- /dev/null +++ b/frontend/src/features/media/pages/MediaLibraryPage.test.tsx @@ -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(); + + 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(); + 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(); + expect(await screen.findByTestId('storage-warning')).toHaveTextContent('vol'); + }); + + it('selects photos and shows the bulk bar without any delete action yet', async () => { + renderWithProviders(); + 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(); + 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(); + 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(); + + expect(await screen.findByTestId('media-error')).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/features/media/pages/MediaLibraryPage.tsx b/frontend/src/features/media/pages/MediaLibraryPage.tsx new file mode 100644 index 0000000..d2b574f --- /dev/null +++ b/frontend/src/features/media/pages/MediaLibraryPage.tsx @@ -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(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 ( +
+
+

{t('media.page.title')}

+ +
+ + {storage.data && } + + {photos.isError && ( +

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

+ )} + {photos.isPending &&

{t('media.loading')}

} + {photos.data && photos.data.modules.length === 0 && ( +

+ {t('media.page.noModules')} +

+ )} + {photos.data && } + setSelection(emptySelection)} /> + + +
+ ); +} diff --git a/frontend/src/features/media/services/hooks.ts b/frontend/src/features/media/services/hooks.ts new file mode 100644 index 0000000..fa7e09c --- /dev/null +++ b/frontend/src/features/media/services/hooks.ts @@ -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({ + queryKey: [...MEDIA_KEY, 'photos'], + queryFn: () => api.get('/api/v1/media-library/photos'), + }); +} + +/** The space the media directory takes against its limit. */ +export function useMediaStorage() { + return useQuery({ + queryKey: [...MEDIA_KEY, 'storage'], + queryFn: () => api.get('/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({ + queryKey: [...MEDIA_KEY, 'cleanup-preview', days, onlyUnused], + queryFn: () => api.get(`/api/v1/media-library/cleanup-preview?days=${days}&onlyUnused=${onlyUnused}`), + enabled, + placeholderData: keepPreviousData, + }); +} diff --git a/frontend/src/features/media/services/types.ts b/frontend/src/features/media/services/types.ts new file mode 100644 index 0000000..c577e5c --- /dev/null +++ b/frontend/src/features/media/services/types.ts @@ -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[]; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 694e495..c6c8b7e 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -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}}" } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 53725a7..ee9c693 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -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}}" } } } diff --git a/frontend/src/mocks/index.ts b/frontend/src/mocks/index.ts index 717edf6..fd565d6 100644 --- a/frontend/src/mocks/index.ts +++ b/frontend/src/mocks/index.ts @@ -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'; diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index d4be45f..1c43541 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -245,6 +245,18 @@ const heroRoute = createRoute({ ), }); +const mediaRoute = createRoute({ + getParentRoute: () => authenticatedRoute, + path: '/media', + component: () => ( + + + {lazyPage(() => import('@/features/media/pages/MediaLibraryPage'), 'MediaLibraryPage')()} + + + ), +}); + const offeringsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/offerings', @@ -333,6 +345,7 @@ export const routeTree = rootRoute.addChildren([ usersRoute, cmsRoute, heroRoute, + mediaRoute, offeringsRoute, offeringsNewRoute, offeringsEditRoute, diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 843d434..252268b 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -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": { diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs new file mode 100644 index 0000000..fc44359 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryControllerTests.cs @@ -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(); + library.ListAsync(Arg.Any()).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().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().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)); + } +} diff --git a/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs new file mode 100644 index 0000000..6ad3496 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Media/MediaStorageUsageTests.cs @@ -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(); + store.GetTotalBytesAsync(Arg.Any()).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()); + } +} diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index 79a14b8..c199a95 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -85,6 +85,8 @@ public static class ServiceCollectionExtensions services.AddOptions() .Configure>((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(); services.TryAddSingleton(sp => new ResetCooldown(sp.GetRequiredService(), TimeSpan.FromMinutes(sp.GetRequiredService>().Value.CooldownMinutes))); services.AddScoped(); diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs new file mode 100644 index 0000000..0d22b3f --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryController.cs @@ -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 Uses); + +public sealed record MediaLibraryDto(IReadOnlyList Photos, IReadOnlyList Modules); + +public sealed record MediaStorageDto(long UsedBytes, long LimitBytes, string Level, int WarningPercent); + +/// What a clean-up with these settings would select. A preview only: nothing is deleted. +public sealed record MediaCleanupPreviewDto(int Days, bool OnlyUnused, int Count, long Bytes, IReadOnlyList Photos); + +/// +/// 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. +/// +[ApiController] +[Route("media-library")] +[Authorize(Policy = "AdminOnly")] +public class MediaLibraryController(IMediaLibraryService library, TimeProvider time, MediaStorageUsage? storage = null) : ControllerBase +{ + [HttpGet("photos")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Photos(CancellationToken cancellationToken) + { + var items = await library.ListAsync(cancellationToken); + return Ok(new MediaLibraryDto(items.Select(ToDto).ToList(), library.Modules)); + } + + [HttpGet("storage")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task 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(StatusCodes.Status200OK)] + public async Task 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()); +} diff --git a/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs b/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs new file mode 100644 index 0000000..c0d2d6b --- /dev/null +++ b/src/SlpModularCms.Core/Media/Library/MediaStorageUsage.cs @@ -0,0 +1,72 @@ +using Microsoft.Extensions.Options; + +namespace SlpModularCms.Core.Media.Library; + +public enum MediaStorageLevel +{ + Ok, + Warning, + Full, +} + +/// Everything in the media directory (originals and variants). +/// The safety limit; 0 means no limit. +public sealed record MediaStorageInfo(long UsedBytes, long LimitBytes, MediaStorageLevel Level); + +/// +/// The space the media directory takes against its limit (Media:MaxTotalBytes). 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). +/// +public sealed class MediaStorageUsage(IMediaStore store, IOptions 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 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(); + } + } +} diff --git a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs index 4fdd8bd..02a12e1 100644 --- a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs @@ -22,7 +22,7 @@ public static class MediaServiceCollectionExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddScoped(); + services.TryAddSingleton(); if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest))) { services.AddHostedService();