<?php
///////////////////////////////////////////////////////////////////////////

require_once 'lib/hashed_array.php';
require_once 'lib/tv/abstract_tv.php';
require_once 'lib/tv/default_epg_item.php';
require_once 'flussonic_setup_screen.php';
require_once 'flussonic_channel.php';
require_once 'flussonic_config.php';
///////////////////////////////////////////////////////////////////////////

class FlussonicM3uTv extends AbstractTv
{
    public function __construct()
    {
        parent::__construct(
            AbstractTv::MODE_CHANNELS_N_TO_M,
            FlussonicConfig::TV_FAVORITES_SUPPORTED,
            true);
    }

    public function get_fav_icon_url()
    {
        return FlussonicConfig::FAV_CHANNEL_GROUP_ICON_PATH;
    }

    ///////////////////////////////////////////////////////////////////////

    private static function get_icon_path($channel_id)
    { return sprintf(FlussonicConfig::M3U_ICON_FILE_URL_FORMAT, $channel_id); }

    ///////////////////////////////////////////////////////////////////////

    public function get_tv_playback_url($channel_id, $archive_ts, $protect_code, &$plugin_cookies)
    {
        $format = isset($plugin_cookies->format) ?
            $plugin_cookies->format : 'hls+UTC-Archivetime';
		
		$token = isset($plugin_cookies->token) ?
            $plugin_cookies->token : '0';
		
		hd_print("$format");
		
		$this->ensure_channels_loaded($plugin_cookies);
		$media_url = $this->get_channel($channel_id)->get_streaming_url();
		
		$media_url = str_replace("flussonic_token", $token, $media_url);
		hd_print($media_url);

			if($format == 'hls'){
				hd_print("OPEN hls");
				$media_url=str_replace('mpegts', 'index.m3u8', $media_url)."|||dune_params|||hls_forced_type:event";
				//$media_url=str_replace('http://', 'http://ts://', $media_url);
			}
			if($format == 'hls+video.m3u8'){
				hd_print("OPEN hls");
				$media_url=str_replace('mpegts', 'video.m3u8', $media_url);
				$media_url=str_replace('index.m3u8', 'video.m3u8', $media_url)."|||dune_params|||hls_forced_type:event";
				//$media_url=str_replace('http://', 'http://ts://', $media_url);
			}

			if($format == 'mpeg'){
				hd_print("OPEN MPEGTS");
				$media_url=str_replace('index.m3u8', 'mpegts', $media_url);
				$media_url=str_replace('http://', 'http://ts://', $media_url);
			}

			if($format == 'mpd'){
				hd_print("OPEN mpd");
				$media_url=str_replace('index.m3u8', 'index.mpd', $media_url);
				//$media_url=str_replace('http://', 'http://ts://', $media_url);
			}
		
			////////////////////////////////////////////////////////////////////
			if($archive_ts < 1 && $format == 'hlsffmpeg'){
				if(file_exists("/codecpack/WWW/cgi-bin/hls.sh"))
					$media_url="http://ts://127.0.0.1:81/cgi-bin/hls.sh?".str_replace("m3u8", "m3u9", $media_url);
			}
			////////////////////////////////////////////////////////////////////
			if($archive_ts > 0 && $format == 'hls'){
				$media_url = str_replace("index.m3u8", "archive-".$archive_ts."-10800.m3u8", $media_url);
			hd_print($media_url);
			}
				else if($archive_ts > 0 && $format == 'hls+video.m3u8'){
				    $media_url = str_replace("video.m3u8", "video-".$archive_ts."-10800.m3u8", $media_url);
				    hd_print($media_url);
				}
				else if($archive_ts > 0 && $format == 'hls+UTC-Archivetime'){
				    $media_url.="&utc=$archive_ts&lutc=".time();
				    hd_print($media_url);
				}
				else if($archive_ts > 0 && $format == 'mpd'){
					//$media_url=str_replace('dyndns.tv', 'dyndns.tv:89', $media_url);
			        $media_url = str_replace("index.mpd", "archive-".$archive_ts."-10800.mpd", $media_url);
					hd_print($media_url);	
				}

			else if($archive_ts > 0 && $format == 'hlsffmpeg'){
				$media_url = str_replace("index.m3u8", "archive-".$archive_ts."-4200.m3u8", $media_url);
			if(file_exists("/codecpack/WWW/cgi-bin/hls.sh")) $media_url="http://ts://127.0.0.1:81/cgi-bin/hls.sh?".str_replace("m3u8", "m3u9", $media_url);
			}
			//////////////////////////////////////////////////////////////////////	
			else if($archive_ts > 0 && $format == 'mpeg')
			$media_url = str_replace("mpegts", "archive-".$archive_ts."-10800.ts", $media_url);
		
		$pass_sex = isset($plugin_cookies->pass_sex) ? $plugin_cookies->pass_sex : '1234';
		$protected = $this->get_channel($channel_id)->is_protected();
		if ($protected) 
        {
       	   if ($protect_code !== $pass_sex)  $media_url=''; 
        }
		
		hd_print("OPEN MEDIA-URL: $media_url");
        return $media_url;
     }
	 ///////////////////////////////////////////////////////////////////////

