Liefere Filme im Dateimodus und Downloads mit Bereichsabrufen aus und rechne die Prüfsumme einmal

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 <noreply@anthropic.com>
This commit is contained in:
StommerandClaude Sonnet 5.5 committed 2026-12-01 11:12:58 +01:00
1 parent 9e8d0020b3
commit f07fbae940
6 files changed
+281 -24

No files matched your search

+2 -1
View File
@@ -53,6 +53,7 @@ public function writeUnlessRecent(
string $action, string $action,
string $format, string $format,
string $marking, string $marking,
string|\Closure|null $checksum = null,
): bool { ): bool {
$recent = MediaDelivery::query() $recent = MediaDelivery::query()
->where('grant_id', $grant->id) ->where('grant_id', $grant->id)
@@ -65,7 +66,7 @@ public function writeUnlessRecent(
return false; 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; return true;
} }
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Domain\Media;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
/**
* SHA-256 einer Datei der Medienablage für den Auslieferungsnachweis (08 §7), je Datei einmal berechnet.
*
* Die Dateien sind nach dem Speichern unveränderlich. Der gemerkte Wert gilt daher für Pfad, Größe und Änderungszeit;
* ändert sich eine davon, wird neu gerechnet. Ist die Datei nicht lesbar, ist das Ergebnis null (der Nachweis nennt
* dann keine Prüfsumme, statt die Auslieferung zu blockieren).
*/
class FileChecksum
{
public function of(string $diskName, string $path): ?string
{
$disk = Storage::disk($diskName);
try {
if (! $disk->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;
}
}
}
@@ -4,6 +4,7 @@
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
/** /**
@@ -14,17 +15,29 @@ trait ServesByteRanges
{ {
private const CHUNK = 262144; 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<string, string> $extra weitere Kopfzeilen
*/
protected function respondWithRanges(
Request $request,
string $diskName,
string $path,
bool $ranged,
?string $name = null,
string $disposition = 'inline',
array $extra = [],
): StreamedResponse {
$headers = [ $headers = [
'Content-Disposition' => 'inline', 'Content-Disposition' => $name === null ? $disposition : $this->disposition($disposition, $name),
'X-Content-Type-Options' => 'nosniff', 'X-Content-Type-Options' => 'nosniff',
'Accept-Ranges' => 'bytes', 'Accept-Ranges' => 'bytes',
]; ] + $extra;
$range = $request->header('Range'); $range = $request->header('Range');
if (! is_string($range) || ! $ranged) { 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); $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. * Erster Bereich aus „bytes=a-b“, „bytes=a-“ oder „bytes=-n“; null, wenn er nicht erfüllbar ist.
* *
@@ -17,10 +17,12 @@
use App\Domain\Entitlement\Grant; use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus; use App\Domain\Entitlement\GrantStatus;
use App\Domain\Media\DeliveryLog; use App\Domain\Media\DeliveryLog;
use App\Domain\Media\FileChecksum;
use App\Domain\Media\FilmPlayback; use App\Domain\Media\FilmPlayback;
use App\Domain\Media\HlsPlaylist; use App\Domain\Media\HlsPlaylist;
use App\Domain\Media\MediaRendition; use App\Domain\Media\MediaRendition;
use App\Domain\Media\StreamLifetime; use App\Domain\Media\StreamLifetime;
use App\Http\Controllers\Concerns\ServesByteRanges;
use App\Http\Controllers\Concerns\ServesImages; use App\Http\Controllers\Concerns\ServesImages;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Http\CourseOutline; use App\Http\CourseOutline;
@@ -40,6 +42,7 @@
class LibraryController extends Controller class LibraryController extends Controller
{ {
use ServesByteRanges;
use ServesImages; use ServesImages;
/** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */ /** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */
@@ -252,9 +255,6 @@ public function show(Request $request, LicenseArticle $article): View
'action' => $action, 'action' => $action,
'allowed' => $decision->allowed, 'allowed' => $decision->allowed,
'reason' => $decision->reason, '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'), 'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
'playback' => app(FilmPlayback::class)->mode($version->id), 'playback' => app(FilmPlayback::class)->mode($version->id),
'renew_url' => $decision->allowed && $action === 'streamen' && app(FilmPlayback::class)->mode($version->id) === 'hls' '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( public function rendition(
@@ -505,6 +505,7 @@ private function playlist(
} }
private function fileResponse( private function fileResponse(
Request $request,
Grant $grant, Grant $grant,
LicenseArticle $article, LicenseArticle $article,
ArticleRelease $release, ArticleRelease $release,
@@ -515,24 +516,27 @@ private function fileResponse(
): StreamedResponse { ): StreamedResponse {
$disk = Storage::disk('media_derived'); $disk = Storage::disk('media_derived');
abort_unless($disk->exists($file) && ! str_contains($file, '..'), 404); abort_unless($disk->exists($file) && ! str_contains($file, '..'), 404);
$delivery = app(DeliveryLog::class)->write( $log = app(DeliveryLog::class);
$grant, $checksum = fn (): ?string => app(FileChecksum::class)->of('media_derived', $file);
$article,
$release,
$version,
$action,
$format,
hash_file('sha256', $disk->path($file)) ?: null,
'k0',
);
// Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“); Laravel setzt Content-Disposition mit // Ein vollständiger Abruf ist eine Auslieferung. Teilabrufe (Springen, Fortsetzen) derselben Wiedergabe zählen
// ASCII-Rückfall und UTF-8-Name. // innerhalb der Laufzeit der Adresse nicht erneut; gibt es noch keinen Nachweis, entsteht genau einer.
return $disk->response( 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, $file,
true,
$this->downloadName($version, $file), $this->downloadName($version, $file),
['X-License-Copy' => $delivery->copy_id],
$action === 'laden' ? 'attachment' : 'inline', $action === 'laden' ? 'attachment' : 'inline',
$copy === '' ? [] : ['X-License-Copy' => $copy],
); );
} }
+3
View File
@@ -4,6 +4,7 @@
use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Media\FileChecksum;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable; use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@@ -82,6 +83,8 @@ public function handle(): void
} }
$version->save(); $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); DeriveThumbnail::dispatch('element', $version->content_element_id);
DeriveFilmRenditions::dispatch($version->id); DeriveFilmRenditions::dispatch($version->id);
} }
+181
View File
@@ -0,0 +1,181 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Entitlement\MediaDelivery;
use App\Domain\Media\FileChecksum;
use App\Http\SignedLink;
use App\Jobs\StoreContentFile;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Tests\Support\BuildsFilmFixtures;
use Tests\TestCase;
/**
* Filme ohne HLS-Stufen (Dateimodus) und Downloads im Mitgliederbereich: Bereichsabrufe (206/416) wie bei der
* Website, damit Safari und iOS abspielen und Springen möglich ist. Der Auslieferungsnachweis zählt eine Auslieferung,
* nicht jeden Teilabruf; die Prüfsumme wird je Datei einmal berechnet.
*/
class MemberFileRangesTest extends TestCase
{
use BuildsFilmFixtures;
use RefreshDatabase;
private const BODY = '0123456789abcdefghij';
public function test_a_ranged_request_gets_only_the_requested_bytes(): void
{
[$member, $url] = $this->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,
])];
}
}