koel/app/Services/Streamer/Adapters/PhpStreamerAdapter.php

48 lines
1.8 KiB
PHP
Raw Normal View History

2015-12-13 04:42:28 +00:00
<?php
2024-02-24 07:28:49 +00:00
namespace App\Services\Streamer\Adapters;
2015-12-13 04:42:28 +00:00
2024-02-24 07:28:49 +00:00
use App\Models\Song;
2018-08-30 02:53:18 +00:00
use DaveRandom\Resume\FileResource;
use DaveRandom\Resume\InvalidRangeHeaderException;
use DaveRandom\Resume\NonExistentFileException;
use DaveRandom\Resume\RangeSet;
use DaveRandom\Resume\ResourceServlet;
use DaveRandom\Resume\SendFileFailureException;
use DaveRandom\Resume\UnreadableFileException;
use DaveRandom\Resume\UnsatisfiableRangeException;
2019-06-30 15:26:27 +00:00
use Symfony\Component\HttpFoundation\Response;
2018-08-30 02:53:18 +00:00
2020-12-22 20:11:22 +00:00
use function DaveRandom\Resume\get_request_header;
2024-02-24 07:28:49 +00:00
class PhpStreamerAdapter extends LocalStreamerAdapter
2015-12-13 04:42:28 +00:00
{
2024-02-24 07:28:49 +00:00
public function stream(Song $song, array $config = []): void
2015-12-13 04:42:28 +00:00
{
2018-08-30 02:53:18 +00:00
try {
2024-02-24 07:28:49 +00:00
$path = $song->storage_metadata->getPath();
$rangeHeader = get_request_header('Range');
// On Safari, "Range" header value can be "bytes=0-1" which breaks streaming.
$rangeHeader = $rangeHeader === 'bytes=0-1' ? 'bytes=0-' : $rangeHeader;
$rangeSet = RangeSet::createFromHeader($rangeHeader);
2024-02-24 07:28:49 +00:00
$resource = new FileResource($path, mime_content_type($path));
2018-08-30 02:53:18 +00:00
(new ResourceServlet($resource))->sendResource($rangeSet);
2022-08-08 16:00:59 +00:00
} catch (InvalidRangeHeaderException) {
2019-06-30 15:26:27 +00:00
abort(Response::HTTP_BAD_REQUEST);
2022-08-08 16:00:59 +00:00
} catch (UnsatisfiableRangeException) {
2019-06-30 15:26:27 +00:00
abort(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
2022-08-08 16:00:59 +00:00
} catch (NonExistentFileException) {
2019-06-30 15:26:27 +00:00
abort(Response::HTTP_NOT_FOUND);
2022-08-08 16:00:59 +00:00
} catch (UnreadableFileException) {
2019-06-30 15:26:27 +00:00
abort(Response::HTTP_INTERNAL_SERVER_ERROR);
2018-08-30 02:53:18 +00:00
} catch (SendFileFailureException $e) {
2019-06-30 15:26:27 +00:00
abort_unless(headers_sent(), Response::HTTP_INTERNAL_SERVER_ERROR);
2018-08-30 02:53:18 +00:00
echo "An error occurred while attempting to send the requested resource: {$e->getMessage()}";
2015-12-13 04:42:28 +00:00
}
exit;
}
}