     public function load_channels(&$plugin_cookies)
     {
		hd_print("LOAD CHANNELS");
        $this->channels = new HashedArray();
        $this->groups = new HashedArray();

		$token = isset($plugin_cookies->token) ? $plugin_cookies->token : '0';
		if ($token === "0") {
			$all_channels_group = new AllChannelsGroup($this, "%tr%t30", FlussonicConfig::PLUGIN_SETUP); //Ключ не найден! Перейдите в настройки
			$this->groups->put($all_channels_group);
			$plugin_cookies->isTokenValid = '0';
		}
		else {
			$source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST."/ott/m3u8-dune/".$token."/playlist.m3u8"));
			//hd_print("-".$source."-");
			if ($source === "nottoken" || $source == "Token not found"){
			hd_print("trying other plylist");
          $source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST2."/pl/m3u8-dune/".$token."/pl.m3u8")); //если первый не идёт, скачать этот
      	}
			
	  	if ($source === "nottoken" || $source == ""){
                $all_channels_group = new AllChannelsGroup($this, "%tr%t30", FlussonicConfig::PLUGIN_SETUP); //Ключ не найден! Перейдите в настройки
                $this->groups->put($all_channels_group);
                $plugin_cookies->isTokenValid = '0';
            } else {
                $plugin_cookies->isTokenValid = '1';

                if ($this->is_favorites_supported()) {
                    $this->groups->put(new FavoritesGroup($this, '__favorites', FlussonicConfig::FAV_CHANNEL_GROUP_CAPTION, FlussonicConfig::FAV_CHANNEL_GROUP_ICON_PATH));
                }

                $all_channels_group = new AllChannelsGroup($this, FlussonicConfig::ALL_CHANNEL_GROUP_CAPTION, FlussonicConfig::ALL_CHANNEL_GROUP_ICON_PATH);

                $this->groups->put($all_channels_group);

                $put_groups = Array();
		
		 file_put_contents('/tmp/playlist.m3u', $source);
				
		 $show_my = '/tmp/playlist.m3u';
        
		 $m3u_lines =
            file(
                $show_my,
                FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
	
		
         for ($i = 0; $i < count($m3u_lines); ++$i)
         {	
            if (preg_match('/EXTINF:/i', $m3u_lines[$i]))
			{
				$pars = explode('group-title="', $m3u_lines[$i]);
				$group_name = strstr($pars[1], '"', true);
				
				
				if (!in_array($group_name, $put_groups))
					array_push($put_groups, $group_name);
				
            if ($i + 1 >= count($m3u_lines))
                break;
			}
         }
			
		 $i=1;
		 foreach ($put_groups as $g)
         {

            hd_print(base64_encode($g).".png      -:$g");

            $this->groups->put(
                new DefaultGroup(
                    strval($i),
                    strval($g),
					FlussonicConfig::M3U_ICON_GROUP_FILE_URL_FORMAT . "/icon/".str_replace("/", "", base64_encode($g)).".png"));//Group icon
          $i++;
		 }
		
		  for ($i = 0; $i < count($m3u_lines); ++$i)
			{
			
            if (preg_match('/EXTINF:/i', $m3u_lines[$i]))
			{
				$pars = explode(',', $m3u_lines[$i]); 				
				$pars = str_ireplace(
					array (
							'&Ccedil;',
						    '&uuml;',
							'&#286;',
							'&amp;',
						  ),
					array (							
							"Ç",
							"ü",
							'Ğ',
							' & ',
						  ),
					$pars
				  );
				  $caption = $pars[1];

				$pars = explode('tvg-id="', $m3u_lines[$i]);
				if(count($pars) > 1)
				$id = strstr($pars[1], '"', true);
				else
					$i=$i;
				/////////////////////////////////////////////////
				$pars = explode('url-logo="', $m3u_lines[0]);
		        $icon_url = strstr($pars[1], '"', true);
				$pars = explode('tvg-logo="', $m3u_lines[$i]); 
				$logo = $icon_url.strstr($pars[1], '"', true); 

				// ARCHIVE & DAYS
                $pars = explode('timeshift="', $m3u_lines[$i]);
                $archive_days = strstr($pars[1], '"', true);
                if(intval($archive_days) > 0)
                    $archive = 1;
                else
                    $archive = 0;

				/////////////////////////////////////////////////
				$pars = explode('group-title="', $m3u_lines[$i]);
				$group_name = strstr($pars[1], '"', true);
				
				$media_url = $m3u_lines[$i + 1];
				
				$protect_code = 0;
				if(preg_match('/group-title="XXX/i', $m3u_lines[$i]))
					$protect_code = 1;
				
				if ($i + 1 >= count($m3u_lines))
					break;			
			
			 $channel =
                new FlussonicChannel(
                    base64_encode($caption)."&&".$id,
                    strval($caption),
					strval($logo),//dirname(__FILE__)."/icons/sender.png",
					strval($media_url), 0, $archive_days, 7, $protect_code, $archive, $archive_days);

				$this->channels->put($channel);
			
			 foreach ($this->groups as $g){
				
				$tv_category_id = strval($g->get_id());
				
				$group = $this->groups->get($tv_category_id);

				if($g->get_title() == $group_name){
                $channel->add_group($group);
                $group->add_channel($channel);	}
				 }
			   }
			}
		}
    }
}
    ///////////////////////////////////////////////////////////////////////////
