<?php
header("Content-Type: text/html;  charset=utf-8",true);
header('Access-Control-Allow-Origin: *');
ini_set("memory_limit", "1024M");
ini_set("max_execution_time", 1800);

function protecao($dados) {

$dados = str_replace(";","",$dados);
$dados = str_replace("rm%20-fr%20","",$dados);
$dados = str_replace("rm -fr","",$dados);
$dados = str_replace("rm -fr","",$dados);
$dados = str_replace("rm -f","",$dados);
$dados = str_replace("rm -R","",$dados);

return $dados;
}

// Validaes
$login = protecao($_GET["login"]);
$video = protecao($_GET["video"]);
$pasta = protecao($_GET["pasta"]);

function liveExecuteCommand($cmd)
{

    while (@ ob_end_flush());

    $proc = popen("$cmd 2>&1", 'r');

    $live_output     = "";
    $complete_output = "";
    $linha = 1;
    while (!feof($proc))
    {
        $live_output     = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo str_replace("/home/streaming/".$login."/","",$live_output)."<br><script>window.scrollBy(0,100);</script>";
        @ flush();
    }

    pclose($proc);

}

if($_GET["formato"] == "720p") {
$formato = "22";
} else {
$formato = "18";
}

@system("chmod 777 /home/streaming/".$login."/".$pasta."");

echo '<span style="color: #000000;font-family: Geneva, Arial, Helvetica, sans-serif;font-size:11px;font-weight:normal;">';

$path = ($pasta == "/") ? "/home/streaming/".$login : "/home/streaming/".$login."/".$pasta;

$nome_video = str_replace("\n", "", shell_exec('/usr/local/bin/youtube-dl --windows-filenames --restrict-filenames --get-filename -o "%(title)s.mp4" https://www.youtube.com/watch?v='.$video));
$arquivo_final = $path."/".str_replace(".mp4", "", $nome_video).".mp4";

echo "Video <strong>".str_replace("_", " ", $nome_video)."<br></strong><script>window.scrollBy(0,100);</script>";
echo "Fazendo Download...<br><script>window.scrollBy(0,100);</script>";

liveExecuteCommand("/usr/local/bin/youtube-dl --windows-filenames --restrict-filenames --no-cache-dir --output '".$arquivo_final."' --format ".$formato." https://www.youtube.com/watch?v=".$video."");

@system("/bin/chown streaming.streaming ".$arquivo_final."");

if(file_exists($arquivo_final)) {

echo "<span style=\"color: #009900;font-family: Geneva, Arial, Helvetica, sans-serif;font-size:11px;font-weight:normal;\"><strong>OK!</strong><br><strong>Video:</strong> ".str_replace("/home/streaming/".$login."","",$arquivo_final)."<br></span>";

} else {
echo "<span style=\"color: #FF0000;font-family: Geneva, Arial, Helvetica, sans-serif;font-size:11px;font-weight:normal;\">Error! Por favor tente novamente. Please try again.</span><script>window.scrollBy(0,100);</script>";
}

echo '</span><script>window.scrollBy(0,100);</script>';
?>
