From f07fbae94024dc00cdf240a9a2cdb58157d908a9 Mon Sep 17 00:00:00 2001 From: Stommer Date: Tue, 1 Dec 2026 11:12:58 +0100 Subject: [PATCH] =?UTF-8?q?Liefere=20Filme=20im=20Dateimodus=20und=20Downl?= =?UTF-8?q?oads=20mit=20Bereichsabrufen=20aus=20und=20rechne=20die=20Pr?= =?UTF-8?q?=C3=BCfsumme=20einmal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LibraryController::fileResponse nutzt ServesByteRanges (206/416): Safari und iOS spielen ab, Springen und Fortsetzen eines Downloads gehen. Dateiname und attachment bleiben. Der Nachweis zählt einen vollständigen Abruf als eine Auslieferung; Teilabrufe schreiben nur, wenn noch kein Eintrag der letzten zehn Minuten steht. FileChecksum merkt die SHA-256 je Datei (Pfad, Größe, Zeit) und wird beim Speichern vorgewärmt, damit die erste Wiedergabe nicht auf das Hashen einer großen Datei wartet. Der entfernte decision-Schlüssel der Artikelseite war ungenutzt. Co-Authored-By: Claude Sonnet 5.5 --- app/Domain/Media/DeliveryLog.php | 3 +- app/Domain/Media/FileChecksum.php | 48 +++++ .../Controllers/Concerns/ServesByteRanges.php | 30 ++- .../Controllers/Member/LibraryController.php | 40 ++-- app/Jobs/StoreContentFile.php | 3 + tests/Feature/MemberFileRangesTest.php | 181 ++++++++++++++++++ 6 files changed, 281 insertions(+), 24 deletions(-) create mode 100644 app/Domain/Media/FileChecksum.php create mode 100644 tests/Feature/MemberFileRangesTest.php diff --git a/app/Domain/Media/DeliveryLog.php b/app/Domain/Media/DeliveryLog.php index 3e362d4..ccb812a 100644 --- a/app/Domain/Media/DeliveryLog.php +++ b/app/Domain/Media/DeliveryLog.php @@ -53,6 +53,7 @@ public function writeUnlessRecent( string $action, string $format, string $marking, + string|\Closure|null $checksum = null, ): bool { $recent = MediaDelivery::query() ->where('grant_id', $grant->id) @@ -65,7 +66,7 @@ public function writeUnlessRecent( return false; } - $this->write($grant, $article, $release, $version, $action, $format, null, $marking); + $this->write($grant, $article, $release, $version, $action, $format, $checksum instanceof \Closure ? $checksum() : $checksum, $marking); return true; } diff --git a/app/Domain/Media/FileChecksum.php b/app/Domain/Media/FileChecksum.php new file mode 100644 index 0000000..5c6266a --- /dev/null +++ b/app/Domain/Media/FileChecksum.php @@ -0,0 +1,48 @@ +exists($path)) { + return null; + } + + $key = 'media-checksum:'.hash('sha256', $diskName.'|'.$path.'|'.$disk->size($path).'|'.$disk->lastModified($path)); + + return Cache::rememberForever($key, function () use ($disk, $path): ?string { + $stream = $disk->readStream($path); + + if (! is_resource($stream)) { + return null; + } + + try { + $context = hash_init('sha256'); + hash_update_stream($context, $stream); + + return hash_final($context); + } finally { + fclose($stream); + } + }); + } catch (\Throwable) { + return null; + } + } +} diff --git a/app/Http/Controllers/Concerns/ServesByteRanges.php b/app/Http/Controllers/Concerns/ServesByteRanges.php index 0c7eab9..6ddd037 100644 --- a/app/Http/Controllers/Concerns/ServesByteRanges.php +++ b/app/Http/Controllers/Concerns/ServesByteRanges.php @@ -4,6 +4,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; +use Symfony\Component\HttpFoundation\HeaderUtils; use Symfony\Component\HttpFoundation\StreamedResponse; /** @@ -14,17 +15,29 @@ trait ServesByteRanges { private const CHUNK = 262144; - protected function respondWithRanges(Request $request, string $diskName, string $path, bool $ranged): StreamedResponse - { + /** + * @param string|null $name Dateiname für Ansicht oder Download (ohne: Name der Datei) + * @param string $disposition inline oder attachment + * @param array $extra weitere Kopfzeilen + */ + protected function respondWithRanges( + Request $request, + string $diskName, + string $path, + bool $ranged, + ?string $name = null, + string $disposition = 'inline', + array $extra = [], + ): StreamedResponse { $headers = [ - 'Content-Disposition' => 'inline', + 'Content-Disposition' => $name === null ? $disposition : $this->disposition($disposition, $name), 'X-Content-Type-Options' => 'nosniff', 'Accept-Ranges' => 'bytes', - ]; + ] + $extra; $range = $request->header('Range'); if (! is_string($range) || ! $ranged) { - return Storage::disk($diskName)->response($path, null, $headers); + return Storage::disk($diskName)->response($path, $name, $headers, $disposition); } $disk = Storage::disk($diskName); @@ -63,6 +76,13 @@ protected function respondWithRanges(Request $request, string $diskName, string ]); } + private function disposition(string $type, string $name): string + { + $fallback = (string) preg_replace('/[^ -~]|["\\%]/', '_', $name); + + return HeaderUtils::makeDisposition($type, $name, $fallback); + } + /** * Erster Bereich aus „bytes=a-b“, „bytes=a-“ oder „bytes=-n“; null, wenn er nicht erfüllbar ist. * diff --git a/app/Http/Controllers/Member/LibraryController.php b/app/Http/Controllers/Member/LibraryController.php index 513baab..755d3e0 100644 --- a/app/Http/Controllers/Member/LibraryController.php +++ b/app/Http/Controllers/Member/LibraryController.php @@ -17,10 +17,12 @@ use App\Domain\Entitlement\Grant; use App\Domain\Entitlement\GrantStatus; use App\Domain\Media\DeliveryLog; +use App\Domain\Media\FileChecksum; use App\Domain\Media\FilmPlayback; use App\Domain\Media\HlsPlaylist; use App\Domain\Media\MediaRendition; use App\Domain\Media\StreamLifetime; +use App\Http\Controllers\Concerns\ServesByteRanges; use App\Http\Controllers\Concerns\ServesImages; use App\Http\Controllers\Controller; use App\Http\CourseOutline; @@ -40,6 +42,7 @@ class LibraryController extends Controller { + use ServesByteRanges; use ServesImages; /** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */ @@ -252,9 +255,6 @@ public function show(Request $request, LicenseArticle $article): View 'action' => $action, 'allowed' => $decision->allowed, 'reason' => $decision->reason, - 'decision' => is_numeric($metadata['decision_seconds'] ?? null) - ? (int) $metadata['decision_seconds'] - : null, 'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'), 'playback' => app(FilmPlayback::class)->mode($version->id), 'renew_url' => $decision->allowed && $action === 'streamen' && app(FilmPlayback::class)->mode($version->id) === 'hls' @@ -336,7 +336,7 @@ public function media( ]); } - return $this->fileResponse($decision->grant, $article, $release, $version, $action, $file, 'bestand'); + return $this->fileResponse($request, $decision->grant, $article, $release, $version, $action, $file, 'bestand'); } public function rendition( @@ -505,6 +505,7 @@ private function playlist( } private function fileResponse( + Request $request, Grant $grant, LicenseArticle $article, ArticleRelease $release, @@ -515,24 +516,27 @@ private function fileResponse( ): 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', - ); + $log = app(DeliveryLog::class); + $checksum = fn (): ?string => app(FileChecksum::class)->of('media_derived', $file); - // Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“); Laravel setzt Content-Disposition mit - // ASCII-Rückfall und UTF-8-Name. - return $disk->response( + // Ein vollständiger Abruf ist eine Auslieferung. Teilabrufe (Springen, Fortsetzen) derselben Wiedergabe zählen + // innerhalb der Laufzeit der Adresse nicht erneut; gibt es noch keinen Nachweis, entsteht genau einer. + if (is_string($request->header('Range'))) { + $log->writeUnlessRecent(600, $grant, $article, $release, $version, $action, $format, 'k0', $checksum); + $copy = ''; + } else { + $copy = $log->write($grant, $article, $release, $version, $action, $format, $checksum(), 'k0')->copy_id; + } + + // Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“), mit ASCII-Rückfall und UTF-8-Name. + return $this->respondWithRanges( + $request, + 'media_derived', $file, + true, $this->downloadName($version, $file), - ['X-License-Copy' => $delivery->copy_id], $action === 'laden' ? 'attachment' : 'inline', + $copy === '' ? [] : ['X-License-Copy' => $copy], ); } diff --git a/app/Jobs/StoreContentFile.php b/app/Jobs/StoreContentFile.php index dc0ab93..347c99a 100644 --- a/app/Jobs/StoreContentFile.php +++ b/app/Jobs/StoreContentFile.php @@ -4,6 +4,7 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentVersionStatus; +use App\Domain\Media\FileChecksum; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\Storage; @@ -82,6 +83,8 @@ public function handle(): void } $version->save(); + // Prüfsumme für den Auslieferungsnachweis jetzt rechnen, damit die erste Wiedergabe nicht darauf wartet. + app(FileChecksum::class)->of('media_derived', $target); DeriveThumbnail::dispatch('element', $version->content_element_id); DeriveFilmRenditions::dispatch($version->id); } diff --git a/tests/Feature/MemberFileRangesTest.php b/tests/Feature/MemberFileRangesTest.php new file mode 100644 index 0000000..53d5a3c --- /dev/null +++ b/tests/Feature/MemberFileRangesTest.php @@ -0,0 +1,181 @@ +fileFilm('streamen'); + + $response = $this->actingAs($member)->get($url, ['Range' => 'bytes=2-5']); + + $response->assertStatus(206); + $response->assertHeader('Content-Range', 'bytes 2-5/'.strlen(self::BODY)); + $response->assertHeader('Accept-Ranges', 'bytes'); + $this->assertSame('2345', $response->streamedContent()); + + $open = $this->actingAs($member)->get($url, ['Range' => 'bytes=15-']); + $open->assertStatus(206); + $this->assertSame('fghij', $open->streamedContent()); + + $suffix = $this->actingAs($member)->get($url, ['Range' => 'bytes=-3']); + $this->assertSame('hij', $suffix->streamedContent()); + } + + public function test_an_unsatisfiable_range_gets_416_and_a_plain_request_gets_everything(): void + { + [$member, $url] = $this->fileFilm('streamen'); + + $this->actingAs($member)->get($url, ['Range' => 'bytes=500-600']) + ->assertStatus(416) + ->assertHeader('Content-Range', 'bytes */'.strlen(self::BODY)); + + $plain = $this->actingAs($member)->get($url); + $plain->assertOk(); + $plain->assertHeader('Accept-Ranges', 'bytes'); + $this->assertSame(self::BODY, $plain->streamedContent()); + } + + public function test_a_download_keeps_its_file_name_and_supports_resuming(): void + { + [$member, $url] = $this->fileFilm('laden'); + + $whole = $this->actingAs($member)->get($url); + $whole->assertOk(); + $this->assertStringContainsString('attachment', (string) $whole->headers->get('Content-Disposition')); + $this->assertStringContainsString('Hofszene.mp4', rawurldecode((string) $whole->headers->get('Content-Disposition'))); + + $part = $this->actingAs($member)->get($url, ['Range' => 'bytes=10-']); + $part->assertStatus(206); + $this->assertStringContainsString('attachment', (string) $part->headers->get('Content-Disposition')); + $this->assertStringContainsString('Hofszene.mp4', rawurldecode((string) $part->headers->get('Content-Disposition'))); + $this->assertSame('abcdefghij', $part->streamedContent()); + } + + public function test_partial_requests_count_as_one_delivery_and_a_new_plain_request_counts_again(): void + { + [$member, $url] = $this->fileFilm('streamen'); + + $this->actingAs($member)->get($url, ['Range' => 'bytes=0-1'])->assertStatus(206); + $this->actingAs($member)->get($url, ['Range' => 'bytes=2-9'])->assertStatus(206); + $this->actingAs($member)->get($url, ['Range' => 'bytes=10-'])->assertStatus(206); + + $this->assertSame(1, MediaDelivery::query()->count(), 'Teilabrufe derselben Wiedergabe zählen einmal.'); + $row = MediaDelivery::query()->firstOrFail(); + $this->assertSame('streamen', $row->action); + $this->assertSame(hash('sha256', self::BODY), $row->checksum); + + $this->actingAs($member)->get($url)->assertOk(); + $this->assertSame(2, MediaDelivery::query()->count(), 'Ein vollständiger Abruf ist eine eigene Auslieferung.'); + } + + public function test_a_resumed_range_without_any_earlier_record_still_leaves_a_record(): void + { + [$member, $url] = $this->fileFilm('streamen'); + + $this->actingAs($member)->get($url, ['Range' => 'bytes=10-'])->assertStatus(206); + + $this->assertSame(1, MediaDelivery::query()->count()); + } + + public function test_the_checksum_is_computed_once_per_file(): void + { + Storage::fake('media_derived'); + Cache::flush(); + Storage::disk('media_derived')->put('inhalte/a.mp4', 'inhalt eins'); + $checksum = app(FileChecksum::class); + + $first = $checksum->of('media_derived', 'inhalte/a.mp4'); + $this->assertSame(hash('sha256', 'inhalt eins'), $first); + + // Gleiche Größe und gleicher Zeitstempel: der gemerkte Wert gilt, die Datei wird nicht erneut gelesen. + $path = Storage::disk('media_derived')->path('inhalte/a.mp4'); + $time = filemtime($path); + file_put_contents($path, 'INHALT EINS'); + touch($path, $time); + clearstatcache(); + $this->assertSame($first, $checksum->of('media_derived', 'inhalte/a.mp4')); + + // Andere Größe: neu berechnen. + file_put_contents($path, 'ganz anderer inhalt'); + clearstatcache(); + $this->assertSame(hash('sha256', 'ganz anderer inhalt'), $checksum->of('media_derived', 'inhalte/a.mp4')); + + $this->assertNull($checksum->of('media_derived', 'inhalte/gibtesnicht.mp4')); + } + + public function test_storing_a_new_file_warms_the_checksum(): void + { + Storage::fake('media_derived'); + Storage::fake('cms_incoming'); + Cache::flush(); + Storage::disk('cms_incoming')->put('inhalte/neu.mp4', 'frischer film'); + $element = app(ContentService::class)->createElement('film', 'film', 'Neu'); + $version = $element->versions()->create([ + 'number' => 1, + 'status' => ContentVersionStatus::Entwurf, + 'content_hash' => hash('sha256', 'x'), + 'metadata' => ['incoming' => 'inhalte/neu.mp4'], + ]); + + app(StoreContentFile::class, ['versionId' => $version->id, 'source' => 'inhalte/neu.mp4'])->handle(); + + $stored = $version->fresh()->metadata['file']; + $path = Storage::disk('media_derived')->path($stored); + $time = filemtime($path); + file_put_contents($path, 'FRISCHER FILM'); + touch($path, $time); + clearstatcache(); + + $this->assertSame(hash('sha256', 'frischer film'), app(FileChecksum::class)->of('media_derived', $stored), 'Der Wert wurde schon beim Speichern gemerkt.'); + } + + /** + * @return array{0: User, 1: string} + */ + private function fileFilm(string $action): array + { + Storage::fake('media_derived'); + Cache::flush(); + Storage::disk('media_derived')->put('inhalte/hof.mp4', self::BODY); + $content = app(ContentService::class); + $element = $content->createElement('film', 'film', 'Hofszene'); + $version = $content->publishElementVersion($element, null, ['file' => 'inhalte/hof.mp4']); + [$article, $offer, $release] = $this->offerFor($version, ['film' => ['streamen', 'laden']]); + $member = User::factory()->create(); + app(GrantIssuer::class)->claim($member, $offer); + + return [$member, SignedLink::temporary('member.media', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'version' => $version->id, + 'action' => $action, + 'reader' => $member->id, + ])]; + } +}