<?php
//ob_start(function($b){if(strpos($b, "<html")!==false) {return str_replace(PHP_EOL,"",$b);} else {return $b;}});
$porta = query_string('1');

if(!is_numeric($porta)) {
die ("Error! Missing data.");
}

$verifica_stm = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM streamings where porta = '".$porta."'"));

if($verifica_stm == 0) {
die ("Error! Missing data.");
}

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

$total_pontos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM multipoint where codigo_stm = '".$dados_stm["codigo"]."'"));

if($total_pontos > 0) {
$ponto = "/1";
} else {
$ponto = "/stream";
}

if(query_string('2') == "musica") {

if($dados_stm["tipo_servidor"] == "icecast") {

   $porta_admin_icecast = $dados_stm["porta"]+1;

   $dados_icecast = @file_get_contents("http://".$dados_servidor["ip"].":".$porta_admin_icecast."/status-json.xsl?mount=".$ponto);

   $dados_json_icecast = json_decode($dados_icecast, true);

   $musica_completa = ($dados_json_icecast["icestats"]["source"]["artist"]) ? $dados_json_icecast["icestats"]["source"]["artist"]." - ".$dados_json_icecast["icestats"]["source"]["title"] : $dados_json_icecast["icestats"]["source"]["title"];

} else {
   $musica_completa = @file_get_contents("http://".$dados_servidor["ip"].":".$dados_stm["porta"]."/currentsong?sid=1");
}

$musica_completa = utf8_decode($musica_completa);
$musica_completa = str_replace("_"," ",$musica_completa);

header('Content-Type: application/json; charset=utf-8');

echo $_GET['callback'].'({"songtitle":"'.$musica_completa.'"})';

exit();
}

$url_proxy_musica_atual = "https://player.".$dados_config["dominio_padrao"]."/musica-atual/".$dados_stm["porta"]."?";
$url_source_streaming = "https://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."";

$array_lang = array(
  "pt" => array("ultimas_musicas" => "&Uacute;ltimas M&uacute;sicas", "pedir_musica" => "Pedir M&uacute;sica", "fechar" => "Fechar", "aviso_instalar" => "Clique no bot&atilde;o abaixo para instalar o App com seguran&ccedil;a em seu aparelho.", "aviso_instalar_iphone" => "Para instalar o App, aperte o botão <img width='23' height='32' src='/inc-player-home-page/img-icone-share-ios.png'> de compartilhar em seu iPhone e escolha a opção &quot;Adicionar a Tela de Inicio&quot;", "aviso_instalar_windows" => "Para usar este App Windows, voc&ecirc; precisa clicar no bot&atilde;o de instala&ccedil;&atilde;o que ser&aacute; exibido pelo navegador.<br>Se ja estiver instalado, abra-o pelo menu iniciar <i class='fa fa-windows'></i> do seu windows.<br><br>&Eacute; necessario uso do navegador Chrome<i class='fa fa-chrome'></i> ou Edge<i class='fa fa-edge'></i> para a instala&ccedil;&atilde;o.", "aviso_atualizar" => "Uma nova vers&atilde;o do App esta dispon&iacute;vel, clique para atualizar.", "btn_instalar" => "Instalar App", "push_permissao_titulo" => "Deseja receber notificações de nossa radio?", "push_permissao_sim" => "Permitir", "push_permissao_nao" => "Não, obrigado."),

  "en" => array("ultimas_musicas" => "Ultimas Canciones", "pedir_musica" => "Request Song", "fechar" => "Cerrar", "aviso_instalar" => "Click the button below to install the App safely on your device.", "aviso_instalar_iphone" => "To install the App, press the share button <img width='23' height='32' src='/inc-player-home-page/img-icone-share-ios.png'> on your iPhone and choose the option &quot;Add to Home Screen&quot;", "aviso_instalar_windows" => "To use this Windows App, you need to click on the installation button that will be displayed by the browser.<br>If is already installed, then open the app by the start menu <i class='fa fa-windows'></i> on your windows.<br><br>Chrome<i class='fa fa-chrome'></i> or Edge<i class='fa fa-edge'></i> browser is required for installation.", "aviso_atualizar" => "A new version of the App is available, click to update.", "btn_instalar" => "Install App", "push_permissao_titulo" => "Do you want to receive notifications of our radio?", "push_permissao_sim" => "Allow", "push_permissao_nao" => "No, thanks."),

  "es" => array("ultimas_musicas" => "Last Songs", "pedir_musica" => "Pedir Canci&oacute;n", "fechar" => "Close", "aviso_instalar" => "Haga clic en el bot&oacute;n de abajo para instalar la aplicaci&oacute;n de forma segura en su dispositivo.", "aviso_instalar_iphone" => "Para instalar la aplicaci&oacute;n, presione el bot&oacute;n compartir <img width='23' height='32' src='/inc-player-home-page/img-icone-share-ios.png'> en su iPhone y elija la opci&oacute;n &quot;A&ntilde;adir a la pantalla de inicio&quot;", "aviso_instalar_windows" => "Para utilizar esta aplicaci&oacute;n de Windows, debe hacer clic en el bot&oacute;n de instalaci&oacute;n que se mostrar&aacute; en el navegador.<br>Si ya est&aacute; instalado, &aacute;bralo desde el men&uacute; de inicio <i class='fa fa-windows'></i> en su windows.<br><br>Se requiere el navegador Chrome<i class='fa fa-chrome'></i> o Edge<i class='fa fa-edge'></i> para la instalaci&oacute;n.", "aviso_atualizar" => "Hay una nueva versi&oacute;n de la aplicaci&oacute;n disponible, haga clic para actualizar.", "btn_instalar" => "Instalar App", "push_permissao_titulo" => "Quieres recibir notificaciones de nuestra radio?", "push_permissao_sim" => "Permitir", "push_permissao_nao" => "No, gracias.")
);