public function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
    public function get_day_epg_iterator($channel_id, $day_start_ts, &$plugin_cookies)
    {
		$replace = array(
            '&#196;' => 'Г„',
            '&#228;' => 'Г¤',
            '&#214;' => 'Г–',
            '&#220;' => 'Гњ',
            '&#223;' => 'Гџ',
            '&#246;' => 'Г¶',
            '&#252;' => 'Гј',
            '&#39;'  => "'",
            '&quot;' => '"',
            '&#257;' => 'ā',
            '&#258;' => 'Ă',
            '&#268;' => 'Č',
            '&#326;' => 'ņ',
            '&#327;' => 'Ň',
            '&#363;' => 'ū',
            '&#362;' => 'Ū',
            '&#352;' => 'Š',
            '&#353;' => 'š',
            '&#382;' => 'ž',
            '&#275;' => 'ē',
            '&#276;' => 'Ĕ',
            '&#298;' => 'Ī',
            '&#299;' => 'ī',
            '&#291;' => 'ģ',
            '&#311;' => 'ķ',
			'&#316;' => 'ļ',
			'&amp;' => ' & ',
        );

		$channel_id = explode("&&", $channel_id);
		$channel_id = $channel_id[1];
		
		$epg_date     = gmdate("Y.m.d", $day_start_ts);
        $epg_date_new = date("Y-m-d H:m:s", strtotime('-1 hour', $day_start_ts));
        $epg_date_end = date("Y-m-d H:m:s", strtotime('+1 day', $day_start_ts));

    $epg = array();

    if (file_exists("/tmp/itv_channel_".$channel_id."_".$day_start_ts)) {
	$doc = file_get_contents("/tmp/itv_channel_".$channel_id."_".$day_start_ts);
	$epg = unserialize($doc);
    }
    else {
	try {
            $doc = HD::http_get_document(sprintf(FlussonicConfig::EPG_URL_FORMAT, $channel_id, $epg_date));
	}
	catch (Exception $e) {
	    hd_print("Can't fetch EPG ID:$id");
	    return array();
	}

        $ch_data = json_decode($doc);
        foreach ($ch_data->data as $key => $value) {
          if ($value->begin >= strtotime($epg_date_new) AND $value->begin < strtotime($epg_date_end)) {
            $epg[$value->begin]['name'] = $value->title;
            $epg[$value->begin]['desc'] = $value->description;
          }
        }
        if (count($epg) > 0)
		{
			file_put_contents("/tmp/itv_channel_".$channel_id."_".$day_start_ts, serialize($epg));
		}
	}
	$epg_result = array();

    ksort($epg, SORT_NUMERIC);

    $start = 0;
    $end = 0;
    foreach ($epg as $time => $value) {
        $tm =  $time; // + $epg_shift;
        if ($start == 0) $start = $tm;
        $end = $tm;

        $epg_result[] =
                new DefaultEpgItem(
                    strval($value["name"]),
                    strval($value["desc"]),
                    intval($tm),
                    intval(-1));
    }

    return
            new EpgIterator(
                $epg_result,
                $start,//$day_start_ts,
                $end//$day_start_ts + 100400
    );
    }
}

///////////////////////////////////////////////////////////////////////////
?>
