Skip to content

Instantly share code, notes, and snippets.

@bzz0217
Created May 7, 2016 17:38
Show Gist options
  • Save bzz0217/1e9d2a2b7585133f7d49a40168e95e91 to your computer and use it in GitHub Desktop.
Save bzz0217/1e9d2a2b7585133f7d49a40168e95e91 to your computer and use it in GitHub Desktop.
動画ダウンローダ - youtube-dlで動画をサーバに保存・進捗状況を出力
<?php
/*
* youtube-dlコマンド実行と進捗状況の取得
*/
class youtube_dl_run_progress{
//外部コマンド設定
public static $config = array(
'time' => '',
'output_path' => '',
'url' => ''
);
public function command_escape(){
self::$config['time'] = escapeshellarg(self::$config['time']);
self::$config['output_path'] = escapeshellarg(self::$config['output_path']);
self::$config['url'] = escapeshellarg(self::$config['url']);
}
/*
* 出力バッファを送信
*/
public function output_buffer(){
ob_flush();
flush();
}
/*
* youtube-dlコマンド実行・進捗ログ取得・進捗バー反映
* @param string cmd コマンド
*/
public function progress_output(){
//$this->command_escape();
$cmd = '/usr/bin/youtube-dl -o "';
$cmd .= self::$config['output_path'];
$cmd .= '%(id)s_' . self::$config['time'] . '.%(ext)s" "';
$cmd .= self::$config['url'] . '" 2>&1';
$handle = popen($cmd,'r');
$log = fgets($handle);
$download_url = "";
while(!feof($handle)) {
//進捗ログ例
//[dailymotion] xxxxx: Downloading webpage
//[dailymotion] xxxxx: Downloading m3u8 information
//[download] Resuming download at byte 13012663
//[download] Destination: /var/www/html/xxxxxx/movie/xxxxxx_20160507.mp4
//[download] 8.3% of 365.54MiB at 182.80KiB/s ETA 31:17
$log = fgets($handle);
//[download] Destination: [OUTPUT_FILE]
$stream_get_line_start_pattern = "{Destination: /var/www/html/(.*)$}";
if(preg_match($stream_get_line_start_pattern, $log, $path)){
$download_url = "http://kzz.bz/" . $path[1];
//1行ずつ指定文字列まで取得
$stream_loop_pattern = "[download]";
//[download] [進捗率] of [総ダウンロード容量] at [秒間ダウンロード容量]/s ETA [残時間]
while($log = stream_get_line($handle, 1024, $stream_loop_pattern)){
if (!empty($log)){
$this->output_buffer();
$progress_pattern = "{([\d|\.]+)% of (.*?) at (.*?) ETA ([\d|:]+)}";
preg_match($progress_pattern, $log, $res);
if (!empty($res)){
echo <<<EOF
<script>
$('#progress_bar').val("{$res[1]}");
$('#output').html("{$res[1]}%");
$('#full_time').html("{$res[4]}");
$('#dl_speed').html("{$res[3]}");
$('#filesize').html("{$res[2]}");
</script>
EOF;
}
if(preg_match('/100%/', $log)){
echo <<<EOF
<script>
$('#bar_area').html("完了");
</script>
EOF;
break;
}
}
}
}
}
pclose($handle);
return $download_url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment