<?php 

/**
 * TVindoor Serverless Class.
 *
 * @since		2.0.0
 *
 * @package		TVindoor
 * @subpackage	TVindoor/includes
 * @author		Sandeep Verma | Valmy Gomes
 */


if ( ! defined( 'ABSPATH' ) ) {
        exit;
}


/*
Plugin Name: Serverless Radio 
Plugin URI: https://www.serverlessradio.com/
Description: Serverless Radio, MP3 Linear Playback, Radio Player, MP3 podcast Player, Audio Player, HTML5, Radiosolution, AutoDJ
Version: 0.7.7
Author: Sandeep Verma
Author URI: https://www.svnlabs.com/
*/ 


add_action( 'template_redirect', 'rtvi_callback' );
 
function rtvi_callback() {

global $post, $wpdb;

  $rtvi = sanitize_text_field($_REQUEST['rtvi']);

  if ( isset($rtvi) && $rtvi!="" ) {  //

    include_once (TVINDOOR_PLUGIN_PATH . 'public/player/player.php');
   wp_footer();
   exit();
   
  }

  $rtvitick = sanitize_text_field($_REQUEST['rtvitick']);

  if ( isset($rtvitick) && $rtvitick!="" ) {  //

   include_once (TVINDOOR_PLUGIN_PATH . 'public/player/events.php');
   
   exit();
   
  }


}



add_action( 'admin_footer', 'rtvi_ajax_scan_folder' );
function rtvi_ajax_scan_folder() { ?>
    <script type="text/javascript" >
    
    
    jQuery('#ScanFolder').click(function(){

        var dataVariable = {
            'action': 'rtvi_action_scan_folder',  
            'sourceurl': jQuery("#sourceurl").val()  
        };

        var playlist = '';


        jQuery('#toggleEmbed').html('');
        jQuery("#EmbedLocal").html('');


        jQuery("#rtvi_playlist").html( '<img src="<?php echo plugin_dir_url( __FILE__ ).'images/preloaderResult.gif'; ?>" /> Scanning...' );

        jQuery.ajax({
            url: ajaxurl, // this will point to admin-ajax.php
            type: 'POST',
            dataType : "json",
            data: dataVariable, 
            success: function (data) {               
           
              
              console.log(data);

              idno = data.length;

            
              playlist += '<div id="list"><ul  id="more_element_area">';

              for(i=0;i<data.length;i++)
              {


              mp3Duration(data[i].source, "duration"+data[i].index);  

              playlist += '<li class="grab" style="cursor: grab;" title="'+data[i].title+'" id="arrayorder_'+data[i].index+'">';
              
              playlist += '<i class="faarrows" style="font-size:12px; color: #666;"><img src="<?php echo plugin_dir_url( __FILE__ ).'images/dd.png'; ?>" border="0" /></i>&nbsp;';

              playlist += '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="title[]" id="title'+data[i].index+'" value="'+data[i].title+'" placeholder="title" />&nbsp;';

              playlist += '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="song[]" id="song'+data[i].index+'" value="'+data[i].source+'" placeholder="mp3" />&nbsp;';

              playlist += '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="duration[]" id="duration'+data[i].index+'" value="" placeholder="duration" />&nbsp;';


              
              playlist += '<a title="Add More" href="javascript:void(0)" onclick="return addNewElement()">Add</a>&nbsp;';
              playlist += '<a title="Remove This" href="javascript:void(0)" onclick="return removeThisElement('+data[i].index+')">Remove</a>&nbsp;';

                          

              playlist += '<div style="clear: both;"></div></li>';

              }

              playlist += '</ul></div>';

              jQuery("#rtvi_playlist").html( playlist );


              if(typeof(idno)  === "undefined") 
               {
                 alert("Error Reading MP3 Folder Link, Please make sure your MP3 Folder Link is public!!");
                 jQuery("#rtvi_playlist").html( "Error Reading MP3 Folder Link, Please make sure your MP3 Folder Link is public!!" );
               } 


               jQuery( "#more_element_area" ).sortable();
               jQuery( "#more_element_area" ).disableSelection();



            },
            error: function(error) { // error logging

              
              alert("Error Reading MP3 Folder Link, Please make sure your MP3 Folder Link is public!!");
              console.log('Error!');
 
              jQuery("#rtvi_playlist").html( "Error Reading MP3 Folder Link, Please make sure your MP3 Folder Link is public!!" );

            }


        });

    });  
   
    </script> 
    
    <?php
}

add_action("wp_ajax_rtvi_action_scan_folder" , "rtvi_action_scan_folder");
function rtvi_action_scan_folder(){
    $id = '991';
    //echo json_encode($_POST);
    $jatem = '1';
    if ($jatem == "") {

    $folderfeedlink = sanitize_text_field($_REQUEST['sourceurl']);

    if(substr($folderfeedlink, -1)!="/")
      $folderfeedlink = $folderfeedlink."/";


    $ff = rtvi_read_folder($folderfeedlink, "mp3");

    $mm = 0;

    $array = array();
        
    foreach($ff as $file)
    {


    $array[] = array("index" => $mm, "title" => rtvi_file_name(basename($file)), "source" => $file, "picture" => "", "artist" => "", "duration" => "");

    $mm++;


         } 
    } else {
        
        $folderfeedlink = json_decode( stripslashes(get_post_meta($id, "rtvi_".$id, true)), true); 
    
    $mm = 0;
    $array = array();
    
    foreach ($folderfeedlink as $a) {
        
       $array[] = array("index" => $mm, "title" => rtvi_file_name(basename($a['source'])), "source" => $a['source'], "picture" => $a['picture'], "artist" => $a['artist'], "duration" => $f = $a['duration']);
    $mm++;
    
         }
    }
    
    

    if($mm == 0)
     echo json_encode(array("error" => "Error Reading MP3 Folder Link"));
    else 
     echo json_encode($array);


    wp_die();
}


add_action("wp_ajax_rtvi_action_scan_folder2" , "rtvi_action_scan_folder2");
function rtvi_action_scan_folder2(){
    global $post;
    $id = '991';
    //echo json_encode($_POST);
  
    $folderfeedlink = json_decode( stripslashes(get_post_meta($id, "rtvi_".$id, true)), true); 
    
    $mm = 0;
    $array = array();
    
 
    foreach ($folderfeedlink as $x) {
     
        $a = $x['index'];
         $b = $x['title'];
          $c = $x['source'];
           $d = $x['picture'];
            $e = $x['artist'];
             $f = $x['duration'];
             

        
        echo '<li class="grab" style="cursor: grab;" title="'. $b .'" id="arrayorder_'. $a .'">';
        
        echo '<i class="faarrows" style="font-size:12px; color: #666;"><img src="'. plugin_dir_url( __FILE__ ).'images/dd.png'.'" border="0" /></i>&nbsp;';
        
        echo '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="'. $b .'" id="title'. $a .'" value="'. $b .'" placeholder="title" />&nbsp;';
        
        echo '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="'. $c .'" id="song'. $a .'" value="'. $c .'" placeholder="mp3" />&nbsp;';
        
        echo '<input class="form-control" style="width: auto; display: inline-block;" type="text" name="'. $f .'" id="duration'. $a .'" value="" placeholder="duration" />&nbsp;';
        
        echo '<a title="Add More" href="javascript:void(0)" onclick="return addNewElement()">Add</a>&nbsp;';
              
        echo '<a title="Remove This" href="javascript:void(0)" onclick="return removeThisElement('. $a .')">Remove</a>&nbsp;';
        
        echo '<div style="clear: both;"></div></li>';
        
        
        
        echo '';
      
        
    $mm++;
    
         }
          echo '</ul></div>';
/*
    if($mm == 0)
     echo 'erro'; //não tem nada
    else 
     echo 'sucesso'; //tem e deve carregar
*/

  //  wp_die();
}


