Leite Vorschaubilder und Filmstufen geschuetzt ab
Deploy Test / test (push) Successful in 2m28s
Deploy Test / deploy (push) Failing after 14s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-16 09:40:59 +01:00
1 parent d6ff881e4e
commit c997eb500c
32 files changed
+979 -68

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ ARG PHP_VERSION=8.4
# ---- Basis: PHP mit den Erweiterungen für Laravel und Filament -------------------------------
FROM php:${PHP_VERSION}-fpm-alpine AS base
RUN apk add --no-cache icu-libs libzip libpng libjpeg-turbo freetype libpq oniguruma su-exec \
RUN apk add --no-cache icu-libs libzip libpng libjpeg-turbo freetype libpq oniguruma su-exec ffmpeg \
&& apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev postgresql-dev oniguruma-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j"$(nproc)" pdo_pgsql intl zip gd bcmath opcache pcntl exif \
+32
View File
@@ -44,6 +44,38 @@ public function explanation(): string
};
}
public function deskLabel(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombination',
self::Uebung => 'Modul',
self::Kurs => 'Programm',
};
}
public function deskExplanation(): string
{
return match ($this) {
self::Kombination => $this->explanation(),
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
};
}
/**
* @return array<string, string>
*/
public static function deskOptions(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->deskLabel();
}
return $options;
}
/**
* @return array<string, string>
*/
+3
View File
@@ -13,6 +13,9 @@ class MediaDelivery extends Model
'content_element_version_id',
'action',
'format',
'copy_id',
'checksum',
'marking',
'delivered_at',
];
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Domain\Media;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\MediaDelivery;
class DeliveryLog
{
public function write(
Grant $grant,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
string $format,
?string $checksum,
string $marking,
): MediaDelivery {
return MediaDelivery::query()->create([
'grant_id' => $grant->id,
'license_article_id' => $article->id,
'article_release_id' => $release->id,
'content_element_version_id' => $version->id,
'action' => $action,
'format' => $format,
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
'checksum' => $checksum,
'marking' => $marking,
'delivered_at' => now(),
]);
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Domain\Media;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
class FfmpegFilmTranscoder implements FilmTranscoder
{
public function available(): bool
{
return (new ExecutableFinder)->find('ffmpeg') !== null;
}
public function derive(int $versionId, string $sourceRelative): array
{
$binary = (new ExecutableFinder)->find('ffmpeg');
if ($binary === null) {
return [];
}
$disk = Storage::disk('media_derived');
$source = $disk->path($sourceRelative);
$base = 'ableitungen/'.$versionId;
$rows = [];
foreach ([480, 720, 1080] as $height) {
$directory = $base.'/'.$height;
$disk->makeDirectory($directory);
$playlist = $disk->path($directory.'/index.m3u8');
$segment = $disk->path($directory.'/segment_%03d.m4s');
$process = new Process([
$binary,
'-y',
'-i',
$source,
'-vf',
'scale=-2:'.$height,
'-c:v',
'libx264',
'-preset',
'veryfast',
'-crf',
'23',
'-c:a',
'aac',
'-hls_time',
'6',
'-hls_playlist_type',
'vod',
'-hls_segment_filename',
$segment,
$playlist,
]);
$process->setTimeout(3600);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Die Qualitätsstufe '.$height.' ließ sich nicht ableiten.');
}
$rows[] = [
'role' => 'variant',
'label' => (string) $height,
'path' => $directory.'/index.m3u8',
];
}
$master = "#EXTM3U\n#EXT-X-VERSION:3\n"
."#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=854x480\n480/index.m3u8\n"
."#EXT-X-STREAM-INF:BANDWIDTH=2500000,RESOLUTION=1280x720\n720/index.m3u8\n"
."#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080\n1080/index.m3u8\n";
$disk->put($base.'/master.m3u8', $master);
$rows[] = ['role' => 'master', 'label' => 'master', 'path' => $base.'/master.m3u8'];
return $rows;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Domain\Media;
interface FilmTranscoder
{
public function available(): bool;
/**
* @return list<array{role: string, label: string, path: string}>
*/
public function derive(int $versionId, string $sourceRelative): array;
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Domain\Media;
class HlsPlaylist
{
public function rewrite(string $playlist, string $playlistPath, callable $sign): string
{
$directory = str_replace('\\', '/', dirname($playlistPath));
$lines = preg_split("/\r\n|\n|\r/", $playlist) ?: [];
$rewritten = [];
foreach ($lines as $line) {
$value = trim($line);
if ($value === '' || str_starts_with($value, '#')) {
$rewritten[] = $line;
continue;
}
$target = str_starts_with($value, 'ableitungen/')
? $value
: ($directory === '.' ? $value : $directory.'/'.$value);
$rewritten[] = $sign($target);
}
return implode("\n", $rewritten)."\n";
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Domain\Media;
use Illuminate\Database\Eloquent\Model;
class MediaRendition extends Model
{
protected $fillable = [
'content_element_version_id',
'role',
'label',
'path',
];
public static function masterPath(int $versionId): ?string
{
$path = static::query()
->where('content_element_version_id', $versionId)
->where('role', 'master')
->value('path');
return is_string($path) && $path !== '' ? $path : null;
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Domain\Media;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
class ThumbnailDeriver
{
public function forElement(ContentElement $element): void
{
$version = $element->versions()->orderByDesc('number')->first();
$file = is_array($version?->metadata) ? ($version->metadata['file'] ?? null) : null;
if (! $version instanceof ContentElementVersion || ! is_string($file) || $file === '') {
$this->fail($element, 'Für dieses Medium liegt noch keine Datei vor.');
return;
}
if (in_array($element->output_class, ['film', 'audio'], true)) {
$this->frame($element, $file);
return;
}
$this->still($element, Storage::disk('media_derived'), $file, 'element-'.$element->id);
}
public function forCompositionUpload(Composition $composition, string $incoming): void
{
if (! str_starts_with($incoming, 'vorschau/') || str_contains($incoming, '..')) {
$this->failComposition($composition, 'Das Vorschaubild wurde nicht übernommen.');
return;
}
$this->still($composition, Storage::disk('cms_incoming'), $incoming, 'komposition-'.$composition->id);
}
private function frame(ContentElement $element, string $file): void
{
$binary = (new ExecutableFinder)->find('ffmpeg');
$disk = Storage::disk('media_derived');
if ($binary === null || ! $disk->exists($file)) {
$this->fail($element, 'Für dieses Medium liegt noch kein abgeleitetes Vorschaubild vor.');
return;
}
$target = 'vorschau/element-'.$element->id.'.jpg';
$disk->makeDirectory('vorschau');
$process = new Process([
$binary,
'-y',
'-ss',
'0',
'-i',
$disk->path($file),
'-frames:v',
'1',
$disk->path($target),
]);
$process->setTimeout(120);
$process->run();
if (! $process->isSuccessful() || ! $disk->exists($target)) {
$this->fail($element, 'Aus der Filmdatei ließ sich kein Vorschaubild erzeugen.');
return;
}
$element->thumbnail_path = $target;
$element->thumbnail_alt = $element->working_title;
$element->thumbnail_error = null;
$element->save();
}
private function still(ContentElement|Composition $subject, Filesystem $disk, string $file, string $name): void
{
if (! $disk->exists($file)) {
$this->failSubject($subject, 'Die Bilddatei wurde nicht gefunden.');
return;
}
$image = @imagecreatefromstring($disk->get($file));
if ($image === false) {
$this->failSubject($subject, 'Die Bilddatei ließ sich nicht lesen.');
return;
}
$width = imagesx($image);
$height = imagesy($image);
$targetWidth = 640;
$targetHeight = (int) max(1, round($height * ($targetWidth / max(1, $width))));
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
ob_start();
imagejpeg($canvas, null, 82);
$bytes = ob_get_clean();
imagedestroy($image);
imagedestroy($canvas);
if (! is_string($bytes) || $bytes === '') {
$this->failSubject($subject, 'Das Vorschaubild ließ sich nicht schreiben.');
return;
}
$path = 'vorschau/'.$name.'.jpg';
Storage::disk('media_derived')->put($path, $bytes);
$subject->thumbnail_path = $path;
$subject->thumbnail_alt = $subject instanceof Composition ? $subject->designation : $subject->working_title;
$subject->thumbnail_error = null;
$subject->save();
}
private function fail(ContentElement $element, string $reason): void
{
$this->failSubject($element, $reason);
}
private function failComposition(Composition $composition, string $reason): void
{
$this->failSubject($composition, $reason);
}
private function failSubject(ContentElement|Composition $subject, string $reason): void
{
$subject->thumbnail_error = $reason;
$subject->save();
}
}
@@ -65,8 +65,8 @@ public function form(Schema $schema): Schema
Textarea::make('material_note')->label('Materialbedarf')->rows(2),
Placeholder::make('status')->label('Stand')->content(fn (): HtmlString => new HtmlString(e($this->statusText()))),
Placeholder::make('outline')->label('Gliederung der aktuellen Fassung')->content(fn (): HtmlString => new HtmlString($this->outlineHtml())),
Select::make('kind')->label('Art')->options(CompositionKind::options())->required()
->helperText('Übung, Kurs und fachliche Kombination sind verschiedene Zusammenstellungen. Die Art lässt sich hier ändern.'),
Select::make('kind')->label('Zusammenstellung')->options(CompositionKind::deskOptions())->required()
->helperText('Programm, Modul oder fachliche Kombination. Die Inhaltsart steuert die Bibliothek. Die gespeicherte Herkunft bleibt bestehen.'),
Select::make('editorial_content_kind_id')
->label('Inhaltsart')
->options(fn (): array => EditorialContentKind::selectOptions())
@@ -20,7 +20,7 @@ abstract protected function kind(): CompositionKind;
public function getSubheading(): string|Htmlable|null
{
return $this->kind()->explanation();
return $this->kind()->deskExplanation();
}
protected function getHeaderActions(): array
+179 -21
View File
@@ -4,6 +4,7 @@
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\EditorialDimension;
use App\Domain\Catalog\IdentityDimension;
@@ -11,12 +12,15 @@
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Entitlement\MediaDelivery;
use App\Domain\Media\DeliveryLog;
use App\Domain\Media\HlsPlaylist;
use App\Domain\Media\MediaRendition;
use App\Http\Controllers\Controller;
use App\Http\CourseOutline;
use App\Http\LibraryCatalog;
use App\Http\SignedLink;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -142,6 +146,7 @@ public function show(Request $request, LicenseArticle $article): View
? (int) $metadata['decision_seconds']
: null,
'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
'playback' => MediaRendition::masterPath($version->id) !== null ? 'hls' : 'file',
'pillars' => $version->element->pillars->pluck('name')->all(),
'url' => $decision->allowed
? SignedLink::temporary('member.media', now()->addMinutes(10), [
@@ -171,42 +176,90 @@ public function media(
ArticleRelease $release,
ContentElementVersion $version,
string $action,
): View|StreamedResponse {
): View|StreamedResponse|Response {
abort_unless(in_array($action, ['ansehen', 'streamen', 'laden'], true), 404);
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
abort_unless($decision->allowed, 403, $decision->reason);
if ($decision->grant !== null) {
MediaDelivery::query()->create([
'grant_id' => $decision->grant->id,
'license_article_id' => $article->id,
'article_release_id' => $release->id,
'content_element_version_id' => $version->id,
'action' => $action,
'format' => 'bestand',
'delivered_at' => now(),
]);
}
abort_unless($decision->allowed && $decision->grant !== null, 403, $decision->reason);
$version->loadMissing('element');
$master = $action === 'streamen' ? MediaRendition::masterPath($version->id) : null;
if (is_string($master)) {
return $this->playlist($request, $article, $release, $version, $decision->grant, $master);
}
$file = $version->metadata['file'] ?? null;
if (! is_string($file) || $file === '' || str_contains($file, '..')) {
$delivery = app(DeliveryLog::class)->write(
$decision->grant,
$article,
$release,
$version,
$action,
'text',
hash('sha256', (string) $version->body),
'k2',
);
return view('member.read', [
'article' => $article,
'version' => $version,
'license' => $decision->grant?->rights_snapshot['purpose'] ?? null,
'license' => $decision->grant->rights_snapshot['purpose'] ?? null,
'reader' => $request->user()->name,
'copy' => $delivery->copy_id,
]);
}
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($file), 404);
return $this->fileResponse($decision->grant, $article, $release, $version, $action, $file, 'bestand');
}
return $disk->response($file, basename($file), [
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
]);
public function rendition(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $datei,
): Response|StreamedResponse {
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
abort_unless($this->renditionBelongsTo($version->id, $datei), 404);
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, 'streamen');
abort_unless($decision->allowed && $decision->grant !== null, 403, $decision->reason);
if (str_ends_with($datei, '.m3u8')) {
return $this->playlist(
$request,
$article,
$release,
$version,
$decision->grant,
$datei,
str_ends_with($datei, 'master.m3u8'),
);
}
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($datei), 404);
return $disk->response($datei, basename($datei), ['Content-Disposition' => 'inline']);
}
public function thumbnail(Request $request, string $kind, int $subject): StreamedResponse
{
abort_unless(in_array($kind, ['komposition', 'element'], true), 404);
$model = $kind === 'komposition'
? Composition::query()->findOrFail($subject)
: ContentElement::query()->findOrFail($subject);
$path = $model->thumbnail_path;
abort_unless(is_string($path) && str_starts_with($path, 'vorschau/') && ! str_contains($path, '..'), 404);
abort_unless($this->maySeeThumbnail($request, $kind, $subject), 403);
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
return $disk->response($path);
}
/**
@@ -219,6 +272,111 @@ private function matches(array $card, string $query): bool
return str_contains($haystack, mb_strtolower($query));
}
private function playlist(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
Grant $grant,
string $path,
bool $record = true,
): Response {
abort_unless($this->renditionBelongsTo($version->id, $path), 404);
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($path), 404);
$rewritten = app(HlsPlaylist::class)->rewrite(
$disk->get($path),
$path,
fn (string $target): string => SignedLink::temporary('member.rendition', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'datei' => $target,
'reader' => $request->user()->id,
]),
);
$copy = '';
if ($record) {
$delivery = app(DeliveryLog::class)->write(
$grant,
$article,
$release,
$version,
'streamen',
'hls',
hash('sha256', $rewritten),
'k0',
);
$copy = $delivery->copy_id;
}
return response($rewritten, 200, [
'Content-Type' => 'application/vnd.apple.mpegurl',
'X-License-Copy' => $copy,
]);
}
private function fileResponse(
Grant $grant,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
string $file,
string $format,
): StreamedResponse {
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($file) && ! str_contains($file, '..'), 404);
$delivery = app(DeliveryLog::class)->write(
$grant,
$article,
$release,
$version,
$action,
$format,
hash_file('sha256', $disk->path($file)) ?: null,
'k0',
);
return $disk->response($file, basename($file), [
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
'X-License-Copy' => $delivery->copy_id,
]);
}
private function renditionBelongsTo(int $versionId, string $path): bool
{
$prefix = 'ableitungen/'.$versionId;
return ($path === $prefix || str_starts_with($path, $prefix.'/')) && ! str_contains($path, '..');
}
private function maySeeThumbnail(Request $request, string $kind, int $subject): bool
{
$grants = $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion', 'article.currentRelease.rootCompositionVersion')->get();
foreach ($grants as $grant) {
$release = $grant->article->currentRelease;
if ($release === null) {
continue;
}
if ($kind === 'komposition' && $release->rootCompositionVersion?->composition_id === $subject) {
return true;
}
if ($kind === 'element' && $release->contents->contains(
fn ($content): bool => $content->elementVersion?->content_element_id === $subject,
)) {
return true;
}
}
return false;
}
private function grantQuery(Request $request)
{
return Grant::query()
+5
View File
@@ -13,6 +13,7 @@
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Media\MediaRendition;
use App\Models\User;
use Illuminate\Support\Collection;
@@ -117,9 +118,12 @@ private function present(User $user, StructureNode $node): array
$view = null;
$download = null;
$playback = 'file';
if ($node->contentElementVersionId !== null) {
$view = $this->open($user, $node->contentElementVersionId, $this->viewAction($node->outputClass));
$download = $this->open($user, $node->contentElementVersionId, 'laden');
$playback = MediaRendition::masterPath($node->contentElementVersionId) !== null ? 'hls' : 'file';
}
return [
@@ -127,6 +131,7 @@ private function present(User $user, StructureNode $node): array
'title' => $node->title,
'kind' => $node->editorialKindLabel ?? $node->technicalKindLabel,
'output_class' => $node->outputClass,
'playback' => $playback,
'view_url' => $view,
'download_url' => $download,
'program_url' => $this->programUrl($node),
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Jobs;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Media\FilmTranscoder;
use App\Domain\Media\MediaRendition;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Throwable;
class DeriveFilmRenditions implements ShouldQueue
{
use Queueable;
public int $timeout = 3600;
public function __construct(public readonly int $versionId) {}
public function handle(FilmTranscoder $transcoder): void
{
$version = ContentElementVersion::query()->with('element')->find($this->versionId);
$file = is_array($version?->metadata) ? ($version->metadata['file'] ?? null) : null;
if ($version === null || $version->element->output_class !== 'film' || ! is_string($file) || $file === '') {
return;
}
if (! $transcoder->available()) {
return;
}
try {
$rows = $transcoder->derive($version->id, $file);
} catch (Throwable) {
return;
}
foreach ($rows as $row) {
MediaRendition::query()->updateOrCreate(
[
'content_element_version_id' => $version->id,
'label' => $row['label'],
],
[
'role' => $row['role'],
'path' => $row['path'],
],
);
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Jobs;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\ThumbnailDeriver;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class DeriveThumbnail implements ShouldQueue
{
use Queueable;
public function __construct(
public readonly string $subject,
public readonly int $subjectId,
public readonly ?string $incoming = null,
) {}
public function handle(ThumbnailDeriver $deriver): void
{
if ($this->subject === 'komposition') {
$composition = Composition::query()->find($this->subjectId);
if ($composition !== null && is_string($this->incoming)) {
$deriver->forCompositionUpload($composition, $this->incoming);
}
return;
}
$element = ContentElement::query()->find($this->subjectId);
if ($element !== null) {
$deriver->forElement($element);
}
}
}
+2
View File
@@ -72,6 +72,8 @@ public function handle(): void
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->status = ContentVersionStatus::Bereit;
$version->save();
DeriveThumbnail::dispatch('element', $version->content_element_id);
DeriveFilmRenditions::dispatch($version->id);
}
private function storedName(string $name): ?string
+3 -1
View File
@@ -6,6 +6,8 @@
use App\Domain\Cms\NavigationItemPolicy;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePolicy;
use App\Domain\Media\FfmpegFilmTranscoder;
use App\Domain\Media\FilmTranscoder;
use App\Filament\Support\MediaUploadLimit;
use App\Http\Responses\StaffLoginResponse;
use App\Models\User;
@@ -19,7 +21,7 @@ class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
$this->app->bind(FilmTranscoder::class, FfmpegFilmTranscoder::class);
}
public function boot(): void
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('media_renditions', function (Blueprint $table) {
$table->id();
$table->foreignId('content_element_version_id')->constrained()->restrictOnDelete();
$table->string('role');
$table->string('label');
$table->string('path');
$table->timestamps();
$table->unique(['content_element_version_id', 'label']);
});
Schema::table('media_deliveries', function (Blueprint $table) {
$table->string('copy_id')->nullable();
$table->string('checksum')->nullable();
$table->string('marking')->nullable();
});
}
public function down(): void
{
Schema::table('media_deliveries', function (Blueprint $table) {
$table->dropColumn(['copy_id', 'checksum', 'marking']);
});
Schema::dropIfExists('media_renditions');
}
};
+1 -1
View File
@@ -71,6 +71,6 @@ ## Annahmen und offene Punkte
- **Öffentliche CMS-Bilder:** Der Web-Prozess schreibt nicht nach `public/`. Ein Upload liegt zuerst auf dem beschreibbaren Storage-Volume (`cms_incoming`). Die Queue kopiert nach `public/` auf dem Medienpfad. Ausgeliefert wird die Datei über die Anwendung unter `/medien/…`, zuerst aus dem öffentlichen Medienpfad, ersatzweise aus dem Eingang. `storage:link` wird dafür nicht gebraucht.
- **Reverse Proxy:** Die Anwendung vertraut weitergeleiteten Proxy-Kopfzeilen. Nginx reicht `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Port` und `X-Forwarded-For` an PHP weiter. Der Proxy vor dem Container muss `X-Forwarded-Proto` setzen, damit Adressen `https` bleiben.
- **Upload:** Filme bis 2 GB. Dieselbe Grenze gilt in Livewire (Zwischendatei, sonst 12 MB), im Formular, in PHP (`upload_max_filesize`, `post_max_size`) und in Nginx (`client_max_body_size`). Die signierte Upload-Adresse gilt 60 Minuten. Die Queue kopiert die Datei als Strom nach `derived/` und behält den Auftrag bis zu einer Stunde; `retry_after` der Datenbank-Queue liegt darüber.
- **Queue:** Datenbank-Queue (`QUEUE_CONNECTION=database`), kein Redis. Reicht für den Start. Der Worker erlaubt einem Auftrag bis zu einer Stunde (`--timeout=3600`).
- **Queue:** Datenbank-Queue (`QUEUE_CONNECTION=database`), kein Redis. Reicht für den Start. Der Worker erlaubt einem Auftrag bis zu einer Stunde (`--timeout=3600`). Das App-Image enthält `ffmpeg`. Die Queue leitet daraus Vorschaubilder und, wenn die Datei lesbar ist, drei HLS-Qualitätsstufen nach `derived/` ab. Fehlt die Ableitung, bleibt die gespeicherte Datei über den bisherigen berechtigten Abruf lesbar. Der Web-Prozess schreibt diese Ableitungen nicht.
- **Gate vor Prod:** Merge-Schutz ist eine Gitea-Einstellung und gehört nicht in die Workflows.
- **Umzug Test auf den Pi:** Werte oben in `deploy-test.yml` ändern (Label `ubuntu-latest`, Guard auf `raspberrypi5`/`aarch64`, Pfade, Port). Das Dockerfile baut auch für ARM64. Vorher Speicherlage auf dem Pi klären.
+9 -36
View File
@@ -4,6 +4,9 @@
"requires": true,
"packages": {
"": {
"dependencies": {
"hls.js": "^1.7.4"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"concurrently": "^10.0.3",
@@ -42,31 +45,6 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/@emnapi/core": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
"integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-beta.2",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
"integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
@@ -1210,6 +1188,12 @@
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/hls.js": {
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.4.tgz",
"integrity": "sha512-3GlxGdPvT2YHvQYOt+yOzT/DEior/qJVNIylHA77kgeoBTdQQqi70GwefNEUmHQeNGyjC8U62+bruqW/Tpm+tg==",
"license": "Apache-2.0"
},
"node_modules/indent-string": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz",
@@ -1731,17 +1715,6 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/react": {
"version": "19.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
"integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-reconciler": {
"version": "0.33.0",
"resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz",
+3
View File
@@ -15,5 +15,8 @@
},
"optionalDependencies": {
"@laravel/multiplex": "^0.4.1"
},
"dependencies": {
"hls.js": "^1.7.4"
}
}
+7
View File
@@ -700,6 +700,13 @@ body.member .thumb .flag {
border-radius: var(--radius-pille);
}
body.member .thumb img {
width: 100%;
height: 8rem;
object-fit: cover;
border-radius: 8px;
}
body.member .thumb-label {
align-self: flex-start;
background: rgb(255 255 255 / 92%);
+22
View File
@@ -1,3 +1,25 @@
import Hls from 'hls.js';
document.querySelectorAll('video[data-hls]').forEach((video) => {
const source = video.dataset.hls;
if (!source) {
return;
}
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = source;
return;
}
if (Hls.isSupported()) {
const playback = new Hls();
playback.loadSource(source);
playback.attachMedia(video);
}
});
document.addEventListener('click', (event) => {
const fullscreen = event.target.closest('[data-fullscreen]');
+1 -1
View File
@@ -28,7 +28,7 @@
@endif
@if ($entry['playable'])
<div class="player">
<video controls preload="metadata" playsinline src="{{ $entry['url'] }}"></video>
<video controls preload="metadata" playsinline @if (($entry['playback'] ?? 'file') === 'hls') data-hls="{{ $entry['url'] }}" @else src="{{ $entry['url'] }}" @endif></video>
<button class="button button-quiet" type="button" data-fullscreen>Vollbild</button>
</div>
@elseif ($entry['allowed'] && $entry['url'])
+3
View File
@@ -75,6 +75,9 @@
'card' => $program + [
'error' => $program['composition']->thumbnail_error,
'image' => filled($program['composition']->thumbnail_path) ? ($program['composition']->thumbnail_alt ?: 'Vorschaubild') : null,
'image_url' => str_starts_with((string) $program['composition']->thumbnail_path, 'vorschau/')
? route('member.thumbnail', ['kind' => 'komposition', 'subject' => $program['composition']->id])
: null,
],
])
@endforeach
@@ -9,7 +9,11 @@
<a href="{{ $href }}">
<div class="thumb">
<span class="flag">{{ $card['kind'] ?: 'Material' }}</span>
<span class="thumb-label">{{ filled($card['image'] ?? null) ? $card['image'] : 'Platzhalter' }}</span>
@if (filled($card['image_url'] ?? null))
<img src="{{ $card['image_url'] }}" alt="{{ $card['image'] ?: 'Vorschaubild' }}">
@else
<span class="thumb-label">{{ filled($card['image'] ?? null) ? $card['image'] : 'Platzhalter' }}</span>
@endif
</div>
<div class="card-copy">
<h2>{{ $card['title'] }}</h2>
@@ -20,7 +20,7 @@
@if ($node['output_class'] === 'audio')
<audio controls preload="metadata" src="{{ $node['view_url'] }}"></audio>
@else
<video controls preload="metadata" playsinline src="{{ $node['view_url'] }}"></video>
<video controls preload="metadata" playsinline @if (($node['playback'] ?? 'file') === 'hls') data-hls="{{ $node['view_url'] }}" @else src="{{ $node['view_url'] }}" @endif></video>
<button class="button button-quiet" type="button" data-fullscreen>Vollbild</button>
@endif
</div>
+7 -1
View File
@@ -30,7 +30,13 @@
@endif
<div>
<dt>Vorschaubild</dt>
<dd>{{ filled($composition->thumbnail_path) ? ($composition->thumbnail_alt ?: 'Vorschaubild') : 'Platzhalter' }}</dd>
<dd>
@if (str_starts_with((string) $composition->thumbnail_path, 'vorschau/'))
<img src="{{ route('member.thumbnail', ['kind' => 'komposition', 'subject' => $composition->id]) }}" alt="{{ $composition->thumbnail_alt ?: 'Vorschaubild' }}">
@else
Platzhalter
@endif
</dd>
</div>
</dl>
@if (filled($composition->thumbnail_error))
+3
View File
@@ -6,6 +6,9 @@
<p class="crumb"><a href="{{ route('member.library') }}">Bibliothek</a></p>
<article class="reading">
<h1>{{ $version->element->working_title }}</h1>
@if (filled($reader ?? null) && filled($copy ?? null))
<p class="state state-hinweis">Lizenziert für {{ $reader }} · Lizenzkopie {{ $copy }}</p>
@endif
@if (filled($license ?? null))
<p class="state state-hinweis">Lizenzkennzeichnung: {{ $license }}</p>
@endif
+7
View File
@@ -63,6 +63,13 @@
Route::get('/ausgabe/{article}/{release}/{version}/{action}', [LibraryController::class, 'media'])
->middleware('signed:relative')
->name('media');
Route::get('/abschnitt/{article}/{release}/{version}/{datei}', [LibraryController::class, 'rendition'])
->where('datei', '.*')
->middleware('signed:relative')
->name('rendition');
Route::get('/vorschau/{kind}/{subject}', [LibraryController::class, 'thumbnail'])
->whereNumber('subject')
->name('thumbnail');
Route::get('/materialien', [LibraryController::class, 'materials'])->name('materials');
Route::get('/berechtigungen', [LibraryController::class, 'grants'])->name('grants');
Route::get('/angebote', [CheckoutController::class, 'offers'])->name('offers');
+3 -1
View File
@@ -2,6 +2,7 @@
namespace Tests\Feature;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ContentVersionStatus;
use App\Filament\Resources\Combinations\CombinationResource;
@@ -115,7 +116,8 @@ public function test_an_exercise_can_gain_and_drop_a_medium_without_losing_the_o
->assertSee('Baustein hinzufügen')
->assertSee('Neue Fassung veröffentlichen');
$this->get(CourseResource::getUrl('index'))->assertOk()->assertSee('Ein Kurs ist keine Übung');
$this->get(CourseResource::getUrl('index'))->assertOk()->assertSee('Ein Programm aus Modulen');
$this->assertStringContainsString('Ein Kurs ist keine Übung', CompositionKind::Kurs->explanation());
$this->get(CombinationResource::getUrl('index'))->assertOk()->assertSee('Materialsatz');
$this->get(ContentElementResource::getUrl('index'))->assertOk()->assertSee('Übungsfilm');
+226
View File
@@ -0,0 +1,226 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\OfferService;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Entitlement\MediaDelivery;
use App\Domain\Media\FilmTranscoder;
use App\Domain\Media\ThumbnailDeriver;
use App\Http\LibraryCatalog;
use App\Http\SignedLink;
use App\Jobs\DeriveFilmRenditions;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class MediaReleaseTest extends TestCase
{
use RefreshDatabase;
public function test_a_thumbnail_stays_on_the_derived_disk_and_off_the_public_route(): void
{
Storage::fake('media_derived');
$image = imagecreatetruecolor(8, 8);
ob_start();
imagepng($image);
$png = ob_get_clean();
imagedestroy($image);
Storage::disk('media_derived')->put('inhalte/bild.png', $png);
$content = app(ContentService::class);
$element = $content->createElement('bild', 'bild', 'Kartenbild');
$version = $content->publishElementVersion($element, null, ['file' => 'inhalte/bild.png']);
$hash = $version->content_hash;
app(ThumbnailDeriver::class)->forElement($element->fresh());
$element->refresh();
$version->refresh();
$this->assertSame(1, $element->versions()->count());
$this->assertSame($hash, $version->content_hash);
$this->assertStringStartsWith('vorschau/element-'.$element->id, (string) $element->thumbnail_path);
Storage::disk('media_derived')->assertExists($element->thumbnail_path);
$this->get('/medien/'.$element->thumbnail_path)->assertNotFound();
[$article, $offer, $release] = $this->offerFor($version, ['bild' => ['ansehen']]);
$member = User::factory()->create();
$stranger = User::factory()->create();
app(GrantIssuer::class)->claim($member, $offer);
$this->actingAs($member)
->get(route('member.thumbnail', ['kind' => 'element', 'subject' => $element->id]))
->assertOk();
$this->actingAs($stranger)
->get(route('member.thumbnail', ['kind' => 'element', 'subject' => $element->id]))
->assertForbidden();
$this->assertNotNull($release);
$this->assertNotNull($article);
}
public function test_adaptive_playback_keeps_the_source_file_and_the_permission_split(): void
{
Storage::fake('media_derived');
Storage::disk('media_derived')->put('inhalte/hof.mp4', 'filmbytes');
$content = app(ContentService::class);
$film = $content->publishElementVersion(
$content->createElement('film', 'film', 'Hofszene'),
null,
['file' => 'inhalte/hof.mp4'],
);
$hash = $film->content_hash;
[$article, $offer, $release] = $this->offerFor($film, ['film' => ['streamen', 'laden']]);
$member = User::factory()->create();
app(GrantIssuer::class)->claim($member, $offer);
$progressive = SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $film->id,
'action' => 'streamen',
'reader' => $member->id,
]);
$this->actingAs($member)->get($progressive)->assertOk()->assertStreamedContent('filmbytes');
$this->app->instance(FilmTranscoder::class, new class implements FilmTranscoder
{
public function available(): bool
{
return true;
}
public function derive(int $versionId, string $sourceRelative): array
{
$base = 'ableitungen/'.$versionId;
Storage::disk('media_derived')->put($base.'/480/index.m3u8', "#EXTM3U\n#EXTINF:6.0,\nsegment.ts\n");
Storage::disk('media_derived')->put($base.'/480/segment.ts', 'segment-bytes');
Storage::disk('media_derived')->put($base.'/master.m3u8', "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=800000\n480/index.m3u8\n");
return [
['role' => 'variant', 'label' => '480', 'path' => $base.'/480/index.m3u8'],
['role' => 'master', 'label' => 'master', 'path' => $base.'/master.m3u8'],
];
}
});
app(DeriveFilmRenditions::class, ['versionId' => $film->id])->handle(app(FilmTranscoder::class));
$film->refresh();
$this->assertSame($hash, $film->content_hash);
$playlist = $this->actingAs($member)->get($progressive)->assertOk();
$playlist->assertHeader('content-type', 'application/vnd.apple.mpegurl');
$this->assertStringContainsString('abschnitt', $playlist->getContent());
$variant = SignedLink::temporary('member.rendition', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $film->id,
'datei' => 'ableitungen/'.$film->id.'/480/segment.ts',
'reader' => $member->id,
]);
$this->actingAs($member)->get($variant)->assertOk()->assertStreamedContent('segment-bytes');
$foreign = SignedLink::temporary('member.rendition', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $film->id,
'datei' => 'ableitungen/999/master.m3u8',
'reader' => $member->id,
]);
$this->actingAs($member)->get($foreign)->assertNotFound();
$download = SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $film->id,
'action' => 'laden',
'reader' => $member->id,
]);
$this->actingAs($member)->get($download)->assertOk()->assertStreamedContent('filmbytes');
$watchRights = app(OfferService::class)->createRightsProfile('Nur ansehen '.str()->random(4), 'ehrenamtlich', [
'film' => ['streamen'],
]);
$watchOffer = app(OfferService::class)->create('Nur Stream '.str()->random(4));
app(OfferService::class)->activate($watchOffer, [
['target' => $article->fresh(), 'rights' => $watchRights],
], ['grant_kind' => 'auf_abruf']);
$watchOnly = User::factory()->create();
app(GrantIssuer::class)->claim($watchOnly, $watchOffer);
$deniedDownload = SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $film->id,
'action' => 'laden',
'reader' => $watchOnly->id,
]);
$before = MediaDelivery::query()->count();
$this->actingAs($watchOnly)->get($deniedDownload)->assertForbidden();
$this->assertSame($before, MediaDelivery::query()->count());
}
public function test_a_document_view_is_marked_and_two_grants_stay_separate(): void
{
$content = app(ContentService::class);
$sheet = $content->publishElementVersion(
$content->createElement('text', 'document', 'Merkblatt'),
'Erst vorlesen.',
);
[$article, $offer, $release] = $this->offerFor($sheet, ['document' => ['ansehen']]);
$second = app(OfferService::class);
$otherRights = $second->createRightsProfile('Nur ansehen', 'ehrenamtlich', ['document' => ['ansehen']]);
$otherOffer = $second->create('Zweites Angebot');
$second->activate($otherOffer, [
['target' => $article->fresh(), 'rights' => $otherRights],
], ['grant_kind' => 'auf_abruf']);
$member = User::factory()->create(['name' => 'Trainer Prüfung']);
app(GrantIssuer::class)->claim($member, $offer);
app(GrantIssuer::class)->claim($member, $otherOffer);
$snapshots = Grant::query()->orderBy('id')->pluck('rights_snapshot', 'id')->all();
$url = SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $sheet->id,
'action' => 'ansehen',
'reader' => $member->id,
]);
$this->actingAs($member)->get($url)->assertOk()->assertSee('Lizenziert für Trainer Prüfung')->assertSee('Lizenzkopie');
$this->assertSame(1, MediaDelivery::query()->count());
$delivery = MediaDelivery::query()->first();
$this->assertSame('k2', $delivery->marking);
$this->assertNotNull($delivery->checksum);
$this->assertContains($delivery->grant_id, array_keys($snapshots));
$this->assertSame($snapshots, Grant::query()->orderBy('id')->pluck('rights_snapshot', 'id')->all());
$stranger = User::factory()->create();
$this->actingAs($stranger)->get($url)->assertForbidden();
$this->assertSame(1, MediaDelivery::query()->count());
$catalog = app(LibraryCatalog::class)->index($member);
$this->assertCount(1, array_filter($catalog['materials'], fn (array $card): bool => $card['title'] === 'Merkblatt'));
}
/**
* @param array<string, list<string>> $capabilities
* @return array{0: mixed, 1: mixed, 2: mixed}
*/
private function offerFor($version, array $capabilities): array
{
$articles = app(ArticleService::class);
$offers = app(OfferService::class);
$article = $articles->create('ausgabe-'.str()->random(6));
$release = $articles->publishRelease($article, $version, 'Stand.');
$rights = $offers->createRightsProfile('Rechte '.str()->random(4), 'ehrenamtlich', $capabilities);
$offer = $offers->create('Angebot '.str()->random(4));
$offers->activate($offer, [
['target' => $article->fresh(), 'rights' => $rights],
], ['grant_kind' => 'auf_abruf']);
return [$article->fresh(), $offer, $release];
}
}