Lege Bildfassungen an und liefere sie zwischengespeichert aus (ADR-63)
CI Feature / test (push) Successful in 6m26s
Deploy Test / test (push) Successful in 5m14s
Deploy Test / deploy (push) Successful in 31s

Vorschaubilder entstehen zusätzlich als klein (360 px) und mittel (960 px),
Website-Bilder in den Breiten 640, 1280 und 1920. Auswahl, Listen und Karten
laden die kleinen Fassungen; die Website nutzt srcset. Adressen tragen Größe und
Version und werden dauerhaft zwischengespeichert (ETag, 304). Die Website-Route
läuft ohne Sitzung und Cookies. Bestand füllt sich über die Warteschlange oder
mit media:varianten. Die Optionsliste des CMS fragt nicht mehr je Eintrag ab.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-28 09:37:00 +01:00
1 parent 0492133201
commit 63b42b366c
54 files changed
+1033 -82

No files matched your search

@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use App\Jobs\DeriveImageVariants;
use App\Jobs\DeriveWebsiteVariants;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
/**
* Legt für vorhandene Bilder die kleineren Fassungen an (docs/architektur/bildvarianten.md). Neue Bilder bekommen sie beim
* Ableiten; dieser Befehl holt den Bestand nach. Die Arbeit macht die Warteschlange (nur sie darf in derived/ und public/
* schreiben); mit --now läuft sie hier im Prozess, den man dafür im Queue-Container startet.
*/
class DeriveMediaVariants extends Command
{
protected $signature = 'media:varianten {--now : Sofort hier ausführen statt in die Warteschlange zu legen} {--pretend : Nur zählen}';
protected $description = 'Legt für vorhandene Vorschaubilder und freigegebene Website-Bilder die kleineren Fassungen an';
public function handle(): int
{
$derived = Storage::disk('media_derived');
$paths = [];
foreach ([ContentElement::query(), Composition::query()] as $query) {
$query->where('thumbnail_path', 'like', 'vorschau/%')
->pluck('thumbnail_path')
->each(function (mixed $path) use (&$paths): void {
if (is_string($path)) {
$paths[$path] = true;
}
});
}
$missing = array_values(array_filter(
array_keys($paths),
fn (string $path): bool => ! str_contains($path, '..')
&& ! $derived->exists(ImageVariants::path($path, 'klein'))
&& $derived->exists($path),
));
$websiteIds = ContentElement::query()
->where('output_class', 'bild')
->whereNotNull('website_released_at')
->whereNotNull('website_public_path')
->pluck('id')
->all();
$this->info(count($missing).' Vorschaubilder ohne Fassungen, '.count($websiteIds).' freigegebene Website-Bilder.');
if ($this->option('pretend')) {
return self::SUCCESS;
}
foreach ($missing as $path) {
$this->option('now') ? DeriveImageVariants::dispatchSync($path) : DeriveImageVariants::dispatch($path);
}
foreach ($websiteIds as $id) {
$this->option('now') ? DeriveWebsiteVariants::dispatchSync((int) $id) : DeriveWebsiteVariants::dispatch((int) $id);
}
$this->info($this->option('now') ? 'Fassungen angelegt.' : 'In die Warteschlange gelegt.');
return self::SUCCESS;
}
}
+2 -2
View File
@@ -49,7 +49,7 @@ public function rows(Model $subject): array
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
@@ -134,7 +134,7 @@ public function describe(array $staged): array
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
+1 -1
View File
@@ -104,7 +104,7 @@ public static function previewUrl(?string $target): ?string
return route('website.media', $element);
}
return app(EditorialCatalog::class)->cardUrl('element', $element->id, $element->thumbnail_path);
return app(EditorialCatalog::class)->cardUrl('element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
/**
@@ -319,7 +319,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
notice: $notice,
visual: 'catalog',
visualLabel: $kind,
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at) : null,
missing: $missing,
texts: $texts,
);
@@ -221,7 +221,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
$missing[] = 'Kein Anzeigetitel gepflegt; die Karte zeigt den Arbeitstitel.';
}
$previewImage = $includeNonPublic ? ThumbnailRef::url('editorial.card', 'element', (int) $element->id, $shown->thumbnail_path) : null;
$previewImage = $includeNonPublic ? ThumbnailRef::url('editorial.card', 'element', (int) $element->id, $shown->thumbnail_path, 'mittel', $shown->updated_at) : null;
return new CardSubject(
title: $title,
+1 -1
View File
@@ -115,7 +115,7 @@ private function renderSection(array $section, array $cells, int $index, RenderC
$style = SectionStyle::fromStored($section['style'] ?? []);
$columns = SectionLayouts::columns(array_column($cells, 'units'));
// Hintergrundbild aus dem Medienmanager: öffentlich nur mit Website-Freigabe (WebsiteImage → WebsiteMedia).
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview) : null;
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview, 1920) : null;
$hasImage = $imageUrl !== null;
$classes = [
+22 -13
View File
@@ -86,7 +86,7 @@ public function elementId(mixed $value): ?int
return is_int($id) ? $id : null;
}
public function presentation(mixed $value): ?WebsitePresentation
public function presentation(mixed $value, ?ContentElement $loaded = null): ?WebsitePresentation
{
$id = $this->elementId($value);
@@ -95,7 +95,8 @@ public function presentation(mixed $value): ?WebsitePresentation
}
if (! array_key_exists($id, $this->presentations)) {
$this->presentations[$id] = $this->media->present($id) ?? false;
// Ein schon geladenes Medium wird weitergereicht (kein zweiter Zugriff je Eintrag in der Auswahl).
$this->presentations[$id] = $this->media->present($loaded?->getKey() === $id ? $loaded : $id) ?? false;
}
return $this->presentations[$id] ?: null;
@@ -105,12 +106,12 @@ public function presentation(mixed $value): ?WebsitePresentation
* Bildadresse für die Darstellung. Öffentlich nur freigegebene Medien (oder frühere CMS-Bilder ohne Zuordnung);
* in der Redaktionsvorschau zusätzlich das Vorschaubild eines nicht freigegebenen Mediums.
*/
public function url(mixed $value, bool $preview = false): ?string
public function url(mixed $value, bool $preview = false, ?int $width = null): ?string
{
$presentation = $this->presentation($value);
if ($presentation !== null) {
return $presentation->kind === 'bild' ? $presentation->url : null;
return $presentation->kind === 'bild' ? $presentation->urlForWidth($width) : null;
}
$id = $this->elementId($value);
@@ -122,7 +123,7 @@ public function url(mixed $value, bool $preview = false): ?string
$element = ContentElement::query()->find($id);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
$legacy = self::normalize($value);
@@ -134,6 +135,14 @@ public function url(mixed $value, bool $preview = false): ?string
return is_string($legacy) ? PublicMedia::url($legacy) : null;
}
/** `srcset` des freigegebenen Bildes (mehrere Breiten), sonst null. Für Hero, Bild mit Text, Karten. */
public function srcset(mixed $value): ?string
{
$presentation = $this->presentation($value);
return $presentation !== null && $presentation->kind === 'bild' ? $presentation->srcset : null;
}
/** Alternativtext: Angabe im Widget, sonst der Alternativtext des Mediums. */
public function alt(mixed $value, mixed $override = null): string
{
@@ -169,7 +178,7 @@ public function previewNotice(mixed $value, string $label = 'Das gewählte Bild'
*
* @return array{public: bool, state: string, title: string, note: string, thumb: ?string, manageUrl: ?string}|null
*/
public function status(mixed $value): ?array
public function status(mixed $value, ?ContentElement $loaded = null): ?array
{
$value = self::normalize($value);
@@ -194,16 +203,16 @@ public function status(mixed $value): ?array
];
}
$element = ContentElement::query()->with('editorialContentKind')->find($id);
$element = $loaded?->getKey() === $id ? $loaded : ContentElement::query()->with('editorialContentKind')->find($id);
if ($element === null) {
return ['public' => false, 'state' => 'missing', 'title' => 'Medium '.$id, 'note' => 'Das Medium gibt es nicht mehr.', 'thumb' => null, 'manageUrl' => null];
}
$title = (string) ($element->display_title ?: $element->working_title);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
$manageUrl = ContentElementResource::getUrl('view', ['record' => $element]);
$public = $this->presentation($id) !== null;
$public = $this->presentation($id, $element) !== null;
$note = match (true) {
$public => 'Für die Website freigegeben.',
@@ -292,7 +301,7 @@ public function options(?string $search = null, int $limit = 60): array
$options = [];
foreach ($elements as $element) {
if (self::isSelectable($element)) {
$options[$element->id] = $this->optionHtml($element->id);
$options[$element->id] = $this->optionHtml($element->id, $element);
}
}
@@ -300,9 +309,9 @@ public function options(?string $search = null, int $limit = 60): array
}
/** HTML-Bezeichnung einer Option oder des gewählten Werts (auch für frühere Pfade). */
public function optionHtml(mixed $value): ?string
public function optionHtml(mixed $value, ?ContentElement $loaded = null): ?string
{
$status = $this->status($value);
$status = $this->status($value, $loaded);
if ($status === null) {
return null;
@@ -315,7 +324,7 @@ public function optionHtml(mixed $value): ?string
default => ['warn', 'Website: nicht freigegeben'],
};
$thumb = $status['thumb'] !== null
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy">'
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy" decoding="async">'
: '<span class="luf-media-option-empty" aria-hidden="true"></span>';
return '<span class="luf-media-option">'.$thumb
@@ -302,6 +302,7 @@ public function resolve(array $widget, RenderContext $context): array
'linkLabel' => filled($item['link_label'] ?? null) ? $item['link_label'] : self::DEFAULT_LINK_LABEL,
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
'imageSrcset' => $images->srcset($item['image'] ?? null),
];
if ($context->preview && ($notice = $images->previewNotice($item['image'] ?? null, 'Das Bild der Karte „'.$item['title'].'“')) !== null) {
@@ -250,6 +250,7 @@ public function resolve(array $widget, RenderContext $context): array
return [
'video' => $video,
'imageUrl' => $images->url($image, $context->preview),
'imageSrcset' => $images->srcset($image),
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'actions' => $actions,
@@ -329,6 +329,7 @@ public function resolve(array $widget, RenderContext $context): array
return [
'imageUrl' => $imageUrl,
'imageSrcset' => $imageUrl === null ? null : $images->srcset($image),
'imageAlt' => $imageAlt,
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'video' => $video,
@@ -130,7 +130,7 @@ protected function filmFieldData(?ContentElement $film): array
? route('content.website-frame', ['element' => $film])
: null,
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path) : null,
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path, 'mittel', $film->updated_at) : null,
'filmStartSecond' => $film instanceof ContentElement ? ($stills->thumbnailSecond($film) ?? '0') : '0',
];
}
@@ -349,6 +349,7 @@ public function resolve(array $widget, RenderContext $context): array
'clip' => $clip,
'cardStyle' => $subject?->style ?? $this->cardStyle(),
'imageUrl' => app(WebsiteImage::class)->url($imageRef, $context->preview),
'imageSrcset' => app(WebsiteImage::class)->srcset($imageRef),
'alt' => app(WebsiteImage::class)->alt($imageRef, $data['alt'] ?? null),
'imageNotice' => $context->preview ? app(WebsiteImage::class)->previewNotice($imageRef, 'Das Kartenbild') : null,
'focus' => PremiumFields::focus($data, 66, 45),
@@ -65,7 +65,7 @@ protected function imageSourceFields(): array
'composition' => $composition,
'compositionTitle' => $composition instanceof Composition ? (string) ($composition->display_title ?: $composition->designation) : '',
'compositionThumbnailUrl' => $composition instanceof Composition && app(CompositionStill::class)->hasThumbnail($composition)
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path)
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at)
: null,
];
}),
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace App\Domain\Media;
use Illuminate\Contracts\Filesystem\Filesystem;
/**
* Größenstufen eines Bildes (docs/architektur/bildvarianten.md).
*
* Neben der Hauptdatei (`vorschau/element-12.jpg`, „voll“: bis 2400 px bei Bildern, 640 px sonst) liegen daneben
* kleinere JPEG-Fassungen, benannt nach der Hauptdatei (`element-12-klein.jpg`). Es gibt keine Spalte dafür: Die Hauptdatei
* bleibt `thumbnail_path`, die Fassungen folgen der Namensregel. Fehlt eine Fassung, gilt die Hauptdatei (kein Bruch bei
* Bestand, der noch nicht abgeleitet ist).
*
* Verwaltungsoberfläche (Disk `media_derived`):
* - `klein` 360 px: Auswahl, Listen, Karten (Anzeige bis etwa 180 px, doppelt für scharfe Bildschirme)
* - `mittel` 960 px: Detailansicht, Vorschau, Titelbild im Editor
* - voll: die Hauptdatei
*
* Website (Disk `media_public`, `website/{id}/datei-{breite}.jpg`): Breiten {@see self::PUBLIC_WIDTHS}, daneben die
* Hauptdatei `datei.jpg`. Eine Fassung entsteht nur, wenn die Quelle breiter ist (nie vergrößern).
*
* Geschrieben wird nur in der Warteschlange; der Web-Prozess liest.
*/
class ImageVariants
{
/** @var array<string, int> */
public const SIZES = ['klein' => 360, 'mittel' => 960];
/** @var list<int> */
public const PUBLIC_WIDTHS = [640, 1280, 1920];
private const QUALITY = 80;
public static function isSize(mixed $size): bool
{
return is_string($size) && array_key_exists($size, self::SIZES);
}
public static function isPublicWidth(mixed $width): bool
{
return is_int($width) && in_array($width, self::PUBLIC_WIDTHS, true);
}
/** `vorschau/element-12.jpg` → `vorschau/element-12-klein.jpg` */
public static function path(string $base, string $size): string
{
$extension = pathinfo($base, PATHINFO_EXTENSION);
$stem = $extension === '' ? $base : substr($base, 0, -(strlen($extension) + 1));
return $stem.'-'.$size.'.jpg';
}
/** `website/12/datei.jpg` → `website/12/datei-640.jpg` */
public static function publicPath(string $base, int $width): string
{
return self::path($base, (string) $width);
}
/**
* Pfad, der für die Größe ausgeliefert wird: die Fassung, wenn es sie gibt, sonst die Hauptdatei.
*/
public static function resolve(Filesystem $disk, string $base, ?string $size): string
{
if (! self::isSize($size)) {
return $base;
}
$variant = self::path($base, (string) $size);
return $disk->exists($variant) ? $variant : $base;
}
/**
* Legt die Fassungen der Verwaltungsoberfläche zur Hauptdatei an (Warteschlange). Ist die Quelle nicht breiter als die
* Stufe, entfällt die Fassung, und eine ältere wird entfernt.
*
* @return list<string> Pfade der geschriebenen Fassungen
*/
public static function generate(Filesystem $disk, string $base): array
{
$targets = [];
foreach (self::SIZES as $name => $width) {
$targets[self::path($base, $name)] = $width;
}
return self::write($disk, $disk, $base, $targets);
}
/**
* Legt die Breiten für die Website neben der öffentlichen Hauptdatei an. Nur JPEG-Quellen: andere Formate (PNG, GIF,
* WebP) können Transparenz tragen, die ein JPEG nicht hält; sie bleiben unverändert.
*
* @return list<string> Pfade der geschriebenen Fassungen
*/
public static function generatePublic(Filesystem $source, Filesystem $target, string $sourcePath, string $publicBase): array
{
if (! in_array(strtolower(pathinfo($publicBase, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return [];
}
$targets = [];
foreach (self::PUBLIC_WIDTHS as $width) {
$targets[self::publicPath($publicBase, $width)] = $width;
}
return self::write($source, $target, $sourcePath, $targets);
}
/** Entfernt alle Fassungen zu einer öffentlichen Hauptdatei (Rücknahme, Ersatz). */
public static function deletePublic(Filesystem $disk, string $publicBase): void
{
foreach (self::PUBLIC_WIDTHS as $width) {
$disk->delete(self::publicPath($publicBase, $width));
}
}
/**
* @param array<string, int> $targets Zielpfad → Breite
* @return list<string>
*/
private static function write(Filesystem $source, Filesystem $target, string $sourcePath, array $targets): array
{
if (! $source->exists($sourcePath)) {
return [];
}
$bytes = $source->get($sourcePath);
$image = is_string($bytes) && $bytes !== '' ? @imagecreatefromstring($bytes) : false;
if ($image === false) {
return [];
}
$width = imagesx($image);
$height = imagesy($image);
$written = [];
foreach ($targets as $path => $targetWidth) {
if ($width <= $targetWidth) {
$target->delete($path);
continue;
}
$encoded = self::scaled($image, $width, $height, $targetWidth);
if ($encoded !== null && $target->put($path, $encoded)) {
$written[] = $path;
}
}
imagedestroy($image);
return $written;
}
private static function scaled(\GdImage $image, int $width, int $height, int $targetWidth): ?string
{
$targetHeight = (int) max(1, round($height * ($targetWidth / max(1, $width))));
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
imagefill($canvas, 0, 0, (int) imagecolorallocate($canvas, 255, 255, 255));
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
imageinterlace($canvas, true);
ob_start();
imagejpeg($canvas, null, self::QUALITY);
$bytes = ob_get_clean();
imagedestroy($canvas);
return is_string($bytes) && $bytes !== '' ? $bytes : null;
}
}
+2
View File
@@ -89,6 +89,7 @@ public function place(ContentElement $element, string $incoming): void
}
if ($element->output_class === 'bild') {
ImageVariants::generate(Storage::disk('media_derived'), $target);
$element->thumbnail_path = $target;
$element->thumbnail_source = 'eigen';
} else {
@@ -97,6 +98,7 @@ public function place(ContentElement $element, string $incoming): void
$element->thumbnail_error = null;
$element->save();
$element->touch();
Storage::disk('cms_incoming')->delete($incoming);
}
+6
View File
@@ -335,6 +335,7 @@ private function frame(ContentElement $element, ContentElementVersion $version,
return;
}
ImageVariants::generate($disk, $target);
$element->thumbnail_path = $target;
if (! filled($element->thumbnail_alt)) {
$element->thumbnail_alt = $element->working_title;
@@ -344,6 +345,7 @@ private function frame(ContentElement $element, ContentElementVersion $version,
$element->thumbnail_source = 'frame:'.$version->id.'@0';
}
$element->save();
$element->touch();
}
private function still(ContentElement|Composition $subject, Filesystem $disk, string $file, string $name): void
@@ -388,6 +390,7 @@ private function still(ContentElement|Composition $subject, Filesystem $disk, st
$path = 'vorschau/'.$name.'.jpg';
Storage::disk('media_derived')->put($path, $bytes);
ImageVariants::generate(Storage::disk('media_derived'), $path);
$subject->thumbnail_path = $path;
if (! filled($subject->thumbnail_alt)) {
@@ -396,6 +399,9 @@ private function still(ContentElement|Composition $subject, Filesystem $disk, st
$subject->thumbnail_error = null;
$subject->save();
// Die Adresse trägt die Version (updated_at) und wird dauerhaft zwischengespeichert: Ein neu abgeleitetes Bild
// unter gleichem Pfad muss die Version ändern, auch wenn sonst nichts an der Zeile anders ist.
$subject->touch();
}
private function rememberElement(ContentElement $element, string $source): void
+25 -2
View File
@@ -2,14 +2,37 @@
namespace App\Domain\Media;
use Carbon\CarbonInterface;
class ThumbnailRef
{
public static function url(string $route, string $kind, int $id, mixed $path): ?string
/**
* Adresse eines Vorschaubildes.
*
* @param string|null $size `klein` (Auswahl, Listen, Karten), `mittel` (Detail, Vorschau) oder null für die volle Datei
* @param CarbonInterface|int|string|null $version Stand des Bildes (zum Beispiel `updated_at`). Mit Version darf der Browser das Bild
* dauerhaft behalten; ohne Version fragt er jedes Mal nach (ETag).
*/
public static function url(string $route, string $kind, int $id, mixed $path, ?string $size = null, CarbonInterface|int|string|null $version = null): ?string
{
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
return null;
}
return route($route, ['kind' => $kind, 'subject' => $id]);
$query = [];
if (ImageVariants::isSize($size)) {
$query['g'] = $size;
}
if ($version instanceof CarbonInterface) {
$version = $version->getTimestamp();
}
if ($version !== null && $version !== '') {
$query['v'] = $version;
}
return route($route, ['kind' => $kind, 'subject' => $id] + $query);
}
}
+28 -1
View File
@@ -45,10 +45,37 @@ public function present(ContentElement|int $element): ?WebsitePresentation
'audio' => 'audio',
default => 'bild',
},
url: route('website.media', $element),
// Bilder tragen den Zeitpunkt der Freigabe in der Adresse (dauerhaft zwischenspeicherbar); Film und Hörstück bleiben unverändert.
url: $element->output_class === 'film' || $element->output_class === 'audio'
? route('website.media', $element)
: route('website.media', ['element' => $element, 'v' => $element->website_released_at->getTimestamp()]),
srcset: $this->srcset($element, $path),
);
}
/**
* `srcset` eines freigegebenen JPEG-Bildes: die Breiten aus {@see ImageVariants::PUBLIC_WIDTHS} und die volle Datei.
* Fehlt eine Breite noch (Bestand), liefert die Adresse die volle Datei und stößt das Anlegen an; die Beschreibung bleibt
* dann ungenau, das Bild aber richtig. PNG, GIF und WebP bleiben ohne Fassungen (Transparenz).
*/
private function srcset(ContentElement $element, string $path): ?string
{
if ($element->output_class !== 'bild' || ! in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return null;
}
$version = $element->website_released_at->getTimestamp();
$entries = [];
foreach (ImageVariants::PUBLIC_WIDTHS as $width) {
$entries[] = route('website.media', ['element' => $element, 'w' => $width, 'v' => $version]).' '.$width.'w';
}
$entries[] = route('website.media', ['element' => $element, 'v' => $version]).' 2400w';
return implode(', ', $entries);
}
/**
* Slideshow: freigegebene Medien in der angegebenen Reihenfolge. Nicht freigegebene Einträge entfallen.
*
+14
View File
@@ -15,5 +15,19 @@ public function __construct(
public readonly ?string $credit,
public readonly string $kind,
public readonly string $url,
/** Bildadressen in mehreren Breiten für `srcset` (nur Bilder, deren Breiten die Warteschlange anlegt), sonst null. */
public readonly ?string $srcset = null,
) {}
/**
* Adresse in einer der Breiten aus {@see ImageVariants::PUBLIC_WIDTHS}; ohne Breiten (oder bei anderer Breite) die volle Datei.
*/
public function urlForWidth(?int $width): string
{
if ($width === null || $this->srcset === null || ! ImageVariants::isPublicWidth($width)) {
return $this->url;
}
return $this->url.(str_contains($this->url, '?') ? '&' : '?').'w='.$width;
}
}
@@ -119,7 +119,7 @@ public function form(Schema $schema): Schema
Placeholder::make('thumbnail_current')->label('Aktuelles Vorschaubild')->content(function (): HtmlString {
/** @var ContentElement $element */
$element = $this->getRecord();
$url = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$url = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
$caption = match ($element->thumbnail_source) {
'eigen' => 'Eigenes Vorschaubild.',
'datei' => 'Vorschaubild aus der Datei des Mediums.',
@@ -589,7 +589,7 @@ private function viewerData(): array
&& $element->output_class === 'text'
&& $shown->status !== ContentVersionStatus::Gesperrt,
'bodyCommitted' => $committed,
'pictureUrl' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'pictureUrl' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at),
'pictureCaption' => $this->pictureCaption($element),
];
}
@@ -1076,7 +1076,7 @@ public function previewHtml(): string
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
'hide_status' => true,
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at),
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
],
]);
@@ -108,7 +108,7 @@ protected function catalogRows(): array
'titel' => $title,
'meta' => 'Lizenzartikel · '.$article->code.(filled($article->product_line) ? ' · '.$article->product_line : ''),
'text' => trim((string) ($article->teaser ?: $article->summary)),
'bild' => $cover !== null ? ThumbnailRef::url('editorial.card', 'element', $cover->id, $cover->thumbnail_path) : null,
'bild' => $cover !== null ? ThumbnailRef::url('editorial.card', 'element', $cover->id, $cover->thumbnail_path, 'klein', $cover->updated_at) : null,
'symbol' => 'dokument',
'url' => $url,
'chips' => $chips,
+12 -14
View File
@@ -18,12 +18,14 @@
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Media\ThumbnailRef;
use App\Filament\Resources\Combinations\CombinationResource;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Resources\Courses\CourseResource;
use App\Filament\Resources\Documents\DocumentResource;
use App\Filament\Resources\Exercises\ExerciseResource;
use App\Filament\Resources\Practices\PracticeResource;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
@@ -115,7 +117,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'usage_note' => (string) ($element->usage_note ?? ''),
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
'image' => $this->cardUrl('element', $element->id, $element->thumbnail_path),
'image' => $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at),
'version_label' => match ($version->status) {
ContentVersionStatus::Entwurf => 'Entwurf',
ContentVersionStatus::Gesperrt => 'deaktiviert',
@@ -163,7 +165,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'kind' => $kind,
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at),
'version_label' => $version->status === ContentVersionStatus::Gesperrt
? 'deaktiviert'
: 'Fassung '.$version->number,
@@ -198,7 +200,7 @@ private function draftCompositionRow(int $compositionId, int $exceptCompositionI
'kind' => $kind,
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at),
'version_label' => 'Entwurf',
'identity' => 'zusammenstellung:'.$composition->id,
'open_url' => route('editorial.draft-preview', ['composition' => $composition]),
@@ -524,7 +526,7 @@ private function rowForPresentationMedium(int $id): ?array
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
'image' => $element->output_class === 'bild'
? $this->cardUrl('element', $element->id, $element->thumbnail_path)
? $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at)
: null,
'version_label' => 'Ohne Inhaltsfassung',
'committed' => false,
@@ -548,13 +550,9 @@ public function tone(string $outputClass, string $kindLabel): string
};
}
public function cardUrl(string $kind, int $id, ?string $path): ?string
public function cardUrl(string $kind, int $id, ?string $path, ?string $size = null, CarbonInterface|int|string|null $version = null): ?string
{
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
return null;
}
return route('editorial.card', ['kind' => $kind, 'subject' => $id]);
return ThumbnailRef::url('editorial.card', $kind, $id, $path, $size, $version);
}
/**
@@ -891,7 +889,7 @@ public function filmPictures(array $members): array
continue;
}
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path);
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
if ($image === null || isset($pictures[$element->id])) {
continue;
@@ -933,7 +931,7 @@ public function mediaPictures(string $query): array
->limit(12)
->get()
->map(function (ContentElement $element): ?array {
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path);
$image = $this->cardUrl('element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at);
if ($image === null) {
return null;
@@ -957,7 +955,7 @@ public function mediaPictures(string $query): array
*/
public function cover(Composition $composition, array $members): array
{
$own = $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path);
$own = $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path, 'mittel', $composition->updated_at);
if ($own !== null) {
return ['url' => $own, 'note' => null, 'own' => true];
@@ -970,7 +968,7 @@ public function cover(Composition $composition, array $members): array
}
return [
'url' => $this->cardUrl($picture['kind'], $picture['subject'], 'vorschau/gesetzt'),
'url' => $this->cardUrl($picture['kind'], $picture['subject'], 'vorschau/gesetzt', 'mittel'),
'note' => $picture['note'],
'own' => false,
];
+1 -1
View File
@@ -553,7 +553,7 @@ private function card(ContentElement $element, array $portrait, array $uses, arr
'description' => $description === '' ? null : $description,
'usageNote' => $usageNote === '' ? null : $usageNote,
'licenseNote' => $licenseNote === '' ? null : $licenseNote,
'image' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'image' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at),
'imageAlt' => trim((string) ($element->thumbnail_alt ?: $element->working_title)),
'imageNote' => $this->imageNote($element),
'presentation' => $this->isPresentationMedium($element, $portrait['versionCount']),
@@ -0,0 +1,62 @@
<?php
namespace App\Http\Controllers\Concerns;
use App\Domain\Media\ImageVariants;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
/**
* Liefert ein Bild einer Disk mit Zwischenspeicherung aus (docs/architektur/bildvarianten.md).
*
* Mit Versionsangabe in der Adresse (`?v=`) ändert sich die Adresse, sobald sich das Bild ändert; der Browser darf es
* dann ein Jahr behalten. Ohne Version bleibt es bei einer Rückfrage mit ETag und Last-Modified (304 ohne Inhalt).
*/
trait ServesImages
{
/**
* @param 'public'|'private' $scope `private` für alles, was eine Anmeldung oder Berechtigung voraussetzt
*/
protected function respondWithImage(Request $request, string $diskName, string $path, string $scope = 'private', bool $versioned = false): Response
{
$disk = Storage::disk($diskName);
$headers = [
'Content-Disposition' => 'inline',
'X-Content-Type-Options' => 'nosniff',
];
$response = $disk->response($path, null, $headers);
$modified = (int) $disk->lastModified($path);
$size = (int) $disk->size($path);
$response->setEtag(md5($path.'|'.$modified.'|'.$size));
$response->setLastModified(Carbon::createFromTimestamp($modified));
if ($versioned) {
$response->headers->set('Cache-Control', $scope.', max-age=31536000, immutable');
} else {
$response->headers->set('Cache-Control', $scope.', max-age=0, must-revalidate');
}
$response->isNotModified($request);
return $response;
}
/** Pfad der angefragten Größe (`?g=klein|mittel`), sonst die Hauptdatei. */
protected function imagePathFor(Request $request, string $diskName, string $path): string
{
$size = $request->query('g');
return ImageVariants::resolve(Storage::disk($diskName), $path, is_string($size) ? $size : null);
}
/** `?v=` ist da und eine einfache Zahl (Zeitstempel). */
protected function hasImageVersion(Request $request): bool
{
$version = $request->query('v');
return is_string($version) && preg_match('/^[0-9]{1,12}$/', $version) === 1;
}
}
@@ -12,15 +12,18 @@
use App\Domain\Identity\StaffRole;
use App\Domain\Media\ThumbnailDeriver;
use App\Filament\Support\EditorialCatalog;
use App\Http\Controllers\Concerns\ServesImages;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class EditorialPreviewController extends Controller
{
use ServesImages;
public function show(Composition $composition, ?CompositionVersion $version = null): View
{
$this->authorizeStaff();
@@ -104,7 +107,7 @@ public function draft(Composition $composition): View
);
}
public function card(string $kind, int $subject): StreamedResponse
public function card(Request $request, string $kind, int $subject): SymfonyResponse
{
$this->authorizeStaff();
abort_unless(in_array($kind, ['element', 'komposition'], true), 404);
@@ -116,7 +119,13 @@ public function card(string $kind, int $subject): StreamedResponse
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
return $this->respondWithImage(
$request,
'media_derived',
$this->imagePathFor($request, 'media_derived', $path),
'private',
$this->hasImageVersion($request),
);
}
/**
@@ -20,6 +20,7 @@
use App\Domain\Media\FilmPlayback;
use App\Domain\Media\HlsPlaylist;
use App\Domain\Media\MediaRendition;
use App\Http\Controllers\Concerns\ServesImages;
use App\Http\Controllers\Controller;
use App\Http\CourseOutline;
use App\Http\LibraryCatalog;
@@ -32,10 +33,13 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class LibraryController extends Controller
{
use ServesImages;
/** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */
public const TYPES = [
'programm' => 'Programme',
@@ -361,7 +365,7 @@ public function rendition(
return $disk->response($datei, basename($datei), ['Content-Disposition' => 'inline']);
}
public function thumbnail(Request $request, string $kind, int $subject): StreamedResponse
public function thumbnail(Request $request, string $kind, int $subject): SymfonyResponse
{
abort_unless(in_array($kind, ['komposition', 'element'], true), 404);
$model = $kind === 'komposition'
@@ -373,7 +377,13 @@ public function thumbnail(Request $request, string $kind, int $subject): Streame
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
return $this->respondWithImage(
$request,
'media_derived',
$this->imagePathFor($request, 'media_derived', $path),
'private',
$this->hasImageVersion($request),
);
}
/**
@@ -3,16 +3,22 @@
namespace App\Http\Controllers;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use App\Domain\Media\WebsiteMedia;
use App\Http\Controllers\Concerns\ServesByteRanges;
use App\Http\Controllers\Concerns\ServesImages;
use App\Jobs\DeriveWebsiteVariants;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
class WebsiteMediaController extends Controller
{
use ServesByteRanges;
use ServesImages;
public function show(Request $request, ContentElement $element, WebsiteMedia $media): StreamedResponse
public function show(Request $request, ContentElement $element, WebsiteMedia $media): Response
{
$presentation = $media->present($element);
abort_if($presentation === null, 404);
@@ -20,6 +26,45 @@ public function show(Request $request, ContentElement $element, WebsiteMedia $me
$path = $element->website_public_path;
abort_if(! is_string($path), 404);
return $this->respondWithRanges($request, 'media_public', $path, $presentation->kind !== 'bild');
if ($presentation->kind !== 'bild') {
return $this->respondWithRanges($request, 'media_public', $path, true);
}
$path = $this->widthPath($request, $element, $path);
// Die Adresse trägt den Zeitpunkt der Freigabe. Gilt er noch, ändert sich der Inhalt unter dieser Adresse nicht mehr
// (eine neue Freigabe liefert eine neue Adresse); eine veraltete Adresse wird nur kurz vorgehalten und geprüft.
$current = $this->hasImageVersion($request)
&& (int) $request->query('v') === $element->website_released_at?->getTimestamp();
return $this->respondWithImage($request, 'media_public', $path, 'public', $current);
}
/**
* Die angefragte Breite (`?w=640|1280|1920`), sonst die volle Datei. Fehlt die Breite noch, geht die volle Datei hinaus,
* und die Warteschlange legt die Breiten an (höchstens einmal je Stunde und Bild; der Web-Prozess schreibt nie).
*/
private function widthPath(Request $request, ContentElement $element, string $path): string
{
$width = $request->query('w');
if (! is_string($width) || preg_match('/^[0-9]{3,4}$/', $width) !== 1 || ! ImageVariants::isPublicWidth((int) $width)) {
return $path;
}
if (! in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), ['jpg', 'jpeg'], true)) {
return $path;
}
$variant = ImageVariants::publicPath($path, (int) $width);
if (Storage::disk('media_public')->exists($variant)) {
return $variant;
}
if (Cache::add('bildvarianten.website.'.$element->id, true, now()->addHour())) {
DeriveWebsiteVariants::dispatch($element->id);
}
return $path;
}
}
+3 -2
View File
@@ -92,6 +92,7 @@ public function index(User $user): array
'image_url' => $picture === null ? null : route('member.thumbnail', [
'kind' => $picture['kind'],
'subject' => $picture['subject'],
'g' => 'mittel',
]),
'url' => route('member.program', $composition),
];
@@ -113,7 +114,7 @@ public function index(User $user): array
: ($element?->id !== null ? 'element-'.$element->id : 'artikel-'.$article->id);
$subject = $element ?? $composition ?? $article;
$text = $element !== null ? $this->text($element) : null;
$imageUrl = $element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
$imageUrl = $element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
$media[$key] = ($media[$key] ?? []) + [
'used_in' => [],
'versions' => [],
@@ -376,7 +377,7 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
}
if ($view !== null && $element !== null) {
$poster = ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
$poster = ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'mittel', $element->updated_at);
}
}
+2 -2
View File
@@ -129,8 +129,8 @@ private function entry(User $user, Grant $grant): array
if ($grant->status === GrantStatus::Aktiv) {
$imageUrl = $composition !== null
? ThumbnailRef::url('member.thumbnail', 'komposition', $composition->id, $composition->thumbnail_path)
: ($element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path));
? ThumbnailRef::url('member.thumbnail', 'komposition', $composition->id, $composition->thumbnail_path, 'klein', $composition->updated_at)
: ($element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path, 'klein', $element->updated_at));
}
$title = $composition !== null
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Jobs;
use App\Domain\Media\ImageVariants;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
/**
* Legt die kleineren Fassungen (klein, mittel) zu einem vorhandenen Vorschaubild an. Läuft nur in der Warteschlange, die in
* derived/ schreiben darf. Auslöser: Bestand ohne Fassungen, den die Auslieferung oder der Befehl `media:varianten` findet.
*/
class DeriveImageVariants implements ShouldQueue
{
use Queueable;
public function __construct(public readonly string $path) {}
public function handle(): void
{
if (preg_match('#^vorschau/[A-Za-z0-9._\-/]+$#', $this->path) !== 1 || str_contains($this->path, '..')) {
return;
}
ImageVariants::generate(Storage::disk('media_derived'), $this->path);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Jobs;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ImageVariants;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
/**
* Legt die Breiten für die Website zu einem bereits freigegebenen Bild an (Bestand von vor den Bildfassungen). Verändert
* weder die Freigabe noch den Prüfverlauf; die Freigabe selbst schreibt die Fassungen in {@see PublishWebsiteMedia}.
*/
class DeriveWebsiteVariants implements ShouldQueue
{
use Queueable;
public function __construct(public readonly int $elementId) {}
public function handle(): void
{
$element = ContentElement::query()->find($this->elementId);
if (! $element instanceof ContentElement || $element->output_class !== 'bild' || $element->website_released_at === null) {
return;
}
$path = $element->website_public_path;
if (! is_string($path) || preg_match('#^website/'.$element->id.'/datei\.[a-z0-9]+$#', $path) !== 1) {
return;
}
$disk = Storage::disk('media_public');
ImageVariants::generatePublic($disk, $disk, $path, $path);
}
}
+9
View File
@@ -4,6 +4,7 @@
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\IdentityChange;
use App\Domain\Media\ImageVariants;
use App\Domain\Media\WebsiteRelease;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
@@ -51,6 +52,12 @@ public function handle(WebsiteRelease $release): void
if (is_string($previous) && $previous !== $target && str_starts_with($previous, 'website/'.$element->id.'/')) {
Storage::disk('media_public')->delete($previous);
ImageVariants::deletePublic(Storage::disk('media_public'), $previous);
}
if ($element->output_class === 'bild') {
// Breiten für die Website neben der Hauptdatei; ohne sie liefert die Website immer die volle Datei.
ImageVariants::generatePublic(Storage::disk('media_derived'), Storage::disk('media_public'), $derived, $target);
}
$this->mark($element, $element->website_released_at?->toIso8601String(), now()->toIso8601String());
@@ -69,6 +76,8 @@ private function deletePublicFile(ContentElement $element): void
}
Storage::disk('media_public')->delete($path);
// Auch die Breiten: Sonst bliebe ein zurückgenommenes Bild unter dem Namen einer Fassung erreichbar.
ImageVariants::deletePublic(Storage::disk('media_public'), $path);
}
private function mark(ContentElement $element, ?string $before, ?string $after): void