add_action("wp_ajax_rtvi_action_scan_folder3" , "rtvi_action_scan_folder3");
function rtvi_action_scan_folder3(){
    global $post;
    $id = '991';
    //echo json_encode($_POST);
  
    $folderfeedlink = json_decode( stripslashes(get_post_meta($id, "rtvi_".$id, true)), true); 
    
    $mm = 0;
    $array = array();
    
    foreach ($folderfeedlink as $a) {
        
       $array[] = array("index" => $mm, "title" => $a['title'], "source" => $a['source'], "picture" => $a['picture'], "artist" => $a['artist'], "duration" => $f = $a['duration']);
    $mm++;
    
         }
         
          if($mm == 0)
     echo json_encode(array("error" => "Error Reading MP3 Folder Link"));
    else 
     echo json_encode($array);


    wp_die();
}



add_action( 'admin_footer', 'rtvi_get_player' );
function rtvi_get_player() { ?>
    <script type="text/javascript">

    var rtvi = "<?php echo time(); ?>";  

    jQuery('#GetPlayer').click(function(){

        var dataVariable = {
            'action': 'rtvi_action_get_player', 
            'rtvi' : rtvi,
            'playlistData': jQuery("#playlistFrm").serialize() 
        };

        jQuery.ajax({
            url: ajaxurl, // this will point to admin-ajax.php
            type: 'POST',
            dataType : "json",
            data: dataVariable, 
            success: function (data) {

                console.log(data.rtvi);

                var str = '<iframe src="<?php echo esc_url( home_url( '/' ) ); ?>?rtvi='+data.rtvi+'" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" width="100%" height="108"></iframe>'; 

                jQuery('#toggleEmbed').html('<textarea name="ecode" style="width:100%" cols="30" rows="3">'+str+'</textarea>');

                jQuery("#EmbedLocal").html(str);

            }
        });
    });

    </script> 
    <?php
}


add_action("wp_ajax_rtvi_action_get_player" , "rtvi_action_get_player");
function rtvi_action_get_player(){
    
    
    //print_r($_POST);

    parse_str($_POST['playlistData'], $rtvi_array);

    //print_r($rtvi_array);

    //wp_die();


    $rtvi = sanitize_text_field($_REQUEST['rtvi']);

    $titles = array_map( 'sanitize_text_field', wp_unslash( $rtvi_array['title'] ) );
    //$songs = array_map( 'sanitize_text_field', wp_unslash( $rtvi_array['song'] ) );

    $songs = $rtvi_array['song'];

    $durations = array_map( 'sanitize_text_field', wp_unslash( $rtvi_array['duration'] ) );

    //print_r($songs);


    if($rtvi!="")
    { 

    $i=0;

    $playlist = array();


    foreach ($titles as $key => $value) {
      
     $playlist[] = array("index" => $i, "title" => $value, "source" => $songs[$i], "picture" => "", "artist" => "", "duration" => $durations[$i]);

     $i++;

    }


    $echo = json_encode($playlist);

    $echo = str_replace("\/", "/", $echo);

    update_post_meta($rtvi, "rtvi_".$rtvi, $echo);
    
    


    //echo $time;

    echo json_encode(array("rtvi" => $rtvi));

    }



    wp_die();
}




function rtvi_get_current_song($startedAt, $rtvi)
{


//$elapsedTime = (time() - $startedAt);  

$elapsedTime = (time() - $rtvi);     

$list = json_decode( stripslashes(get_post_meta($rtvi, "rtvi_".$rtvi, true)), true);  

$array = array();

$i=0;

$totalDuration = 0;

foreach ($list as $l) {


//$mp3s = preg_replace('/ /i', '%20', $l['source']);

//$mp3s = mb_check_encoding($l['source'], 'UTF-8') ? $l : utf8_encode($l['source']);

$mp3s = $l['source'];   

$duration2 = $l['duration'];

$totalDuration += $duration2;

//$array[] = array( "id" => $i, "title" => $l['title'], "totaltime" => $duration2, "duration" => $duration2, "estimate" => $duration2 );

$array[] = array( "id" => $i, "title" => $mp3s, "estimate" => $duration2 );

$i++;

}

//print_r($array);

//echo $elapsedTime."-".$totalDuration." > ";

//echo intval($elapsedTime / $totalDuration)." > ";

$rem =  $elapsedTime % $totalDuration;

$temp = $rem;

$clist = count($array);

//print_r($array);

foreach($array as $k=>$ar)
{
   $temp = ($temp - $ar['estimate']);
   
   $next = $k+1; 
   if($next>=$clist) $next = 0;
   
   $prev1 = $k-1;
   if($prev1<0) $prev1 = $clist-1;
   
   $prev2 = $k-2;
   if($prev2<0) $prev2 = $clist-2;
   
   
   if($temp<0)
   {
     //echo $k." | ".$temp;
   return array("id" => $k, "title" => $ar['title'], "tick" => $ar['estimate']+$temp, "next" => $array[$next]['title'], "prev1" => $array[$prev1]['title'], "prev2" => $array[$prev2]['title']);
   break;

   }
    
}


}



