diff --git a/Dockerfile b/Dockerfile index 1df653e..3d8df19 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 \ diff --git a/app/Domain/Catalog/CompositionKind.php b/app/Domain/Catalog/CompositionKind.php index 3c9819c..b84b275 100644 --- a/app/Domain/Catalog/CompositionKind.php +++ b/app/Domain/Catalog/CompositionKind.php @@ -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 + */ + public static function deskOptions(): array + { + $options = []; + + foreach (self::cases() as $case) { + $options[$case->value] = $case->deskLabel(); + } + + return $options; + } + /** * @return array */ diff --git a/app/Domain/Entitlement/MediaDelivery.php b/app/Domain/Entitlement/MediaDelivery.php index 9ea89db..5318898 100644 --- a/app/Domain/Entitlement/MediaDelivery.php +++ b/app/Domain/Entitlement/MediaDelivery.php @@ -13,6 +13,9 @@ class MediaDelivery extends Model 'content_element_version_id', 'action', 'format', + 'copy_id', + 'checksum', + 'marking', 'delivered_at', ]; diff --git a/app/Domain/Media/DeliveryLog.php b/app/Domain/Media/DeliveryLog.php new file mode 100644 index 0000000..1f08038 --- /dev/null +++ b/app/Domain/Media/DeliveryLog.php @@ -0,0 +1,36 @@ +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(), + ]); + } +} diff --git a/app/Domain/Media/FfmpegFilmTranscoder.php b/app/Domain/Media/FfmpegFilmTranscoder.php new file mode 100644 index 0000000..562123c --- /dev/null +++ b/app/Domain/Media/FfmpegFilmTranscoder.php @@ -0,0 +1,81 @@ +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; + } +} diff --git a/app/Domain/Media/FilmTranscoder.php b/app/Domain/Media/FilmTranscoder.php new file mode 100644 index 0000000..dcc8887 --- /dev/null +++ b/app/Domain/Media/FilmTranscoder.php @@ -0,0 +1,13 @@ + + */ + public function derive(int $versionId, string $sourceRelative): array; +} diff --git a/app/Domain/Media/HlsPlaylist.php b/app/Domain/Media/HlsPlaylist.php new file mode 100644 index 0000000..46ecc22 --- /dev/null +++ b/app/Domain/Media/HlsPlaylist.php @@ -0,0 +1,30 @@ +where('content_element_version_id', $versionId) + ->where('role', 'master') + ->value('path'); + + return is_string($path) && $path !== '' ? $path : null; + } +} diff --git a/app/Domain/Media/ThumbnailDeriver.php b/app/Domain/Media/ThumbnailDeriver.php new file mode 100644 index 0000000..1f0bb41 --- /dev/null +++ b/app/Domain/Media/ThumbnailDeriver.php @@ -0,0 +1,142 @@ +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(); + } +} diff --git a/app/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index f00ab91..f2a363e 100644 --- a/app/Filament/Resources/Compositions/Pages/EditComposition.php +++ b/app/Filament/Resources/Compositions/Pages/EditComposition.php @@ -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()) diff --git a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php index 4614998..9a531ae 100644 --- a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php +++ b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php @@ -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 diff --git a/app/Http/Controllers/Member/LibraryController.php b/app/Http/Controllers/Member/LibraryController.php index d82598e..52e1bfb 100644 --- a/app/Http/Controllers/Member/LibraryController.php +++ b/app/Http/Controllers/Member/LibraryController.php @@ -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() diff --git a/app/Http/LibraryCatalog.php b/app/Http/LibraryCatalog.php index b0c1fb0..fc44d0f 100644 --- a/app/Http/LibraryCatalog.php +++ b/app/Http/LibraryCatalog.php @@ -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), diff --git a/app/Jobs/DeriveFilmRenditions.php b/app/Jobs/DeriveFilmRenditions.php new file mode 100644 index 0000000..e79d226 --- /dev/null +++ b/app/Jobs/DeriveFilmRenditions.php @@ -0,0 +1,52 @@ +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'], + ], + ); + } + } +} diff --git a/app/Jobs/DeriveThumbnail.php b/app/Jobs/DeriveThumbnail.php new file mode 100644 index 0000000..ea7221b --- /dev/null +++ b/app/Jobs/DeriveThumbnail.php @@ -0,0 +1,39 @@ +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); + } + } +} diff --git a/app/Jobs/StoreContentFile.php b/app/Jobs/StoreContentFile.php index ba3e864..144ad52 100644 --- a/app/Jobs/StoreContentFile.php +++ b/app/Jobs/StoreContentFile.php @@ -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 diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 1b73a68..87da06d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -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 diff --git a/database/migrations/2026_11_16_170000_media_renditions_and_delivery_marking.php b/database/migrations/2026_11_16_170000_media_renditions_and_delivery_marking.php new file mode 100644 index 0000000..ffac828 --- /dev/null +++ b/database/migrations/2026_11_16_170000_media_renditions_and_delivery_marking.php @@ -0,0 +1,35 @@ +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'); + } +}; diff --git a/docs/betrieb/DEPLOYMENT.md b/docs/betrieb/DEPLOYMENT.md index eb9c2fd..f8bea40 100644 --- a/docs/betrieb/DEPLOYMENT.md +++ b/docs/betrieb/DEPLOYMENT.md @@ -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. diff --git a/package-lock.json b/package-lock.json index 99c6966..731adc8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 13ec885..1841ad6 100644 --- a/package.json +++ b/package.json @@ -15,5 +15,8 @@ }, "optionalDependencies": { "@laravel/multiplex": "^0.4.1" + }, + "dependencies": { + "hls.js": "^1.7.4" } } diff --git a/resources/css/app.css b/resources/css/app.css index 5e681ea..a2de2c4 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -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%); diff --git a/resources/js/app.js b/resources/js/app.js index 4beebcc..6de2d8b 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -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]'); diff --git a/resources/views/member/article.blade.php b/resources/views/member/article.blade.php index 65725bd..28f98b1 100644 --- a/resources/views/member/article.blade.php +++ b/resources/views/member/article.blade.php @@ -28,7 +28,7 @@ @endif @if ($entry['playable'])
- +
@elseif ($entry['allowed'] && $entry['url']) diff --git a/resources/views/member/library.blade.php b/resources/views/member/library.blade.php index 41efb97..4111176 100644 --- a/resources/views/member/library.blade.php +++ b/resources/views/member/library.blade.php @@ -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 diff --git a/resources/views/member/partials/card.blade.php b/resources/views/member/partials/card.blade.php index 5f0bf95..f8fd531 100644 --- a/resources/views/member/partials/card.blade.php +++ b/resources/views/member/partials/card.blade.php @@ -9,7 +9,11 @@
{{ $card['kind'] ?: 'Material' }} - {{ filled($card['image'] ?? null) ? $card['image'] : 'Platzhalter' }} + @if (filled($card['image_url'] ?? null)) + {{ $card['image'] ?: 'Vorschaubild' }} + @else + {{ filled($card['image'] ?? null) ? $card['image'] : 'Platzhalter' }} + @endif

{{ $card['title'] }}

diff --git a/resources/views/member/partials/structure.blade.php b/resources/views/member/partials/structure.blade.php index 3082671..7af0825 100644 --- a/resources/views/member/partials/structure.blade.php +++ b/resources/views/member/partials/structure.blade.php @@ -20,7 +20,7 @@ @if ($node['output_class'] === 'audio') @else - + @endif
diff --git a/resources/views/member/program.blade.php b/resources/views/member/program.blade.php index 12e0d3f..acb184c 100644 --- a/resources/views/member/program.blade.php +++ b/resources/views/member/program.blade.php @@ -30,7 +30,13 @@ @endif
Vorschaubild
-
{{ filled($composition->thumbnail_path) ? ($composition->thumbnail_alt ?: 'Vorschaubild') : 'Platzhalter' }}
+
+ @if (str_starts_with((string) $composition->thumbnail_path, 'vorschau/')) + {{ $composition->thumbnail_alt ?: 'Vorschaubild' }} + @else + Platzhalter + @endif +
@if (filled($composition->thumbnail_error)) diff --git a/resources/views/member/read.blade.php b/resources/views/member/read.blade.php index 48297bf..c2d1bc0 100644 --- a/resources/views/member/read.blade.php +++ b/resources/views/member/read.blade.php @@ -6,6 +6,9 @@

Bibliothek

{{ $version->element->working_title }}

+ @if (filled($reader ?? null) && filled($copy ?? null)) +

Lizenziert für {{ $reader }} · Lizenzkopie {{ $copy }}

+ @endif @if (filled($license ?? null))

Lizenzkennzeichnung: {{ $license }}

@endif diff --git a/routes/web.php b/routes/web.php index 17b84b1..ac02aa6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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'); diff --git a/tests/Feature/MediaAdministrationTest.php b/tests/Feature/MediaAdministrationTest.php index 6be8f19..1d59e00 100644 --- a/tests/Feature/MediaAdministrationTest.php +++ b/tests/Feature/MediaAdministrationTest.php @@ -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'); diff --git a/tests/Feature/MediaReleaseTest.php b/tests/Feature/MediaReleaseTest.php new file mode 100644 index 0000000..aa2d9ec --- /dev/null +++ b/tests/Feature/MediaReleaseTest.php @@ -0,0 +1,226 @@ +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> $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]; + } +}