使用 Laravel 将 youtube-dl 输出流式传输到 S3

Asw*_*mar 5 php youtube-dl laravel

背景:

我在 Laravel 5.3 上

我正在使用 下载 YouTube 视频youtube-dl,使用Symfony Process

$command = '/usr/local/bin/youtube-dl -o '.$new_file_path.' '.$youtube_id;
$process = new Process($command);
$process->setTimeout(null);
$process->run();
Run Code Online (Sandbox Code Playgroud)

在之后Process的运行,我在预期位置下载的文件。现在我可以将它存储到 S3 如下:

\Storage::disk('s3')->putFile($s3_location, new File($new_file_path));
Run Code Online (Sandbox Code Playgroud)

问题

如您所见,我正在将文件下载到本地存储,然后上传到 S3。如果我可以直接写入 S3,那就太好了。特别是因为两个组件都支持流式处理——Process类可以对输出进行流式处理,而S3 Storage可以存储流,如下:

// Process class supports streamed output
// https://symfony.com/doc/current/components/process.html

// note the '-' after '-o' parameter - it asks youtube-dl to give a stream output, which can be piped in a shell
$process = new Process('/usr/local/bin/youtube-dl -o - '.$youtube_id;);
$process->start();

foreach ($process as $type => $data) {
    if ($process::OUT === $type) {
        echo "\nRead from stdout: ".$data;
    } else { // $process::ERR === $type
        echo "\nRead from stderr: ".$data;
    }
}
Run Code Online (Sandbox Code Playgroud)

和,

// S3 Storage supports streams
// https://laravel.com/docs/5.3/filesystem#storing-files
Storage::put('file.jpg', $resource);
Run Code Online (Sandbox Code Playgroud)

我的问题是 - 有没有办法将Process类的流输出包装为资源/流对象,并将其传递给 S3 存储?

Mas*_*ase 0

更正:该脚本实际上会在可用时上传所有块,因为file_get_contents将继续到达EOF

您需要确保有足够的可用内存,因为脚本不处理可用内存的总大小与视频总大小的关系。

请注意,由于我没有 s3 帐户,因此我并未实际对此进行测试,如果有任何问题需要更正答案,请告诉我。

// create ramdrive
// bash $ mkdir /mnt/ram_disk
// bash $ mount -t tmpfs -o size=1024m new_ram_disk /mnt/ram_disk

$array_of_youtube_ids = ['abc001', 'abc002' , 'abc003'];
$storage_path = '/mnt/ram_disk/';



// start all downloads
$index = 0;
foreach ($array_of_youtube_ids as $id){

    $youtube_dls$index] = new YouTubeDlAsync($storage_path.$id, $id);
    $youtube_dls[$index]->start();
    $index ++;
}


// upload all downloads
$index = 0;
foreach ($array_of_youtube_ids as $id){

    $s3uploads[$index] = new UploadToS3($storage_path.$id, $resource);
    $s3uploads[$index]->start();

    $index ++;
}

// Wait for all downloads to finish
foreach ($youtube_dls as $youtube_dl)
    $youtube_dl->join();

// Wait for all uploads to finish
foreach ($s3uploads as $s3upload)
    $s3upload->join();

class YouTubeDlAsync extends Thread {

    public function __construct($new_file_path, $youtube_id) {
        $command = '/usr/local/bin/youtube-dl -o '.$new_file_path.' '.$youtube_id;
        exec($command);
    }
}

class UploadToS3 extends Thread {

    public function __construct($new_file_path, $resource) {
        Storage::put(file_get_contents('file.jpg'), $resource);
    }
}
Run Code Online (Sandbox Code Playgroud)