koel/app/Services/DownloadService.php

53 lines
1.5 KiB
PHP
Raw Normal View History

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