koel/app/Services/DownloadService.php

53 lines
1.5 KiB
PHP
Raw Normal View History

2016-06-02 17:53:26 +00:00
<?php
namespace App\Services;
2016-06-04 17:10:29 +00:00
use App\Models\Song;
2017-06-04 01:12:08 +00:00
use App\Models\SongZipArchive;
2024-01-07 12:43:10 +00:00
use Illuminate\Http\Response;
2021-06-05 10:47:56 +00:00
use Illuminate\Support\Collection;
2024-01-07 12:43:10 +00:00
use Illuminate\Support\Facades\File;
2016-06-02 17:53:26 +00:00
2018-08-18 12:27:17 +00:00
class DownloadService
2016-06-02 17:53:26 +00:00
{
2022-07-29 06:47:10 +00:00
public function __construct(private S3Service $s3Service)
2018-08-29 04:06:17 +00:00
{
}
2024-01-10 23:11:45 +00:00
public function getDownloadablePath(Collection $songs): string
2016-06-02 17:53:26 +00:00
{
2024-01-07 12:43:10 +00:00
if ($songs->count() === 1) {
2024-01-10 23:11:45 +00:00
return $this->getLocalPath($songs->first());
2016-06-02 17:53:26 +00:00
}
2018-08-18 10:35:42 +00:00
2024-01-07 12:43:10 +00:00
return (new SongZipArchive())
->addSongs($songs)
->finish()
->getPath();
2016-06-02 17:53:26 +00:00
}
2024-01-10 23:11:45 +00:00
public function getLocalPath(Song $song): string
2016-06-02 17:53:26 +00:00
{
2020-12-22 20:11:22 +00:00
if ($song->s3_params) {
2016-07-11 07:26:39 +00:00
// The song is hosted on Amazon S3.
// We download it back to our local server first.
2018-08-29 04:06:17 +00:00
$url = $this->s3Service->getSongPublicUrl($song);
2024-01-10 00:47:09 +00:00
// @todo decouple http from services
2024-01-07 12:43:10 +00:00
abort_unless((bool) $url, Response::HTTP_NOT_FOUND);
2016-07-11 07:26:39 +00:00
2020-12-22 20:11:22 +00:00
$localPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . basename($song->s3_params['key']);
2018-08-18 10:35:42 +00:00
// The following function requires allow_url_fopen to be ON.
2016-07-11 07:26:39 +00:00
// We're just assuming that to be the case here.
2024-01-10 00:47:09 +00:00
File::copy($url, $localPath);
2016-07-11 07:26:39 +00:00
} else {
// The song is hosted locally. Make sure the file exists.
$localPath = $song->path;
2024-01-07 12:43:10 +00:00
abort_unless(File::exists($localPath), Response::HTTP_NOT_FOUND);
}
2018-08-18 10:35:42 +00:00
return $localPath;
2016-06-02 17:53:26 +00:00
}
}