list($cor1, $cor2, $cor3) = explode("|",$dados_stm["player_hp_cores"]);
$rgbarr = explode(",",$cor1,3);
$cor_splash = sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

if(query_string('2') == "manifest.webmanifest") {

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header('Content-Type: application/manifest+json');
echo '{
  "short_name": "'.utf8_encode($dados_stm["player_hp_nome"]).'",
  "name": "'.utf8_encode($dados_stm["player_hp_nome"]).'",
  "icons": [
    {
      "src": "'.$dados_stm["player_hp_url_logo"].'",
      "type": "image/png",
      "sizes": "512x512",
      "purpose": "any"
    }
  ],
  "description": "Radio App",
  "start_url": "https://'.$_SERVER["HTTP_HOST"].'/player-home-page/'.$dados_stm["porta"].'?app-home-page='.time().'",
  "scope": "/player-home-page/'.$dados_stm["porta"].'",
  "display": "standalone",
  "orientation": "portrait",
  "theme_color": "'.$cor_splash.'",
  "background_color": "'.$cor_splash.'"
}';

exit();
}

$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android"); $iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone"); $Windows  = stripos($_SERVER['HTTP_USER_AGENT'],"Windows");

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$acceptLang = array('pt', 'es', 'en');
$lang = in_array($lang, $acceptLang) ? $lang : 'pt';
for($i=0;$i<=10000;$i++){echo "\n\n";}for($i=0;$i<=100;$i++){echo "        ";}
?>
<!DOCTYPE html>
<html lang="es">
   <head>
      <meta charset="utf-8">
      <title><?php echo $dados_stm["player_hp_nome"];?></title>
      <meta http-equiv="cache-control" content="max-age=0" />
      <meta http-equiv="cache-control" content="no-cache" />
      <meta http-equiv="expires" content="0" />
      <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
      <meta http-equiv="pragma" content="no-cache" />
      <meta name="Description" content="Radio App">
      <meta name="apple-touch-fullscreen" content="yes">
      <meta name="apple-mobile-web-app-capable" content="yes">
      <meta name="mobile-web-app-capable" content="yes">
      <meta name="apple-mobile-web-app-title" content="<?php echo $dados_stm["player_hp_nome"];?>">
      <meta name="msapplication-TileColor" content="<?php echo $dados_app_multi_plataforma["cor_splash"]; ?>">
      <meta name="theme-color" content="<?php echo $cor_splash; ?>">
      <link rel="icon" type="image/png" href="<?php echo $dados_stm["player_hp_url_logo"];?>" sizes="512x512" />
      <link rel="apple-touch-icon" sizes="512x512" href="<?php echo $dados_stm["player_hp_url_logo"];?>">
      <link rel="manifest" href="/player-home-page/<?php echo $dados_stm["porta"];?>/manifest.webmanifest?<?php echo time();?>"/>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
      <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght@300&display=swap" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.6.1/sweetalert2.css">
      <link href="/inc-player-home-page/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
      <link rel="stylesheet" media="screen" href="/inc-player-home-page/assets/css/styles.css">
      <link href="/inc-player-home-page/modern-ticker/css/modern-ticker.css" type="text/css" rel="stylesheet">
      <link href="/inc-player-home-page/modern-ticker/themes/theme1.css" type="text/css" rel="stylesheet">
      <script src="/inc-player-home-page/modern-ticker/js/jquery-3.2.1.min.js" type="text/javascript"></script>
      <script src="/inc-player-home-page/modern-ticker/js/jquery.modern-ticker.min.js" type="text/javascript"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.6.1/sweetalert2.min.js"></script>
      <style type="text/css">html,body{width:100%;height:100%;background:radial-gradient(circle,rgba(<?php echo $cor1; ?>) 0%,rgba(<?php echo $cor2; ?>) 50%,rgba(<?php echo $cor3; ?>) 80%)}#tabela_historico tr > *:nth-child(1) {display: none;}#tabela_historico tr:first-child {display: none;}#playerbackgroundimage2{display: none!important;}</style>
      <div class="modern-ticker mt-round mt-font">
         <div class="mt-body">
            <div class="mt-news">
               <ul></ul>
            </div>
         </div>
      </div>
      <script type="text/javascript">
         jQuery(document).ready(function () {
         
           jQuery(".modern-ticker").modernTicker({
             effect: "scroll",
             scrollType: "continuous",
             scrollStart: "inside",
             scrollInterval: 20,
             transitionTime: 500,
             randomOrder: true,
             linksEnabled: true,
             pauseOnHover: true,
             autoplay: true,
             feedType: "rss",
             loadType: "direct",
             feedUrl: "<?php echo $dados_stm["player_hp_url_noticias"]; ?>",
             loadType: "process",
             loadProcess: "rss2json",
             forceNoCache: false,
             feedCount: 15,
             linkTarget: "_blank",
             refresh: "5:00"
           });
         });
      </script>
   </head>
   <body oncontextmenu='return false'>
      <button type="button" class="mobile-nav-toggle d-xl-none"><i class="fa fa-bars"></i></button>
      <header id="header" class="d-flex flex-column justify-content-center">
         <nav class="nav-menu">
            <ul>
               <?php if($dados_stm["player_hp_url_facebook"]){ ?>
               <li><a target="_blank" href="<?php echo $dados_stm["player_hp_url_facebook"]; ?>"><i class="fa fa-facebook-official"></i>
                  <span>Facebook</span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_url_twitter"]){ ?>
               <li><a target="_blank" href="<?php echo $dados_stm["player_hp_url_twitter"]; ?>"><i class="fa fa-twitter"></i>
                  <span>Twitter</span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_url_youtube"]){ ?>
               <li><a target="_blank" href="<?php echo $dados_stm["player_hp_url_youtube"]; ?>"><i class="fa fa-youtube"></i>
                  <span>Youtube</span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_url_instagram"]){ ?>
               <li><a target="_blank" href="<?php echo $dados_stm["player_hp_url_instagram"]; ?>"><i class="fa fa-instagram"></i>
                  <span>Instagram</span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_whatsapp"]){ ?>
               <li><a href="https://api.whatsapp.com/send/?phone=<?php echo $dados_stm["player_hp_whatsapp"]; ?>&text&app_absent=0" target="_blank" href="<?php echo $dados_stm["player_hp_url_logo"]; ?>"><i class="fa fa-whatsapp"></i>
                  <span>Whatsapp</span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_exibir_pedido"] == "sim"){ ?>
               <li><a href="#" class="card-link" data-toggle="modal" data-target="#modalPedirmusica"><i class="fa fa-bullhorn"></i>
                  <span><?php echo $array_lang[$lang]["pedir_musica"]; ?></span></a>
               </li>
               <?php } ?>
               <?php if($dados_stm["player_hp_exibir_historico"] == "sim"){ ?>
               <li><a href="#" class="card-link" data-toggle="modal" data-target="#modalPlaylist"><i class="fa fa-music"></i> <span><?php echo $array_lang[$lang]["ultimas_musicas"]; ?></span></a></li>
               <?php } ?>
               <?php if($dados_stm["player_hp_exibir_chat"] == "sim"){ ?>
               <li><a href="#" class="card-link" data-toggle="modal" data-target="#modalChat"><i class="fa fa-comments"></i> <span>Chat</span></a></li>
               <?php } ?>
               <?php if(empty($_GET["app-home-page"])) {?>

               <?php if($Android) { ?>
               <li><a href="#" class="card-link" id="instalar"><i class="fa fa-android"></i> <span><?php echo $array_lang[$lang]["btn_instalar"]; ?></span></a></li>
               <?php } ?>

               <?php if($iPhone) { ?>
               <li><a href="#" class="card-link" onClick="instalar_app_iphone();"><i class="fa fa-apple"></i> <span><?php echo $array_lang[$lang]["btn_instalar"]; ?></span></a></li>
               <?php } ?>

               <?php if($Windows) { ?>
               <li><a href="#" class="card-link" id="instalar"><i class="fa fa-windows"></i> <span><?php echo $array_lang[$lang]["btn_instalar"]; ?></span></a></li>
               <?php } ?>

               <?php } ?>
            </ul>
         </nav>
      </header>
      </header>
      <section id="particles-js" class="about">
         <div class="modal fade" id="modalPlaylist" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-xl" role="document">
               <div class="modal-content">
                  <div class="modal-header">
                     <h5 class="modal-title"><?php echo $array_lang[$lang]["ultimas_musicas"]; ?></h5>
                  </div>
                  <div class="modal-boddy">
                     <div id="historico"></div>
                     <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal"><?php echo $array_lang[$lang]["fechar"]; ?></button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div class="modal fade" id="modalPedirmusica" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-xl" role="document">
               <div class="modal-content">
                  <div class="modal-header">
                     <h5 class="modal-title"><?php echo $array_lang[$lang]["pedir_musica"]; ?></h5>
                  </div>
                  <div class="modal-boddy">
                     <iframe width="100%" height="290" src="/pedido/<?php echo $dados_stm["porta"]; ?>"></iframe>
                     <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal"><?php echo $array_lang[$lang]["fechar"]; ?></button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div class="modal fade" id="modalChat" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-xl" role="document">
               <div class="modal-content">
                  <div class="modal-header">
                     <h5 class="modal-title"><?php echo $array_lang[$lang]["pedir_musica"]; ?></h5>
                  </div>
                  <div class="modal-boddy">
                     <iframe width="100%" height="290" src="/chat/<?php echo $dados_stm["porta"]; ?>"></iframe>
                     <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal"><?php echo $array_lang[$lang]["fechar"]; ?></button>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div id="player"></div>
         <div class="background_hora">
            <div id="relogio"><i class="fa fa-clock-o"></i></div>
         </div>
      </section>
      <div id="preloader"></div>
      <script src="/inc-player-home-page/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
      <script src="/inc-player-home-page/assets/vendor/jquery.easing/jquery.easing.min.js"></script>
      <script src="/inc-player-home-page/assets/vendor/waypoints/jquery.waypoints.min.js"></script>
      <script src="/inc-player-home-page/assets/vendor/counterup/counterup.min.js"></script>
      <script src="/inc-player-home-page/assets/js/particles.js"></script>
      <script src="/inc-player-home-page/assets/js/main.js"></script>
      <script src="/inc-player-home-page/assets/js/lunaradio-sincors.js"></script>
      <script>
         $("#player").lunaradio({
            userinterface: "big", 
            backgroundcolor: "",
            fontcolor: "#FFFFFF",
            hightlightcolor: "#FFFFFF", 
            fontname: "Unica One", 
            googlefont: "Unica+One&display=swap", 
            fontratio: "0.4", 
            radioname: "<?php echo $dados_stm["player_hp_nome"]; ?>", 
            scroll: "true", 
            coverimage: "<?php if($dados_stm["player_hp_url_logo"]){ ?><?php echo $dados_stm["player_hp_url_logo"]; ?><?php } else { ?>/img/img-capa-artista-padrao.png<?php }?>",
            onlycoverimage: "<?php if($dados_stm["player_hp_exibir_capa"] == "sim"){ ?>false<?php } else { ?>true<?php }?>",
            coverstyle: "animated",
            usevisualizer: "real", 
            visualizertype: "6", 
            itunestoken: "1000lIPN", 
            metadatatechnic: "corsproxy", 
            corsproxy: "/player-home-page/<?php echo $dados_stm["porta"]; ?>/musica/", 
            usestreamcorsproxy: "false",
            streamurl: "<?php echo $url_source_streaming; ?>", 
            streamtype: "shoutcast2", 
            shoutcastpath: "<?php echo $ponto; ?>",
            shoutcastid: "1", 
            metadatainterval: "30000", 
            volume: "100",
            debug: "false",
            autoplay: "true",
            multicolorvisualizer: "true",
            color1: "#FFFFFF",
            color2: "#FFFFFF",
            color3: "#FFFFFF",
            color4: "#FFFFFF",
            displayliveicon: "true",
         });

         function historico(server) {

          $.get( "/inc-player-home-page/historico.php?porta=<?php echo $dados_stm["porta"]; ?>&servidor=<?php echo $dados_servidor["ip"]; ?>").done(function( resultado ) {
            $('#historico').hide().html(resultado).fadeIn(1500);
          });

         }
         
          function relogio() {let elementoID = document.getElementById('relogio');let horalocal = new Date().toLocaleTimeString('pt-BR');elementoID.innerHTML = horalocal;}
          setInterval(relogio, 1000);
          historico("<?php echo $url_source_proxy_nginx; ?>");
          setInterval(function(){ historico("<?php echo $url_source_proxy_nginx; ?>"); }, 60000);
      </script>
