<?php
require_once("admin/inc/protecao-final.php");
require_once("admin/inc/classe.ssh.php");

@mysqli_query($conexao,"ALTER TABLE `lives` ADD `rtmp` VARCHAR(255) NOT NULL;");
@mysqli_query($conexao,"ALTER TABLE `lives` ADD `chave` VARCHAR(255) NOT NULL;");

$dados_config = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM configuracoes"));
$dados_stm = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM streamings where login = '".$_SESSION["login_logado"]."'"));
$dados_servidor = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM servidores where codigo = '".$dados_stm["codigo_servidor"]."'"));

date_default_timezone_set($dados_stm["timezone"]);

if($dados_servidor["nome_principal"]) {
$servidor = strtolower($dados_servidor["nome_principal"]).".".$dados_config["dominio_padrao"];
} else {
$servidor = strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"];
}

$source_http = "https://".$servidor."/".$dados_stm["login"]."/".$dados_stm["login"]."/playlist.m3u8";
$source_rtmp = "rtmp://".$servidor.":1935/".$dados_stm["login"]."/".$dados_stm["login"]."";

if(query_string('1')) {

$codigo = code_decode(query_string('1'),"D");

$dados_live = mysqli_fetch_array(mysqli_query($conexao,"SELECT * FROM lives where codigo = '".$codigo."'"));

// Conexao SSH
$ssh = new SSH();
$ssh->conectar($dados_servidor["ip"],$dados_servidor["porta_ssh"]);
$ssh->autenticar("root",code_decode($dados_servidor["senha"],"D"));

$ssh->executar('nohup /usr/local/bin/ffmpeg -re -i '. $source_http.' -c:v copy -c:a copy -bsf:a aac_adtstoasc -preset ultrafast -strict experimental -threads 1 -f flv "'.$dados_live["rtmp"].'" > /dev/null & echo $!');

sleep(5);

$resultado = $ssh->executar("/bin/ps aux | /bin/grep ffmpeg | /bin/grep playlist.m3u8 | /bin/grep ".$dados_stm["login"]." | /bin/grep ".$dados_live["tipo"]." | /usr/bin/wc -l");

if($resultado > 0) {

$data_inicio = date("Y-m-d H:i:s");

mysqli_query($conexao,"Update lives set status = '1', data_inicio = '".$data_inicio."' where codigo = '".$dados_live["codigo"]."'");

// Cria o sessão do status das ações executadas e redireciona.
//$_SESSION["status_acao"] .= "<div class='alert alert-success text-center' role='alert'>Live iniciada com sucesso no servidor de streaming.</div>";
//$_SESSION["status_acao"] .= "<div class='alert alert-warning text-center' role='alert'>Agora voce deve iniciar a transmissao no site.</div>";
$_SESSION["status_acao"] .= "<div class='alert alert-success text-center' role='alert'>Live se inici&oacute; con exito.</div>";
$_SESSION["status_acao"] .= "<div class='alert alert-warning text-center' role='alert'>Ahora debes empezar la transmisi&oacute;n en la red social.</div>";

} else {

mysqli_query($conexao,"Update lives set status = '0' where codigo = '".$dados_live["codigo"]."'");

// Cria o sessão do status das ações executadas e redireciona.
//$_SESSION["status_acao"] = "<div class='alert alert-danger text-center' role='alert'>Nao foi possivel iniciar a live, tente novamente.</div>";
$_SESSION["status_acao"] = "<div class='alert alert-danger text-center' role='alert'>No se puede iniciar la transmisi&oacute;n en vivo, int&eacute;ntalo de nuevo.</div>";
}

header("Location: /gerenciar-lives");
exit();

}


