Skip to content

Commit

Permalink
fix: Upload modal validation
Browse files Browse the repository at this point in the history
wip

remove originalFileName from HandleInertiaRequests.php

Check processing type by Enum

Refactor client side file name handle

update validation

Show specific mimetype on error when not supported

Typos
  • Loading branch information
ChrisToxz committed Jul 22, 2023
1 parent bd1c82f commit 0a29e94
Show file tree
Hide file tree
Showing 11 changed files with 1,575 additions and 142 deletions.
6 changes: 4 additions & 2 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ class Handler extends ExceptionHandler
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
public function register()
{
$this->reportable(function (Throwable $e) {
//
if (app()->bound('sentry')) {
app('sentry')->captureException($e);
}
});
}
}
23 changes: 9 additions & 14 deletions app/Http/Controllers/SlipController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http\Controllers;

use App\Enums\VideoType;
use App\Events\SlipUploaded;
use App\Jobs\CreateSlip;
use App\Jobs\GenerateThumb;
Expand All @@ -10,13 +11,11 @@
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Redirect;
use Validator;

class SlipController extends Controller
{
public function index(Request $request)
{

$slips = Slip::latest()->with('mediable')
->paginate(6)
->withQueryString();
Expand Down Expand Up @@ -45,15 +44,14 @@ public function store(Request $request)
* TODO
* Validation selected type (Cross check with enum)
* Validation check correct mimemtypes that we could accept
* Trigger jobs to save file and run converting if selected
*/

$type = $request->get('type');

$request->validate([
'title' => 'nullable|string|max:1',
'title' => 'nullable|string|max:255',
'description' => 'nullable|string|max:200',
// 'file' => 'file|mimetypes:video/mp4,video/mpeg|max:99999'
'type' => 'required|enum_key:'.VideoType::class
]);

$title = $request->title ?: $request->get('originalFileName');
Expand All @@ -66,25 +64,22 @@ public function store(Request $request)
// Generate Thumbnail
GenerateThumb::dispatchSync($slip, $request->get('file'));
// To the final processing
CreateSlip::dispatch($slip, $request->get('file'), $type);
CreateSlip::dispatch($slip, $request->get('file'), VideoType::fromKey($type));
// Dispatch event to reload Dashboard
SlipUploaded::dispatch();

}


// TODO: Check proper validation for files.
// File size limit? Mimetypes?
public function tempUpload(Request $request)
{
if ($request->file) {
$validator = Validator::make($request->all(), [
$request->validate([
'file' => 'file|mimetypes:video/mp4,video/mpeg|max:999999'
]);
if ($validator->fails()) {
dd('To be done, error handling');
}
}

return Redirect::back()->with([
'originalFileName' => $request->file->getClientOriginalName(),
'tmpPath' => $request->file->store('tmp')
]);
}
Expand All @@ -101,7 +96,7 @@ public function update(Request $request, Slip $slip)
return response()->json(['errors' => $ex->errors()], 422);
}
}

$slip->update($validated);

if ($request->wantsJson()) {
Expand Down
3 changes: 1 addition & 2 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,11 @@ public function share(Request $request): array
'auth' => [
'user' => $request->user(),
],
//Slip upload
'data' => [
'originalFileName' => fn() => $request->session()->get('originalFileName'),
'tmpPath' => fn() => $request->session()->get('tmpPath')
],
'settings' => ['sitename' => app(GeneralSettings::class)->site_name],

'ziggy' => function () use ($request) {
return array_merge((new Ziggy)->toArray(), [
'location' => $request->url(),
Expand Down
45 changes: 26 additions & 19 deletions app/Jobs/CreateSlip.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@
use App\Events\SlipProcessUpdate;
use App\Models\Slip;
use App\Models\Video;
use Exception;
use FFMpeg\Format\Video\X264;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg;
use Symfony\Component\Console\Output\ConsoleOutput;
use Throwable;
use VideoHelper;

class CreateSlip implements ShouldQueue
{
Expand All @@ -29,23 +31,20 @@ class CreateSlip implements ShouldQueue
* Create a new job instance.
*/
public function __construct(
public Slip $slip,
public Slip $slip,
public string $tmpPath,
public int $type
)
{
// TODO: Remove
// $output->writeln($this->job->getJobId());
// $output->writeln($this->job->uuid());
public string $type
) {

}

/**
* Execute the job.
* @throws \Exception
* @throws Exception
*/
public function handle(): void
{
$output = new \Symfony\Component\Console\Output\ConsoleOutput();
$output = new ConsoleOutput();

$streamHash = Str::random(40);
$fileExtension = Str::afterLast($this->tmpPath, '.');
Expand All @@ -71,7 +70,8 @@ public function handle(): void
case VideoType::X264:
$output->writeln("Running X264 process");
$ff = FFMpeg::fromDisk('local')->open($this->tmpPath);
$originalBitrateFormat = (new X264('libmp3lame', 'libx264'))->setKiloBitrate($ff->getVideoStream()->get('bit_rate'));
$originalBitrateFormat = (new X264('libmp3lame',
'libx264'))->setKiloBitrate($ff->getVideoStream()->get('bit_rate'));

$ff->export()->onProgress(function ($percentage, $remaining, $rate) use ($output) {
$output->writeln("Progress: {$percentage} - {$remaining} seconds left at rate: {$rate}");
Expand All @@ -97,29 +97,36 @@ public function handle(): void
});


foreach (\VideoHelper::getSupportedFormats() as $key => $quality) {
foreach (VideoHelper::getSupportedFormats() as $key => $quality) {

if ($ff->getVideoStream()->get('height') >= $quality->height) {
$output->writeln("Quality: {$key} - {$quality->width}x{$quality->height}");
$ff->addFormat((new X264('libmp3lame', 'libx264'))->setKiloBitrate($quality->bitrate), function ($media) use ($quality) {
$media->scale($quality->width, $quality->height);
});
$ff->addFormat((new X264('libmp3lame', 'libx264'))->setKiloBitrate($quality->bitrate),
function ($media) use ($quality) {
$media->scale($quality->width, $quality->height);
});
}
}

$ff->useSegmentFilenameGenerator(function ($name, $format, $key, callable $segments, callable $playlist) {
$ff->useSegmentFilenameGenerator(function (
$name,
$format,
$key,
callable $segments,
callable $playlist
) {
$segments("{$name}--{$format->getKiloBitrate()}-{$key}-%03d.ts");
$playlist("{$name}-{$format->getKiloBitrate()}-{$key}.m3u8");
})
->toDisk('slips')
->save("{$this->slip->token}/{$streamHash}.m3u8");

$video = Video::create(['file' => $streamHash . '.m3u8', 'type' => $this->type]);
$video = Video::create(['file' => $streamHash.'.m3u8', 'type' => $this->type]);
$video->slip()->save($this->slip);

break;
default:
throw new \Exception('Invalid video type.');
throw new Exception('Invalid video type.');
}

// TODO: Getting video details
Expand Down Expand Up @@ -147,7 +154,7 @@ public function failed(Throwable $exception): void
// TODO: Make proper log of failed job including debug information
// maybe spatie/laravel-activitylog?
$this->slip->setStatus(SlipStatus::FAILED());
SlipProcessFinished::dispatch($this->slip, TRUE);
SlipProcessFinished::dispatch($this->slip, true);
SlipProcessUpdate::dispatch($this->slip->token, 'Failed', 0);
}

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"laravel/tinker": "^2.8",
"pbmedia/laravel-ffmpeg": "^8.3",
"pusher/pusher-php-server": "^7.2",
"sentry/sentry-laravel": "^3.6",
"spatie/laravel-settings": "^3.2",
"tightenco/ziggy": "^1.0"
},
Expand Down
Loading

0 comments on commit 0a29e94

Please sign in to comment.