function rtvi_read_folder($url, $fotmat="mp3")
{

$url = stripslashes(preg_replace('/ /i', '%20', $url)); 

//$html = file_get_contents($url); 

$html = "";

$response = wp_remote_get( $url );
 
if ( is_array( $response ) && ! is_wp_error( $response ) ) {
    $headers = $response['headers']; // array of http header lines
    $html    = $response['body']; // use the content
}



if($html=="") echo "<strong>If Audio MP3 Folder is not public...</strong>";

$mp3s = array();

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

//$tRows = $xpath->query("//a[ends-with(@href,'.mp3')]");

if($fotmat=="aac")
 $tRows = $xpath->query('//a[contains(@href, ".aac")]//@href');
else if($fotmat=="mp3")
 $tRows = $xpath->query('//a[contains(@href, ".mp3")]//@href');
else
 $tRows = $xpath->query('//a[contains(@href, ".mp4")]//@href');

//print_r($tRows->nodeValue);

foreach ($tRows as $row) {
    // fetch all 'tds' inside this 'tr'
    //$td = $xpath->query('td', $row);
  
  if(preg_match('#http#', $row->nodeValue))
   $nodeValue = $row->nodeValue; 
  else
   $nodeValue = str_replace("list.php", "", $url).$row->nodeValue;
  
  //echo $row->textContent."<br>";
  //echo $nodeValue."<br>";
  
  //$mp3ss[] = $nodeValue;
  
  $mp3s[] = $nodeValue;
  
} 

return $mp3s;

} 



function rtvi_file_name($s)
{

  $s = str_replace("%20", " ", $s);
  $s = str_replace(".mp3", "", $s);
  $s = str_replace(".MP3", "", $s);
  $s = str_replace("_", " ", $s);
  $s = str_replace("-", " ", $s);
  $s = str_replace("+", " ", $s);
  $s = str_replace("  ", " ", $s);

  return urldecode($s);

} 
 
