<?php
///////////////////////////////////////////////////////////////////////////////
// Mini Classes

class TvModes
{
	const	channels_1_to_n		= false;
	const	channels_n_to_m		= true;
}

class EventDefs
{
	const	on_show				= -1;
	const	on_success			= 0;
	const	on_error			= 1;
	const	on_confirm			= 2;
}

class ControlSwitchDefs
{
	const	switch_on			= 'on';
	const	switch_off			= 'off';
}

class QualityDefs
{
	const	lowest				= 'lowest';
	const	middle				= 'middle';
	const	highest				= 'highest';
}

class TvArchivePlaybackDefs
{
	const	auto				= 'auto';
	const	tstv				= 'tstv';
	const	npvr				= 'npvr';
}

class HttpStreamsDefs
{
	const	hls_cbr				= 'cbr';
	const	hls_abs				= 'vbr';
	const	mpd_abs				= 'mpd_abs';
}

class TvBrowseModeDefs
{
	const	normal				= 'normal';
	const	full				= 'full';
}
///////////////////////////////////////////////////////////////////////////////

require_once 'lib/abstract_preloaded_regular_screen.php';
require_once 'lib/user_input_handler_registry.php';
require_once 'lib/default_dune_plugin_fw.php';
require_once 'lib/osd_component_factory.php';
require_once 'lib/default_dune_plugin.php';
require_once 'lib/control_factory_ext.php';
require_once 'lib/action_factory_safe.php';

require_once 'lib/mapped_array.php';
require_once 'lib/dune_stb_api.php';
require_once 'lib/user_data.php';
require_once 'lib/cache.php';

require_once 'providers/wink/wink.php';
require_once 'addons/custom_epg/custom_epg.php';
require_once 'addons/dune_palette_patcher.php';
require_once 'addons/playback_points.php';
require_once 'epg/epg_engine.php';
require_once 'tv_favorites_screen.php';
require_once 'tv_channels_screen.php';
require_once 'tv_channels_editor.php';
require_once 'tv_groups_screen.php';
require_once 'home_tv_launcher.php';
require_once 'setting_screen.php';
require_once 'tv_bin_screen.php';
require_once 'splash_screen.php';
require_once 'tv_channel.php';
require_once 'home_tv.php';
require_once 'sorter.php';

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

DefaultDunePluginFw::$plugin_class_name = 'HomeTvPlugin';
DefaultDunePluginFw::$plugin_creator_info = 'Brigadir (forum.mydune.ru)';

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

define('HTTP_USER_AGENT',			'Mozilla/5.0');
define('SILENT_HTTP_REQUESTS',		0);

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

class HomeTvPlugin extends DefaultDunePlugin
{
	public	$tv;
	public	$epg;
	public	$smlabs;
	public	$launcher;
	public	$user_data;
	public	$pf_enabled;
	public	$epg_screen;
	public	$bin_screen;
	public	$groups_screen;
	public	$settings_screen;
	public	$channels_editor;
	public	$channels_screen;
	public	$favorites_screen;
	public	$epg_events_screen;

	// Plugin manifest info
	public	$app_name;
	public	$app_caption;
	public	$app_label;
	public	$app_version;
	public	$app_version_idx;
	public	$app_drm_id;
	public	$app_auto_resume_enable;
	public	$app_update_url_valid;
	public	$parental_in_manifest;

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

