Files
laravel-manager-packagist/src/Modules/Media/MediaFileController.php
T

157 lines
4.9 KiB
PHP

<?php
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Http\Request;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use Symfony\Component\HttpFoundation\Response;
/** Passes a media file on to the browser, with ETag and byte ranges (video needs them). */
class MediaFileController
{
/**
* Types a browser may show as they are. Anything else is offered as a download, so a
* stored file can never run as a page on this domain.
*/
private const array INLINE_TYPES = [
'image/jpeg', 'image/png', 'image/webp', 'image/gif',
'video/mp4', 'video/webm',
'application/pdf',
];
public function __invoke(Request $request, MediaLibrary $library, string $media): Response
{
$media = Media::query()->findOrFail((int) $media);
$headers = $this->headers($media);
// A media id never gets other content, so what the browser has is still right.
if (in_array($headers['ETag'], $request->getETags(), true)) {
return response('', 304, $headers);
}
$range = $this->range($request, $media->size);
if ($range === null) {
return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers);
}
[$start, $end, $partial] = $range;
$length = $end - $start + 1;
$headers['Content-Length'] = (string) $length;
if ($partial) {
$headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}";
}
if ($request->isMethod('HEAD')) {
return response('', $partial ? 206 : 200, $headers);
}
try {
$stream = $library->open($media);
} catch (MediaStorageException $e) {
if ($e->status === 404) {
abort(404);
}
return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']);
}
return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers);
}
/** @return array<string, string> */
private function headers(Media $media): array
{
$inline = in_array($media->mime_type, self::INLINE_TYPES, true);
$name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename);
return [
'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream',
'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"',
'X-Content-Type-Options' => 'nosniff',
'Accept-Ranges' => 'bytes',
'Cache-Control' => 'public, max-age=31536000, immutable',
'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"',
];
}
/**
* The part of the file the browser asks for: [first byte, last byte, is it a part].
* Null when the request asks for bytes the file does not have.
*
* @return array{int, int, bool}|null
*/
private function range(Request $request, int $size): ?array
{
$header = $request->headers->get('Range');
$whole = [0, max($size - 1, 0), false];
// No range, an empty file, or something other than one plain byte range: send it all.
if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) {
return $whole;
}
[, $first, $last] = $match;
if ($first === '' && $last === '') {
return $whole;
}
if ($first === '') {
// "bytes=-500": the last 500 bytes.
$start = max($size - (int) $last, 0);
$end = $size - 1;
} else {
$start = (int) $first;
$end = $last === '' ? $size - 1 : min((int) $last, $size - 1);
}
if ($start >= $size || $start > $end) {
return null;
}
return [$start, $end, true];
}
/** @param resource $stream */
private function send($stream, int $start, int $length): void
{
try {
if ($start > 0 && stream_get_meta_data($stream)['seekable']) {
fseek($stream, $start);
} else {
$skip = $start;
while ($skip > 0 && ! feof($stream)) {
$chunk = fread($stream, min(65536, $skip));
if ($chunk === false || $chunk === '') {
break;
}
$skip -= strlen($chunk);
}
}
while ($length > 0 && ! feof($stream)) {
$chunk = fread($stream, min(65536, $length));
if ($chunk === false || $chunk === '') {
break;
}
echo $chunk;
flush();
$length -= strlen($chunk);
}
} finally {
fclose($stream);
}
}
}