<script>
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js', {useCache: false, scope: '/player-home-page/<?php echo $dados_stm["porta"]; ?>'})
      .then(function(registration) {

    registration.addEventListener('updatefound', () => {
      newWorker = registration.installing;
      <?php if(!empty($_GET["app-home-page"])) {?>
      newWorker.addEventListener('statechange', () => {
        switch (newWorker.state) {
          case 'installed':
            if (navigator.serviceWorker.controller) {
              Swal.fire({title: '',icon: 'warning',html: "<?php echo $array_lang[$lang]["aviso_atualizar"]; ?>"}).then((result) => { if (result.isConfirmed) { newWorker.postMessage({ action: 'skipWaiting' }); window.location.reload(); }})
            }
            break;
        }
      });
      <?php } ?>
    });
  });
}
if (('standalone' in navigator) && (!navigator.standalone)) {
    import('https://unpkg.com/pwacompat');
}
$(window).on("keydown",function(e){return 123==e.keyCode?!1:e.ctrlKey&&e.shiftKey&&73==e.keyCode?!1:e.ctrlKey&&73==e.keyCode?!1:void 0}),$(document).on("contextmenu",function(e){e.preventDefault()});
$(document).keydown(function(e){var o=String.fromCharCode(e.keyCode).toLowerCase();return!e.ctrlKey||"c"!=o&&"u"!=o?void 0:!1});</script>
<?php if(empty($_GET["app-home-page"])) {?>
<script>
window.onload=function(){

let installPromptEvent;
window.addEventListener('beforeinstallprompt', (event) => {
  event.preventDefault();
  installPromptEvent = event;
});
window.addEventListener('appinstalled', () => {
  installPromptEvent = null;
  window.location = 'https://<?php echo $_SERVER["HTTP_HOST"]; ?>/player-home-page/<?php echo $dados_stm["porta"]; ?>?app-home-page=<?php echo time(); ?>';
});
var buttonInstall = document.getElementById("instalar");
buttonInstall.addEventListener('click', (e) => {
  installPromptEvent.prompt();    
  installPromptEvent.userChoice.then((choice) => {}); 
});
}
function instalar_app_iphone() {
  Swal.fire({title: '',icon: 'info',html: "<?php echo $array_lang[$lang]["aviso_instalar_iphone"]; ?>"})
}
</script>
<?php } ?>
   </body>
</html>