<?php
$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";
}

$url_streaming = "https://".strtolower($dados_servidor["nome"]).".".$dados_config["dominio_padrao"].":".$dados_stm["porta"]."";

if($dados_stm["tipo_servidor"] == "icecast") {
$url_streaming_players = $url_streaming."/".$ponto.".m3u";
} else {
$url_streaming_players = $url_streaming."/listen.m3u?sid=1";
}

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

    function getCapaArtista($str) {
    $termo = urlencode($str);
    $file = file_get_contents('https://itunes.apple.com/search?term=' . $termo . '&media=music&limit=1');
    $jsoncapa = json_decode($file, true);
    if ($jsoncapa['resultCount'] == 1):
        $image60 = (!empty($jsoncapa['results'][0]['artworkUrl60']) ? $jsoncapa['results'][0]['artworkUrl60'] : '');
        $image100 = (!empty($jsoncapa['results'][0]['artworkUrl100']) ? $jsoncapa['results'][0]['artworkUrl100'] : '');
        return str_replace(['60x60', '100x100'], '600x600', ($image100 ? $image100 : $image60));
    else:
        return false;
    endif;
}

    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 = ($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 = @file_get_contents("http://".$dados_servidor["ip"].":".$dados_stm["porta"]."/currentsong?sid=1");
    }

    if($musica):
        $capa = getCapaArtista($musica);
       echo json_encode(['status' => 'on','musica' => $musica, 'capa' => ($capa ? $capa : '/img/img-player-full-capa.png')]);
    else:
        echo json_encode(['status' => 'off','capa' => '/img/img-player-full-capa.png']);
    endif;    
   
    die();
}
 