if($_POST) {

// Verifica se todos os campos foram preenchidos
if(empty($_POST["servidor_rtmp"]) || empty($_POST["chave"])) {
$_SESSION["status_acao"] = "<div class='alert alert-danger text-center' role='alert'>Voc&ecirc; deixou campos em branco.</div>";
header("Location: /gerenciar-lives");
exit();
}

$servidor_rtmp = (substr($_POST["servidor_rtmp"],-1) == "/") ? $_POST["servidor_rtmp"].$_POST["chave"] : $_POST["servidor_rtmp"]."/".$_POST["chave"];
$data_inicio = date("Y-m-d H:i:s");

mysqli_query($conexao,"INSERT INTO lives (codigo_stm,data_inicio,tipo,rtmp,status) VALUES ('".$dados_stm["codigo"]."','".$data_inicio."','".$_POST["tipo"]."','".$servidor_rtmp."','1')");
$codigo_live = mysqli_insert_id($conexao);

// Conexao SSH
$ssh = new SSH();
$ssh->conectar($dados_servidor["ip"],$dados_servidor["porta_ssh"]);
$ssh->autenticar("root",code_decode($dados_servidor["senha"],"D"));

$ssh->executar('nohup /usr/local/bin/ffmpeg -re -i '. $_POST["source"].' -c:v copy -c:a copy -bsf:a aac_adtstoasc -preset ultrafast -strict experimental -threads 1 -f flv "'.$servidor_rtmp.'" > /dev/null & echo $!');

sleep(5);

$resultado = $ssh->executar("/bin/ps aux | /bin/grep ffmpeg | /bin/grep playlist.m3u8 | /bin/grep ".$dados_stm["login"]." | /bin/grep ".$_POST["tipo"]." | /usr/bin/wc -l");

if($resultado > 0) {

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] .= "<div class='alert alert-success text-center' role='alert'>Live iniciada com sucesso no servidor de streaming.</div>";
$_SESSION["status_acao"] .= "<div class='alert alert-warning text-center' role='alert'>Agora voce deve iniciar a transmissao no site.</div>";

} else {

mysqli_query($conexao,"Update lives set status = '0' where codigo = '".$codigo_live."'");

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = "<div class='alert alert-danger text-center' role='alert'>Nao foi possivel iniciar a live, tente novamente.</div>";
}

header("Location: /gerenciar-lives");
exit();

}

