MediaTranscodeJob.php 2.25 KB
<?php

namespace App\Jobs;

use AlibabaCloud\SDK\Mts\V20140618\Models\SubmitJobsRequest;
use App\Helpers\UploadHelper;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class MediaTranscodeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected string $endpoint;

    protected string $bucket;

    protected string $object;

    protected string $location;

    protected array $outPut = [];

    /**
     * Create a new job instance.
     *
     * @param string              $url
     * @param array<string,mixed> $outputs
     */
    public function __construct(string $url, array $outputs)
    {
        $this->endpoint = UploadHelper::getOssEndpoint(false);
        $this->bucket   = UploadHelper::getOssBucket();
        $this->object   = UploadHelper::urlToPath($url);
        $this->location = Str::before($this->endpoint, '.');
        $this->outPut   = Arr::isList($outputs) ? $outputs : [$outputs];
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \JsonException
     */
    public function handle(): void
    {
        if (filled($this->outPut)) {
            $submitJobRequest = new SubmitJobsRequest([
                "input"          => json_encode($this->getInputOption(), JSON_THROW_ON_ERROR),
                "outputs"        => json_encode($this->outPut, JSON_THROW_ON_ERROR),
                "outputBucket"   => $this->bucket,
                "outputLocation" => $this->location,
                "pipelineId"     => config('services.oss.mts.pipeline.default')
            ]);

            $data = UploadHelper::getMtsClient()->submitJobs($submitJobRequest);

            foreach ($data->body->jobResultList->jobResult as $item) {
                Redis::client()->sAdd('media_transcode', $item->job->jobId);
            }
        }
    }

    /**
     * @return array<string,string>
     */
    protected function getInputOption(): array
    {
        return ["Bucket" => $this->bucket, 'Object' => $this->object, 'Location' => $this->location];
    }
}