koel/app/Services/UploadService.php

67 lines
1.9 KiB
PHP
Raw Normal View History

2020-06-07 20:43:04 +00:00
<?php
namespace App\Services;
use App\Exceptions\MediaPathNotSetException;
use App\Exceptions\SongUploadFailedException;
use App\Models\Setting;
use App\Models\Song;
use Illuminate\Http\UploadedFile;
2020-12-22 20:11:22 +00:00
use function Functional\memoize;
2020-06-07 20:43:04 +00:00
class UploadService
{
private const UPLOAD_DIRECTORY = '__KOEL_UPLOADS__';
2022-06-10 10:47:46 +00:00
public function __construct(private FileSynchronizer $fileSynchronizer)
2020-06-07 20:43:04 +00:00
{
}
public function handleUploadedFile(UploadedFile $file): Song
{
$targetFileName = $this->getTargetFileName($file);
$file->move($this->getUploadDirectory(), $targetFileName);
2020-12-22 20:11:22 +00:00
$targetPathName = $this->getUploadDirectory() . $targetFileName;
$result = $this->fileSynchronizer->setFile($targetPathName)->sync();
2020-06-07 20:43:04 +00:00
2022-07-29 11:08:24 +00:00
if ($result->isError()) {
2020-06-07 20:43:04 +00:00
@unlink($targetPathName);
2022-07-29 11:08:24 +00:00
throw new SongUploadFailedException($result->error);
2020-06-07 20:43:04 +00:00
}
return $this->fileSynchronizer->getSong();
}
private function getUploadDirectory(): string
{
return memoize(static function (): string {
2020-06-07 20:43:04 +00:00
$mediaPath = Setting::get('media_path');
if (!$mediaPath) {
throw new MediaPathNotSetException();
}
2020-12-22 20:11:22 +00:00
return $mediaPath . DIRECTORY_SEPARATOR . self::UPLOAD_DIRECTORY . DIRECTORY_SEPARATOR;
});
2020-06-07 20:43:04 +00:00
}
private function getTargetFileName(UploadedFile $file): string
{
// If there's no existing file with the same name in the upload directory, use the original name.
// Otherwise, prefix the original name with a hash.
// The whole point is to keep a readable file name when we can.
2020-12-22 20:11:22 +00:00
if (!file_exists($this->getUploadDirectory() . $file->getClientOriginalName())) {
2020-06-07 20:43:04 +00:00
return $file->getClientOriginalName();
}
2020-12-22 20:11:22 +00:00
return $this->getUniqueHash() . '_' . $file->getClientOriginalName();
2020-06-07 20:43:04 +00:00
}
private function getUniqueHash(): string
{
return substr(sha1(uniqid()), 0, 6);
}
}