?>  
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Player</title>
        <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
        <link href="/playertopo7/dist/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css"/>        
        <link href="/playertopo7/dist/bootstrap-slider/slider.css" rel="stylesheet" type="text/css"/>
        <link href="/playertopo7/inspiration.css" rel="stylesheet" type="text/css"/>
        <script src="/playertopo7/dist/jQuery/jquery.js" type="text/javascript"></script>   
        <script src="/playertopo7/dist/knob/jquery.knob.js" type="text/javascript"></script>
        <script src="/playertopo7/dist/bootstrap-slider/bootstrap-slider.js" type="text/javascript"></script>  
    </head> 
    <body class="inspiration" >  
        <div class='player' data-porta="<?php echo $dados_stm["porta"];?>" data-autoplay='1'  data-api="" data-url="<?php echo $url_streaming;?><?php echo $ponto;?>" ></div>

        <div id="jquery_jplayer_1" class="jp-jplayer"></div>
        <div id="jp_container_1" style='background:#612387;' class="jp-audio-stream" role="application" aria-label="media player">
            <div class="jp-type-single">
                <div class="jp-gui jp-interface">
                    <div class="jp-controls">
                        <img class="jp-play" role="button" tabindex="0" src="/playertopo7/inspiration-pause.png" alt="" height="50"/>
                        <img class="jp-mute" role="button" tabindex="0" src="/playertopo7/inspiration-mute.png" alt="" height="30"/>                     
                    </div>
                    <div class="jp-volume-controls">
                        <!--<img class="jp-volume-max" role="button" tabindex="0" src="inspiration-max.png" alt="" height="30"/>-->                    
                        <div class="jp-volume-bar">
                            <div class="volume">
                                <input type="slider" class="span2" value="" data-slider-min="0" data-slider-max="10" data-slider-step="1" data-slider-value="5" data-slider-id="GC" id="G" data-slider-tooltip="true" data-slider-handle="custom" />
                            </div>
                        </div>
                        <!--<div class="jp-current-time"></div>-->                      
                    </div>
                    <div class="fc_capa"></div> 
                    <div class="content-infor">
                        <div class="musica_atuals musica-musica-atual"></div> 
                    </div>
                </div> 
            </div>
            <div class="btn-players top">
                <div class="contents">
                    <a target="_blank" class="ico-hide" href="<?php echo $url_streaming_players;?>"><img src="/playertopo7/images/icones/img-icone-player-winamp.png" width="32" height="32" title="Ouvir no Winamp" data-toggle="tooltip" /></a>
                    <a target="_blank" class="ico-hide" href="<?php echo $url_streaming_players;?>"><img src="/playertopo7/images/icones/img-icone-player-mediaplayer.png" width="32" height="32" title="Ouvir no MediaPlayer" data-toggle="tooltip"  /></a>
                    <a target="_blank" class="ico-hide" href="<?php echo $url_streaming_players;?>"><img src="/playertopo7/images/icones/img-icone-player-realplayer.png" width="32" height="32" title="Ouvir no RealPlayer" data-toggle="tooltip" /></a>
                    <a target="_blank" class="ico-hide" href="<?php echo $url_streaming_players;?>"><img src="/playertopo7/images/icones/img-icone-player-vlc.png" width="32" height="32" title="Ouvir no RealPlayer" data-toggle="tooltip" /></a>
                    <a target="_blank" class="ico-hide" href="<?php echo $url_streaming_players;?>"><img src="/playertopo7/images/icones/img-icone-player-qt.png" width="32" height="32" title="Ouvir no RealPlayer" data-toggle="tooltip" /></a>
                    <a target="_blank" href="<?php echo $url_streaming_players;?>" class="init"><img src="/playertopo7/images/icones/img-icone-player-iphone.png" width="32" height="32" title="Ouvir no iphone" data-toggle="tooltip" /></a>
                </div> 
            </div> 
        </div>  
    </body>
    <script>
        $(function () {
            con = {
                control: $('.player'),
                RadioAudio: new Audio(),
                onRadioPlay: function () {
                    var pl = $('.jp-play').hasClass('on');

                    con.RadioAudio.src = con.control.data('url');
                    con.RadioAudio.load = true;
                    con.RadioAudio.currentTime = 0;
                    if (!pl) {
                        con.RadioAudio.play();
                        $('.jp-play').addClass('on');
                        $('.jp-play').attr('src', '/playertopo7/inspiration-pause.png');
                    } else {
                        con.RadioAudio.pause();
                        $('.jp-play').removeClass('on');
                        $('.jp-play').attr('src', '/playertopo7/inspiration-play.png');
                    }

                },
                getMusicaAtual: function () {

                    $.getJSON("<?php echo "https://".$_SERVER['HTTP_HOST']."/player-topo-7/".$dados_stm["porta"]."/info";?>", function (data, status) {

                        if (data.status == 'on') {
                            var musica_atual = (typeof data.musica === "object" ? document.title : data.musica.replace(/_/g, ' '));  // Mostra a música atual
                            $('.musica-musica-atual').html("<marquee scrolldelay='100'>" + musica_atual + "</marquee>");
                            $('.fc_capa').html("<img src='" + data.capa + "'/>");
                        } else {
                            $('.musica-musica-atual').html("<marquee scrolldelay='100'>Desligado</marquee>");
                            $('.fc_capa').html("<img src='" + data.capa + "'/>");
                        }

                        con.invervalo();
                    });
                }, invervalo: function () {
                    var TimeId = setTimeout(con.getMusicaAtual, 30000);
                }
            };
            //carrega a musica atual e capa da musica
            con.getMusicaAtual();

            $('.jp-play').on('click', con.onRadioPlay);
            $('.jp-mute').on('click', function () {
                con.RadioAudio.volume = 0;
            });
            //função autoplay (mais só funciona se o usuário autorizar a reprodução automatica, pois os navegadores bloqueiam essa função)
            if (con.RadioAudio.paused && con.control.data('autoplay') == 1) {
                con.onRadioPlay();
            }

            var radioVolume = function () {
                var volume;
                if (g.getValue() == 10) {
                    volume = '1';
                } else {
                    volume = "0." + g.getValue();
                }
                con.RadioAudio.volume = volume;
            };
            var g = $('#G').slider({tooltip: 'always'})
                    .on('slide', radioVolume)
                    .data('slider');
        });
    </script> 
</html>