// Start the class
if ( ! class_exists( 'TVindoor_Admin_Serverless_Radio' ) ) {

class TVindoor_Admin_Serverless_Radio {
        

// Page in WP-Admin
function serverless_meta_box() {

			
?>

<div class="wrap">
<h2>Serverless Radio Player</h2>


<div style="color: #ff0000">Note: Please enter MP3 folder HTTPS link like (https://domain.com/songs/).</div>


<div style="clear: both;">&nbsp;</div>
  
  
<form action="" method="post" name="sourceFrm" id="sourceFrm">

<input type="hidden" id="hiddenid" name="hiddenid" value="<?php echo get_the_ID();?>">
	
<input type="text" name="sourceurl" id="sourceurl" style="width: 60%; display: inline-block;" value="">&nbsp;<input type="button" id="ScanFolder" style="width: auto; display: inline-block;" name="ScanFolder" value="Scan Folder">

<br><br>OR Make Serverless Radio Playlist Manually Below<br><br>
	
</form>
 
<div><b>MP3 Title || MP3 Link || MP3 Duration</b></div> 

<form action="" method="post" name="playlistFrm" id="playlistFrm">

<div align="left" id="rtvi_playlist">
    
     <div id="list"><ul  id="more_element_area">
         <script type="text/javascript"> idno = 0; </script>';
<?php 
$jatem2 = '';
if ($jatem2 == "") {      ?>    
    

<!-- Manual Playlist  -->
   

    <li class="grab" style="cursor: grab;" title="" id="arrayorder_0">

    <i class="faarrows" style="font-size:12px; color: #666;"><img src="<?php echo plugin_dir_url( __FILE__ ).'images/dd.png'; ?>" border="0" /></i>&nbsp;

    <input class="form-control" style="width: auto; display: inline-block;" type="text" name="title[]" id="title0" value="" onchange="setLiTitle('0');" placeholder="title" />&nbsp;

    <input class="form-control" style="width: auto; display: inline-block;" type="text" name="song[]" id="song0" value="" onchange="mp3DurationElement(`0`);" placeholder="mp3" />&nbsp;

    <input class="form-control" style="width: auto; display: inline-block;" type="text" name="duration[]" id="duration0" value="" placeholder="duration" />&nbsp;



    <a title="Add More" href="javascript:void(0)" onclick="return addNewElement()">Add</a>&nbsp;
    <a title="Remove This" href="javascript:void(0)" onclick="return removeThisElement('0')">Remove</a>&nbsp;

                
    <div style="clear: both;"></div></li>


    </ul></div>
<!-- Manual Playlist  -->
<?php } else { 
echo rtvi_action_scan_folder2();
}
?>

</div>

<div style="clear: both;">&nbsp;</div>

<input type="button" name="GetPlayer" id="GetPlayer" value="Get Player">

</form>


<div style="clear: both;">&nbsp;</div>

- Button "Scan Folder" will scan MP3 folder for reading duration of each MP3 file(s) <br>
- Button "Get Player" will make Serverless Radio 


<div style="clear: both;">&nbsp;</div>


<div align="center" id="EmbedLocal"></div>  


<div align="center" id="toggleEmbed" style="display:block; z-index:1000; overflow:hidden;"></div>

 


<strong></strong>



 </div>
<?php		

       }
       
    
        
         function add_serverless_meta_box() {
            add_meta_box(
			'tvindoor_playlist_editor',
			_x( 'Rádio Playlist', 'playlist cpt', 'tvindoor' ),
			array( __CLASS__, 'serverless_meta_box' ),
			TVindoor_Channel::post_type_name_playlist,
			'acf_after_title',
			'high'
		);
        }
    }


} 

//Salvando no BD ao Salvar o Post
add_action( 'save_post', 'serverless_save_post', 10, 3 );


function serverless_save_post ( $post_id,$post, $update ) {

	// Verify if this is an auto save routine.
	// If it is then our form has not been submitted, so we don't want to do anything
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if ( ! $update ) {
		return;
	}

	if ( $post->post_type !== 'tvindoor_playlist' ) { // could be a CPT, for example 'product'
		return;
	}

	// Check permissions
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}
	
	/**
	 * @todo
	 * Check for the post status: published, draft, ...
	 * Maybe we do not need to do anything if it goes to trash?
	 */

 $folderfeedlink = sanitize_text_field($_REQUEST['sourceurl']);

    if(substr($folderfeedlink, -1)!="/")
      $folderfeedlink = $folderfeedlink."/";


    $ff = rtvi_read_folder($folderfeedlink, "mp3");

    $mm = 0;

    $array = array();
        
    foreach($ff as $file)
    {


    $array[] = array("index" => $mm, "title" => rtvi_file_name(basename($file)), "source" => $file, "picture" => "", "artist" => "", "duration" => "");

    $mm++;


    } 

    if($mm == 0)
     $echo = json_encode(array("error" => "Error Reading MP3 Folder Link"));
    else 
     $echo = json_encode($array);
     
     update_post_meta($post_id, "rtvi_".$post_id, $echo);
}





wp_register_script( 'rtvi_plugin_script4', plugins_url('/js/serverless.js', __FILE__));
wp_enqueue_script( 'rtvi_plugin_script4' );  