if($dados_stm["idioma_painel"] == "pt-br") {
$lang_sortable = "Portuguese-Brasil";
} elseif($dados_stm["idioma_painel"] == "en-us") {
$lang_sortable = "English";
} else {
$lang_sortable = "Spanish";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Streaming <?php echo $dados_stm["login"]; ?></title>
  <link rel="stylesheet" href="/inc/materialdesignicons.min.css">
  <link rel="stylesheet" href="/inc/font-awesome.min.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.base.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.addons.css">  
  <?php if($dados_stm["tema_dark"] == "sim") { ?>
  <link rel="stylesheet" href="/inc/theme-dark.css">
  <?php } else { ?>
  <link rel="stylesheet" href="/inc/theme.css">
  <?php } ?>
  <link rel="shortcut icon" href="/img/favicon.ico" />
  <script type="text/javascript" src="/inc/ajax-streaming.js"></script>
  <script type="text/javascript" src="/inc/javascript.js"></script>
</head>
<body>
  <div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
        <?php if($dados_revenda["url_logo"]) { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><img id="logo" src="<?php echo $dados_revenda["url_logo"]; ?>" title="Painel" height="60" border="0"></a>
        <?php } else { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><span>Painel Streaming</span></a>
        <?php } ?>
        <a class="navbar-brand brand-logo-mini" href="/dashboard"><i class="fa fa-video-camera text-muted"></i></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end justify-content-lg-start">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item nav-profile dropdown show">
            <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" id="profileDropdown" aria-expanded="true">
              <i class="fa fa-power-off f-18 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_botao_titulo_ligar']; ?>/<?php echo $lang['lang_botao_titulo_desligar']; ?>"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="profileDropdown">
              <a class="dropdown-item text-success" href="javascript:ligar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> Streaming</a>
              <a class="dropdown-item text-warning" href="javascript:reiniciar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> Streaming</a>
              <?php if($dados_stm["srt_status"] == 'sim') { ?>
              <a class="dropdown-item text-primary" href="javascript:reiniciar_srt('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> SRT</a>
              <?php } ?>
            </div>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown" aria-expanded="false">
              <i class="mdi mdi-bell f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?>"></i>
              <?php if($total_avisos_exibir > 0) { ?><span class="count bg-success"><?php echo $total_avisos_exibir; ?></span><?php } ?>           
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
              <a class="dropdown-item">
                <p class="mb-0 font-weight-normal float-left"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></p>
              </a>
              <div class="dropdown-divider"></div>
              <?php carregar_avisos_streaming($conexao,$dados_stm["porta"],$dados_servidor["codigo"]); ?>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/sair"><i class="mdi mdi-logout f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="Sair/logout"></i></a>
          </li>
          <li>
            <button type="button" class="btn btn-info" id="status-streaming" onClick="status_streaming('<?php echo $login_code; ?>');" style="margin: 10px;min-width: 150px; min-height: 40px"><i class="fa fa-refresh"></i></button>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
      </div>
    </nav>
    <div class="container-fluid page-body-wrapper">
      <?php require_once("menu.php"); ?>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
          <div id="local-status-acoes"><?php echo $_SESSION['status_acao'];unset($_SESSION['status_acao']); ?></div>
          <div class="row">            

            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header>Lives</header>
                  </div>
                <div class="card-body">
                    <table id="data_table" class="table dataTable no-footer" role="grid" aria-describedby="data_table_info">
                                                <thead>
                                                    <tr role="row">
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending">Live</th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending">Inicio</th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending">Dura&ccedil;&atilde;o</th>
                                                        <th class="sorting_asc" tabindex="0" aria-controls="data_table" rowspan="1" colspan="1" aria-sort="ascending">Status</th>
                                                        <th>Opciones</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
<?php
$sql = mysqli_query($conexao,"SELECT * FROM lives where codigo_stm = '".$dados_stm["codigo"]."' ORDER by data_inicio DESC");
while ($dados_live = mysqli_fetch_array($sql)) {

$duracao_segundos1 = strtotime(date("Y-m-d H:i:s")) - strtotime($dados_live["data_inicio"]);
$duracao_segundos2 = strtotime($dados_live["data_fim"]) - strtotime($dados_live["data_inicio"]);

$duracao = ($dados_live["status"] == "0") ? tempo_conectado($duracao_segundos2) : tempo_conectado($duracao_segundos1);

$status = ($dados_live["status"] == "1") ? "Transmitiendo" : "Terminado";

$live_code = code_decode($dados_live["codigo"],"E");

echo "<tr id='".$live_code."'>
<td height='25' align='left' scope='col' class='texto_padrao'>&nbsp;".ucfirst($dados_live["tipo"])."</td>
<td height='25' align='left' scope='col' class='texto_padrao'>&nbsp;".formatar_data($dados_stm["formato_data"], $dados_live["data_inicio"], $dados_stm["timezone"])."</td>
<td height='25' align='left' scope='col' class='texto_padrao'>&nbsp;".$duracao."</td>
<td height='25' align='left' scope='col' class='texto_padrao'>&nbsp;".$status."</td>
<td height='25' align='left' scope='col' class='texto_padrao'>";
if($dados_live["status"] == "1") {
echo "<a href='javascript:finalizar_live(\"".$live_code."\");'><i class='fa fa-stop-circle-o f-18 text-yellow'></i></a>&nbsp;&nbsp;";
} else {
echo "<a href='/gerenciar-lives/".$live_code."'><i class='fa fa-play-circle-o f-18 text-green'></i></a>&nbsp;&nbsp;";
}
echo "<a href='javascript:remover_live(\"".$live_code."\");'><i class='fa fa-trash-o f-18 text-red'></i></a>";
echo "</td>
</tr>";

}
?>
                                                </tbody>
                                            </table>
                </div>
              </div>
            </div>

            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header>Iniciar Live</header>
                  </div>
                <div class="card-body">
                    <form method="post" action="/gerenciar-lives" name="lives">
                                        <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                          <tr>
                                            <td width="150" height="50" align="left" style="padding-left:5px;"><strong>Tipo Live</strong></td>
                                            <td align="left">
                                            <select name="tipo" class="form-control" id="tipo" style="width:100%;" onchange="tipo_live(this.value);">
                                                <option value="youtube" selected="selected">YouTube</option>
                                                <option value="facebook">FaceBook</option>
                                                <option value="twitch">Twitch</option>
                                                <option value="periscope">Periscope</option>
                                                <option value="vimeo">Vimeo</option>
                                                <option value="steam">Steam Valve</option>
                                            </select>
                                        </td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><strong>Source</strong></td>
                                            <td align="left">
                                            <select name="source" class="form-control" id="source" style="width:100%;">
                                                <option value="<?php echo $source_http; ?>" selected="selected">HTTP/m3u8</option>
                                                <option value="<?php echo $source_rtmp; ?>">RTMP</option>
                                            </select>
                                            </td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><strong>Servidor RTMP</strong></td>
                                            <td align="left"><input name="servidor_rtmp" type="text" class="form-control" id="servidor_rtmp" style="width:100%;" value="rtmp://a.rtmp.youtube.com/live2/" /></td>
                                          </tr>
                                          <tr>
                                            <td height="50" align="left" style="padding-left:5px;"><strong>Clave</strong></td>
                                            <td align="left"><input name="chave" type="text" class="form-control" id="chave" style="width:100%;" /></td>
                                          </tr>
                                          <tr>
                                            <td height="50" colspan="2" align="right"><button type="button" class="btn btn-info" onClick="document.lives.submit();">Iniciar Live</button></td>
                                          </tr>
                                        </table>
                                        </form>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
      <!-- modal -->
      <div class="modal fade" id="avisos" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body" id="avisos-conteudo"><img src="/img/ajax-loader.gif" align="center" /></div>
            </div>
        </div>
        </div>
                
        <div class="modal fade" id="log-sistema" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body" id="log-sistema-conteudo" style="text-align:center"><img src="/img/ajax-loader.gif" /></div>
            </div>
        </div>
      </div>
    </div>
  </div>
  <script src="/inc/vendor.bundle.base.js"></script>
  <script src="/inc/vendor.bundle.addons.js"></script>
  <script src="/inc/theme.js"></script>
  <script>
  status_streaming('<?php echo $login_code; ?>');
  setInterval("status_streaming('<?php echo $login_code; ?>')",60000);
        $(document).ready(function() {

            var table = $('#data_table').DataTable({
                responsive: true,
                "lengthMenu": [[25, 50, 100, 200, -1], [25, 50, 100, 200, "Todos/All"]],
                language: {
                    "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/<?php echo $lang_sortable; ?>.json"
                },
                select: true,
                'aoColumnDefs': [{
                    'bSortable': false,
                    'aTargets': ['nosort']
                }]
            });
            $('#data_table tbody').on( 'click', 'tr', function() {
                if ( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected');
                }
                else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
            });

        });

        function tipo_live(tipo) {

            if(tipo == "youtube") {
            document.getElementById("servidor_rtmp").value = "rtmp://a.rtmp.youtube.com/live2/";
            } else if(tipo == "twitch") {
            document.getElementById("servidor_rtmp").value = "rtmp://live-dfw.twitch.tv/app/";
            } else if(tipo == "periscope") {
            document.getElementById("servidor_rtmp").value = "rtmp://ca.pscp.tv:80/x/";
            } else if(tipo == "vimeo") {
            document.getElementById("servidor_rtmp").value = "rtmp://rtmp.cloud.vimeo.com/live/";
            } else if(tipo == "steam") {
            document.getElementById("servidor_rtmp").value = "rtmp://ingest-any-ord1.broadcast.steamcontent.com/app/";
            } else {
            document.getElementById("servidor_rtmp").value = "rtmps://live-api-s.facebook.com:443/rtmp/";   
            }

        }
        function executar_acao_gerenciar_lives( codigo, acao ) {
    
          document.getElementById("local-status-acoes").innerHTML = '<div class="alert alert-info text-center" role="alert"><img src="/img/ajax-loader.gif" /></div>';
          $("#local-status-acoes").show();
          
          var http = new Ajax();
          http.open("GET", "/gerenciar-lives/"+acao+"/"+codigo , true);
          http.onreadystatechange = function() {
            
          if(http.readyState == 4) {
          
            resultado = http.responseText;
            
            document.getElementById("local-status-acoes").innerHTML = resultado;
            $("#local-status-acoes").delay(15000).fadeOut(300);
            if(acao == "remover") {
                $('#' + $.escapeSelector(codigo)).remove();
            }
            
          }
          
          }
          http.send(null);
          delete http;
        }
  </script>
</body>
</html>