46 lines
1.7 KiB
PHP
46 lines
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Content\Media;
|
|
use support\Request;
|
|
use support\Response;
|
|
|
|
final class MediaController
|
|
{
|
|
public function file(Request $request, string $name): Response
|
|
{
|
|
$media = Media::find($name);
|
|
$path = Media::directory() . '/' . $name;
|
|
if (!$media || !is_file($path)) {
|
|
return new Response(404);
|
|
}
|
|
|
|
$length = (int) $media['size'];
|
|
$headers = [
|
|
'Content-Type' => $media['mime'], 'X-Content-Type-Options' => 'nosniff',
|
|
'Content-Security-Policy' => "default-src 'none'; sandbox",
|
|
'Cache-Control' => 'public, max-age=31536000, immutable',
|
|
'Access-Control-Allow-Origin' => '*', 'Accept-Ranges' => 'bytes',
|
|
];
|
|
$range = $request->header('range');
|
|
if ($range === null) {
|
|
return (new Response(200, $headers + ['Content-Length' => (string) $length]))->withFile($path);
|
|
}
|
|
if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || $parts[1] === '' && $parts[2] === '') {
|
|
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
|
|
}
|
|
$start = $parts[1] === '' ? max(0, $length - (int) $parts[2]) : (int) $parts[1];
|
|
$end = $parts[1] === '' || $parts[2] === '' ? $length - 1 : min($length - 1, (int) $parts[2]);
|
|
if ($end < $start) {
|
|
return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
|
|
}
|
|
$count = $end - $start + 1;
|
|
|
|
return (new Response(206, $headers + ['Content-Length' => (string) $count, 'Content-Range' => "bytes $start-$end/$length"]))
|
|
->withFile($path, $start, $count);
|
|
}
|
|
}
|