feat: use getID3 for audio upload validation

This commit is contained in:
Phan An 2022-08-03 23:02:07 +02:00
parent edb3a548ec
commit 16c4fdb8ec
No known key found for this signature in database
GPG key ID: A81E4477F0BB6FDC
3 changed files with 38 additions and 6 deletions

View file

@ -3,6 +3,7 @@
namespace App\Http\Requests\API; namespace App\Http\Requests\API;
use App\Http\Requests\Request; use App\Http\Requests\Request;
use App\Rules\SupportedAudioFile;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
/** @property UploadedFile $file */ /** @property UploadedFile $file */
@ -12,11 +13,7 @@ class UploadRequest extends Request
public function rules(): array public function rules(): array
{ {
return [ return [
'file' => [ 'file' => ['required', 'file', new SupportedAudioFile()],
'required',
'file',
'mimes:mp3,mpga,aac,flac,ogg,oga,opus',
],
]; ];
} }
} }

View file

@ -0,0 +1,35 @@
<?php
namespace App\Rules;
use getID3;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
use Throwable;
use Webmozart\Assert\Assert;
class SupportedAudioFile implements Rule
{
private const SUPPORTED_FORMATS = ['mp3', 'aac', 'ogg', 'flac', 'wav'];
/** @param UploadedFile $value */
public function passes($attribute, $value): bool
{
try {
Assert::oneOf(
Arr::get((new getID3())->analyze($value->getRealPath()), 'fileformat'),
self::SUPPORTED_FORMATS
);
return true;
} catch (Throwable) {
return false;
}
}
public function message(): string
{
return 'Unsupported audio file';
}
}

View file

@ -79,7 +79,7 @@ class MediaSyncService
->ignoreDotFiles((bool) config('koel.ignore_dot_files')) // https://github.com/koel/koel/issues/450 ->ignoreDotFiles((bool) config('koel.ignore_dot_files')) // https://github.com/koel/koel/issues/450
->files() ->files()
->followLinks() ->followLinks()
->name('/\.(mp3|ogg|m4a|flac)$/i') ->name('/\.(mp3|wav|ogg|m4a|flac)$/i')
->in($path) ->in($path)
); );
} }