	public function __construct()
	{
		parent::__construct();

		$plugin_path = dirname(__FILE__);

		if ($debug_mode_on = preg_match('/\/dune_plugins\//', $plugin_path))
			hd_print(__CLASS__ . ' run in debug mode!');

		define('PLUGIN_IMG_PATH',				"$plugin_path/img");
		define('LOCAL_CACHE_PATH',				DuneSystem::$properties['data_dir_path'] . '/cache');
		define('PLAYLISTS_CACHE_PATH',			get_paved_path(LOCAL_CACHE_PATH . '/playlists'));
		define('ICONS_CACHE_PATH',				get_paved_path(LOCAL_CACHE_PATH . '/logos'));
		define('META_LOCAL_CACHE_PATH',			get_paved_path(LOCAL_CACHE_PATH . '/meta'));
		define('USER_DATA_CACHE_PATH',			get_paved_path(LOCAL_CACHE_PATH . '/user_data'));
		define('TEMPORARY_CACHE_PATH',			get_paved_path(DuneSystem::$properties['tmp_dir_path'] . '/cache'));
		define('PLUGIN_CGI_URL',				(preg_match('/android/', get_platform_kind()) && $debug_mode_on)? preg_replace('/\/plugins.*/i', '', DuneSystem::$properties['plugin_cgi_url']) . '/' : DuneSystem::$properties['plugin_cgi_url']);
		define('EXT_EPG_AVAILABLE',				defined('PluginTvInfo::ext_epg_enabled'));
		define('DVB_PLAYBACK_AVAILABLE',		defined('UPDATE_DVB_CHANNELS_ACTION_ID'));
		define('NEWGUI_FEAUTURES_AVAILABLE',	class_exists("PluginRowsFolderView"));

		$fw = get_parsed_firmware_ver();

		define('DUNE_FIRMWARE_STR',				$fw['string'] . (NEWGUI_FEAUTURES_AVAILABLE? ' (NewGUI)' : ''));
		define('DUNE_FIRMWARE_FT',				$fw['features']);
		define('DUNE_FIRMWARE_BN',				$fw['branch_num']);
		define('DEBUG_MODE_ON',					preg_match('/\/storage\//', $plugin_path) && is_dir("$plugin_path/.platform.android"));


		//if (!product_is_apk() && !file_exists('/tmp/verimatrix/hls_verimatrix_web'))
		//{
		//	$vmx_path = get_paved_path('/tmp/verimatrix');
		//	file_put_contents("$vmx_path/hls_verimatrix_web", '1');
		//}

		$update_manifest_path = '/tmp/www/home_tv_update30.xml';
		$repeater_path = DuneSystem::$properties['install_dir_path'] . '/www/cgi-bin/repeater';

		if (!$debug_mode_on)
		{
			$wait = 10;

			while(!file_exists($update_manifest_path) && ($wait-- > 0))
			{
				hd_print("Wait file '$update_manifest_path'");
				usleep(500000);
			}

			hd_print("The file '$update_manifest_path' " . (file_exists($update_manifest_path)? '' : 'not ') . 'found!');
		}

		while(1)
		{
			if (file_exists($update_manifest_path))
			{
				$remote_repeater_version_index = 0;
				$remote_repeater_hash = '';

				if ($update_manifest = file_get_contents($update_manifest_path))
				{
					if ($update_xml = simplexml_load_string($update_manifest))
					{
						foreach($update_xml->plugin_version_descriptor as $plugin_version_descriptor)
							$remote_repeater_hash = strval($plugin_version_descriptor->repeater_version_descriptor->md5);

						if (strnatcasecmp(md5_file($repeater_path), $remote_repeater_hash) <> 0)
						{
							hd_print('Found new version of repeater script!');
							$new_script = http_get_document(strval($plugin_version_descriptor->repeater_version_descriptor->url));

							if (empty($new_script) || (strnatcasecmp(md5($new_script), $remote_repeater_hash) <> 0))
								hd_print('(1) Updating the repeater script was failed!');
							else if (file_put_contents($repeater_path, $new_script))
								hd_print('Script of repeater has been updated successfully!');
							else
								hd_print('(2) Updating the repeater script was failed!');
						}
					}

					$cached_update_manifest_path = get_paved_path(LOCAL_CACHE_PATH . '/update') . '/plugin_manifest.xml';

					if (strcmp($cached_update_manifest_path, $update_manifest_path) <> 0)
					{
						$cached_manifest = file_exists($cached_update_manifest_path)? file_get_contents($cached_update_manifest_path) : '';

						if (md5($update_manifest) <> md5($cached_manifest))
							@file_put_contents($cached_update_manifest_path, $update_manifest);
					}
				}
			}
			else
			{
				$update_manifest_path = get_paved_path(LOCAL_CACHE_PATH . '/update') . '/plugin_manifest.xml';

				if (file_exists($update_manifest_path))
					continue;
			}

			break;
		}

		if ($debug_mode_on && preg_match('/android/', get_platform_kind()))
			if ($repeater = file_get_contents($repeater_path))
				if (file_put_contents(get_paved_path('/tmp/www/cgi-bin') . '/repeater', $repeater))
					shell_exec('chmod -R +x "/tmp/www/cgi-bin/repeater"');

		$plugin_info = get_plugin_info('drm_def', 'action_id', 'check_update', 'auto_resume');
		$this->app_name = $plugin_info['app_name'];
		$this->app_caption = $plugin_info['app_caption'];
		$this->app_label = preg_replace('/(\sv\d*)/u', '', $plugin_info['app_caption']);
		$this->app_version = $plugin_info['app_version'];
		$this->app_version_idx = $plugin_info['app_version_idx'];
		$this->app_drm_id = empty($plugin_info['drm_def'])? '' : $plugin_info['drm_def'][0]['id'];
		$this->app_auto_resume_enable = empty($plugin_info['auto_resume'])? false : ($plugin_info['auto_resume'][0]['enable'] == 'yes');
		$this->parental_in_manifest = (strpos(serialize($plugin_info['action_id']), 'input_pin') !== false);
		$this->app_update_url_valid = (isset($plugin_info['check_update'][0]['url']) && ($plugin_info['check_update'][0]['url'] == DuneSystem::$properties['plugin_cgi_url'] . 'update'));

		$this->tv = new HomeTv($this);
		$this->sorter = new Sorter($this);
		$this->user_data = new UserData();
		$this->bin_screen = new TvBinScreen($this);
		$this->groups_screen = new TvGroupsScreen($this);
		$this->settings_screen = new SettingsScreen($this);
		$this->channels_editor = new TvChannelsEditor($this);
		$this->channels_screen = new TvChannelsScreen($this);
		$this->favorites_screen = new TvFavoritesScreen($this);
		$this->epg = new EpgEngine();
		$this->custom_epg = new CustomEPG($this, $this->epg);
		$this->launcher = new HomeTvLauncher($this);

		PlaybackPoints::init();
		SplashScreen::init($this, PLUGIN_IMG_PATH . '/bg/splash_screen.aai');

		if (EXT_EPG_AVAILABLE)
		{
			require_once 'addons/ext_epg/program_screen.php';

			$this->epg_events_screen = new ProgramScreen();
		}

		if (NEWGUI_FEAUTURES_AVAILABLE)
		{
			require_once 'addons/epfs/epfs_handler.php';

			EpfsHandler::init($this->tv, $this->epg);
		}
	}

	public function check_pf_activation($post_action)
	{
		$this->pf_enabled = false;
		$successful_action = UserInputHandlerRegistry::create_action($this->launcher, 'pf_check_successful', array('post_action' => serialize($post_action)));
		$failed_action = UserInputHandlerRegistry::create_action($this->launcher, 'pf_check_failed', array('post_action' => serialize($post_action)));

		return
			ActionFactory::run_builtin('pf_check', array('extra_text1' => 'Для воспроизведения стримов части ТВ-каналов требуется функционал Dune Extra!'), $successful_action, $failed_action);
	}
}

?>
