Files
wticreatorstudio/Modules/StudioPlus/Services/DownloadService.php
T

109 lines
3.3 KiB
PHP

<?php
namespace Modules\StudioPlus\Services;
use Modules\StudioPlus\Entities\StudioPlusVideo;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Config;
use Google\Cloud\Storage\StorageClient;
use Illuminate\Support\Facades\Response;
class DownloadService
{
private $storageClient;
private $bucketName;
private $googleApiEndpoint;
private $bucket;
public function __construct()
{
$this->storageClient = new StorageClient([
'keyFile' => json_decode(file_get_contents(module_path('StudioPlus', 'google-cloud-platform.json')), true)
]);
$this->bucketName = Config::get('studioplus.bucket_name');
$this->googleApiEndpoint = Config::get('studioplus.google_api_endpoint');
$this->bucket = $this->storageClient->bucket($this->bucketName);
}
public function download($id)
{
$video = StudioPlusVideo::find($id);
if ($video) {
if ($video->upload_status !== StudioPlusVideo::UPLOAD_STATUS_COMPLETE && str_contains($video->video_url, 'temp')) {
$result = "CreatorStudio/temp/upload/{$video->id}/result.mp4";
if (Storage::exists($result)) {
return $result;
}
}
$temp_path = $this->getTempLocalStoragePath($id);
Storage::deleteDirectory($temp_path);
Storage::put("$temp_path/downloading.dat", $id);
$this->downloadFromGCP($video, storage_path("app/$temp_path"));
return "$temp_path/{$video->filename}";
}
return false;
}
public function downloadAsStream($id)
{
$video = StudioPlusVideo::find($id);
if ($video) {
$bucket = $this->storageClient->bucket($this->bucketName);
$object = $bucket->object($video->getRawOriginal('video_url'));
$stream = $object->downloadAsStream();
return [
'object' => $object,
'stream' => $stream,
'video' => $video
];
}
}
public function downloadFromGCP(StudioPlusVideo $studioPlusVideo, string $destinationPath)
{
try {
if (!File::exists($destinationPath)) {
File::makeDirectory($destinationPath);
}
$video = "$destinationPath/{$studioPlusVideo->filename}";
if (File::exists($video)) {
File::delete($video);
}
$bucket = $this->storageClient->bucket($this->bucketName);
$object = $bucket->object($studioPlusVideo->getRawOriginal('video_url'));
$object->downloadToFile("$destinationPath/{$studioPlusVideo->filename}");
return $video;
} catch (\Exception $ex) {
logger($ex->getMessage());
return $ex->getMessage();
}
}
public function getDownloadObject(StudioPlusVideo $video)
{
$bucket = $this->storageClient->bucket($this->bucketName);
$object = $bucket->object($video->getRawOriginal('video_url'));
return $object;
}
public function getTempLocalStoragePath($id)
{
return "CreatorStudio/temp/downloads/videos/$id";
}
}