<?php

///////////////////////////////////////////////////////////////////////////////
// Control of the first plugin start

define('SHOW_SETUP_WIZARD',				0);
define('SHOW_LIST_OF_CHANGES',			1);
define('SHOW_SPECIAL_WARNING',			0);
define('BACKUP_PLAYLISTS_TO_CLOUD',		0);
define('EPG_CACHE_NEED_CLEAR',			0);
define('OLD_PLAYLIST_NOT_COMPATIBLE',	0);
define('OLD_USER_DATA_NOT_COMPATIBLE',	0);

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

class HomeTvLauncher implements UserInputHandler
{
	private $plugin;
	private	$repeater_ver_idx;

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

	private function init_plugin_cookies(&$plugin_cookies, $reset_to_default = false)
	{
		if (isset($plugin_cookies->use_drm))
			unset($plugin_cookies->use_drm);

		if (isset($plugin_cookies->npvr_src))
			unset($plugin_cookies->npvr_src);

		if (isset($plugin_cookies->epg_timeshift))
			unset($plugin_cookies->epg_timeshift);

		if (isset($plugin_cookies->favorite_channels))
			unset($plugin_cookies->favorite_channels);

		if (isset($plugin_cookies->excluded_channels))
			unset($plugin_cookies->excluded_channels);

		if (isset($plugin_cookies->platform_kind) || $reset_to_default)
			unset($plugin_cookies->platform_kind);

		if (isset($plugin_cookies->tv_groups_view_idx))
			unset($plugin_cookies->tv_groups_view_idx);

		if (!isset($plugin_cookies->app_version) || $reset_to_default)
			$plugin_cookies->app_version = '';

		if (!isset($plugin_cookies->scan_not_before))
			$plugin_cookies->scan_not_before = 0;

		if (!isset($plugin_cookies->auto_resume_enable) || $reset_to_default)
			$plugin_cookies->auto_resume_enable = ControlSwitchDefs::switch_off;

		if (!isset($plugin_cookies->autoplay_enable) || $reset_to_default)
		{
			if (isset($plugin_cookies->autoplay_mode))
			{
				$plugin_cookies->autoplay_enable = $plugin_cookies->autoplay_mode;
				unset($plugin_cookies->autoplay_mode);
			}
			else if (isset($plugin_cookies->auto_play))
			{
				$plugin_cookies->autoplay_enable = $plugin_cookies->auto_play;
				unset($plugin_cookies->auto_play);
			}
			else
				$plugin_cookies->autoplay_enable = ControlSwitchDefs::switch_on;
		}

		if (isset($plugin_cookies->autoplay_group_id))
		{
			unset($plugin_cookies->autoplay_group_id);
			if (isset($plugin_cookies->play_group_id))
				unset($plugin_cookies->play_group_id);
		}

		if (isset($plugin_cookies->autoplay_channel_id))
		{
			unset($plugin_cookies->autoplay_channel_id);
			if (isset($plugin_cookies->play_channel_id))
				unset($plugin_cookies->play_channel_id);
		}

		if (!isset($plugin_cookies->epg) || $reset_to_default)
		{
			$plugin_cookies->epg =
				json_encode(
					array
					(
						'enabled'		=> isset($plugin_cookies->epg_enable)? $plugin_cookies->epg_enable : ControlSwitchDefs::switch_on,
						'ext_enable'	=> isset($plugin_cookies->ext_epg_enable)? $plugin_cookies->ext_epg_enable : ControlSwitchDefs::switch_on,
						'fill_enable'	=> isset($plugin_cookies->epg_fill_enable)? $plugin_cookies->epg_fill_enable : ControlSwitchDefs::switch_on,
						'font_size'		=> isset($plugin_cookies->epg_font_size)? $plugin_cookies->epg_font_size : PLUGIN_FONT_SMALL,
					)
				);

			if (isset($plugin_cookies->epg_enable))
				unset($plugin_cookies->epg_enable);

			if (isset($plugin_cookies->epg_font_size))
				unset($plugin_cookies->epg_font_size);

			if (isset($plugin_cookies->ext_epg_enable))
				unset($plugin_cookies->ext_epg_enable);

			if (isset($plugin_cookies->epg_fill_enable))
				unset($plugin_cookies->epg_fill_enable);

			if (isset($plugin_cookies->epg_cache_enable))
				unset($plugin_cookies->epg_cache_enable);
		}
		else if (strpos($plugin_cookies->epg, 'cache_enable'))
		{
			$plugin_cookies_epg = json_decode($plugin_cookies->epg);
			$plugin_cookies->epg =
				json_encode(
					array
					(
						'enabled'		=> isset($plugin_cookies_epg->epg_enable)? $plugin_cookies_epg->epg_enable : ControlSwitchDefs::switch_on,
						'ext_enable'	=> isset($plugin_cookies_epg->ext_epg_enable)? $plugin_cookies_epg->ext_epg_enable : ControlSwitchDefs::switch_on,
						'fill_enable'	=> isset($plugin_cookies_epg->epg_fill_enable)? $plugin_cookies_epg->epg_fill_enable : ControlSwitchDefs::switch_on,
						'font_size'		=> isset($plugin_cookies_epg->epg_font_size)? $plugin_cookies_epg->epg_font_size : PLUGIN_FONT_SMALL,
					)
				);
		}
		else
		{
			if ($plugin_cookies_epg = json_decode($plugin_cookies->epg))
			{
				$providers = array();
				$parsers = $this->plugin->epg->get_parsers_list();

				if (isset($plugin_cookies_epg->services_priority))
				{
					foreach ($plugin_cookies_epg->services_priority as $epg_service)
						if (in_array($epg_service, $parsers))
							$providers[] = $epg_service;

					unset($plugin_cookies_epg->services_priority);
				}

				if (isset($plugin_cookies_epg->providers))
					foreach ($plugin_cookies_epg->providers as $epg_provider)
						if (in_array($epg_provider, $parsers))
							$providers[] = $epg_provider;

				$providers = array_values(array_unique(array_merge($providers, $parsers)));
				$plugin_cookies_epg->providers = $providers;
				$new_plugin_cookies_epg = json_encode($plugin_cookies_epg);

				if ($new_plugin_cookies_epg <> $plugin_cookies->epg)
					$plugin_cookies->epg = $new_plugin_cookies_epg;
			}
		}

		if (!isset($plugin_cookies->qfilter) || $reset_to_default)
		{
			if (isset($plugin_cookies->last_mile_tech))
			{
				$plugin_cookies->qfilter = ($plugin_cookies->last_mile_tech == 'adsl')? QualityDefs::lowest : (($plugin_cookies->last_mile_tech == 'adsl2')? QualityDefs::middle : QualityDefs::highest);
				unset($plugin_cookies->last_mile_tech);
			}
			else
				$plugin_cookies->qfilter = QualityDefs::highest;
		}

		if (!isset($plugin_cookies->tv_archives) || $reset_to_default)
		{
			if (isset($plugin_cookies->view_archive))
			{
				$plugin_cookies->tv_archives = json_encode(array('enabled' => $plugin_cookies->view_archive, 'playback_stream_type' => TvArchivePlaybackDefs::auto, 'reload_when_resume' => ControlSwitchDefs::switch_on));
				unset($plugin_cookies->view_archive);
			}
			else
				$plugin_cookies->tv_archives = json_encode(array('enabled' => ControlSwitchDefs::switch_on, 'playback_stream_type' => TvArchivePlaybackDefs::auto, 'reload_when_resume' => ControlSwitchDefs::switch_on));
		}

		if (!isset($plugin_cookies->playback_http) || $reset_to_default)
		{
			$plugin_cookies->playback_http =
				json_encode(
					array
					(
						'enabled'			=> isset($plugin_cookies->playback_hls_enabled)? $plugin_cookies->playback_hls_enabled : ControlSwitchDefs::switch_on,
						'secury_disable'	=> isset($plugin_cookies->http_secury)? (($plugin_cookies->http_secury == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on) : ControlSwitchDefs::switch_on,
						'hls_bs_prefer'		=> isset($plugin_cookies->hls_bitrate_prefer)? (($plugin_cookies->hls_bitrate_prefer == 'vbr_only')? HttpStreamsDefs::hls_abs : $plugin_cookies->hls_bitrate_prefer) : (product_is_apk()? HttpStreamsDefs::mpd_abs : HttpStreamsDefs::hls_abs),
						'buff_size_ms'		=> isset($plugin_cookies->hls_buff_size_ms)? $plugin_cookies->hls_buff_size_ms : (isset($plugin_cookies->buffering_ms)? $plugin_cookies->buffering_ms : '5000'),
					)
				);

			if (isset($plugin_cookies->playback_hls_enabled))
				unset($plugin_cookies->playback_hls_enabled);

			if (isset($plugin_cookies->hls_bitrate_prefer))
				unset($plugin_cookies->hls_bitrate_prefer);

			if (isset($plugin_cookies->hls_buff_size_ms))
				unset($plugin_cookies->hls_buff_size_ms);

			if (isset($plugin_cookies->buffering_ms))
				unset($plugin_cookies->buffering_ms);

			if (isset($plugin_cookies->http_secury))
				unset($plugin_cookies->http_secury);
		}

		if (!isset($plugin_cookies->location))
		{
			if (isset($plugin_cookies->sdp_root_url))
				unset($plugin_cookies->sdp_root_url);

			if (isset($plugin_cookies->sdp_ip_addr))
				unset($plugin_cookies->sdp_ip_addr);

			if (isset($plugin_cookies->sdp_source))
				unset($plugin_cookies->sdp_source);

			$plugin_cookies->location =
				json_encode(
					array
					(
						'id'		=> 700001,
						'tz_offset'	=> get_local_time_zone_offset(),
					)
				);
		}
		else if (is_null(json_decode($plugin_cookies->location . ' ')))
		{
			if (isset($plugin_cookies->sub_location))
			{
				$sub_location = intval($plugin_cookies->sub_location);
				unset($plugin_cookies->sub_location);
			}
			else
				$sub_location = 700001;

			if (isset($plugin_cookies->sdp_root_url))
				unset($plugin_cookies->sdp_root_url);

			$plugin_cookies->location =
				json_encode(
					array
					(
						'id'		=> empty($sub_location)? 700001 : $sub_location,
						'tz_offset'	=> get_local_time_zone_offset(),
					)
				);
		}
		else
		{
			$location = json_decode($plugin_cookies->location);

			if (!empty($location->sub) && !empty($location->tz_offset))
			{
				$location_id = intval($location->sub);
				$tz_offset = intval($location->tz_offset);
				$plugin_cookies->location =
					json_encode(
						array
						(
							'id'		=> empty($location->sub)? 700001 : $location->sub,
							'tz_offset'	=> empty($tz_offset)? get_local_time_zone_offset() : $tz_offset,
						)
					);
			}
			else if (empty($location->id))
				$plugin_cookies->location =
					json_encode(
						array
						(
							'id'		=> 700001,
							'tz_offset'	=> get_local_time_zone_offset(),
						)
					);
		}

		if (isset($plugin_cookies->time_zone_offset))
			unset($plugin_cookies->time_zone_offset);

		if (isset($plugin_cookies->groups_catalog))
			unset($plugin_cookies->groups_catalog);

		if (!isset($plugin_cookies->channels_search_delay) || $reset_to_default)
			$plugin_cookies->channels_search_delay = '604800';

		if (isset($plugin_cookies->autoscan_delay))
			unset($plugin_cookies->autoscan_delay);

		if (!isset($plugin_cookies->parental) || $reset_to_default)
		{
			$parental = '';

			if (isset($plugin_cookies->pin))
			{
				$parental = json_encode(array('enabled' => $plugin_cookies->parental, 'pin' => $plugin_cookies->pin));
				unset($plugin_cookies->pin);
			}

			if (file_exists('/tmp/home_tv_parental_str')) {
				$parental = file_get_contents('/tmp/home_tv_parental_str');
				unlink('/tmp/home_tv_parental_str');
			}

			if (empty($parental))
				$parental = json_encode(array('enabled' => ControlSwitchDefs::switch_off, 'pin' => ''));

			$plugin_cookies->parental = $parental;
		}

		if (isset($plugin_cookies->playback_udp) || $reset_to_default)
		{
			if (isset($plugin_cookies->udpxy))
			{
				$udpxy = json_decode($plugin_cookies->udpxy);
				$use_udpxy = $udpxy->enabled;
				$udpxy_ip_port = $udpxy->ip . ':' . $udpxy->port;
				$buff_size_ms = $udpxy->buff_size_ms;
				unset($plugin_cookies->udpxy);
			}
			else
			{
				if (file_exists('/tmp/run/active_network_connection.txt'))
					$network = parse_ini_file('/tmp/run/active_network_connection.txt');

				if (isset($plugin_cookies->use_udpxy))
				{
					$use_udpxy = ($plugin_cookies->use_udpxy == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;

					if (isset($plugin_cookies->use_proxy))
					{
						$use_udpxy = ($plugin_cookies->use_proxy == 'yes')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
						unset($plugin_cookies->use_proxy);
					}

					if (isset($plugin_cookies->udpxy_ip_port))
					{
						$udpxy_ip_port = ($use_udpxy == ControlSwitchDefs::switch_on)? (empty($plugin_cookies->udpxy_ip_port)? '192.168.1.1:4022' : $plugin_cookies->udpxy_ip_port) : '192.168.1.1:4022';
						unset($plugin_cookies->udpxy_ip_port);
					}
					else if (isset($plugin_cookies->proxy_ip_port))
					{
						$udpxy_ip_port = ($use_udpxy == ControlSwitchDefs::switch_on)? (empty($plugin_cookies->proxy_ip_port)? '192.168.1.1:4022' : $plugin_cookies->proxy_ip_port) : '192.168.1.1:4022';
						unset($plugin_cookies->proxy_ip_port);
					}
					else
						$udpxy_ip_port = (empty($network['router'])? '192.168.1.1' : $network['router']) . ':4022';

					$buff_size_ms = '1000';
					unset($plugin_cookies->use_udpxy);
				}
				else
				{
					$use_udpxy = ControlSwitchDefs::switch_off;
					$udpxy_ip_port = (empty($network['router'])? '192.168.1.1' : $network['router']) . ':4022';
					$buff_size_ms = '1000';
				}
			}

			$plugin_cookies->playback_udp =
				json_encode(
					array
					(
						'enabled'	=> isset($plugin_cookies->playback_udp_enabled)? $plugin_cookies->playback_udp_enabled : (isset($plugin_cookies->instead_multicast)? (($plugin_cookies->instead_multicast == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on) : (isset($plugin_cookies->playback_udp_multicast)? $plugin_cookies->playback_udp_multicast : ControlSwitchDefs::switch_off)),
						'udpxy'		=>
							array
							(
								'enabled'		=> $use_udpxy,
								'ip'			=> preg_replace('/:.*$/', '', $udpxy_ip_port),
								'port'			=> preg_replace('/^.*:/', '', $udpxy_ip_port),
								'buff_size_ms'	=> $buff_size_ms,
							)
					)
				);

			if (isset($plugin_cookies->playback_udp_enabled))
				unset($plugin_cookies->playback_udp_enabled);

			if (isset($plugin_cookies->instead_multicast))
				unset($plugin_cookies->instead_multicast);

			if (isset($plugin_cookies->playback_udp_multicast))
				unset($plugin_cookies->playback_udp_multicast);
		}

		if (!isset($plugin_cookies->playlist_export) || $reset_to_default)
		{
			if (isset($plugin_cookies->export_to_m3u))
			{
				$export_to_m3u = json_decode($plugin_cookies->export_to_m3u);
				$plugin_cookies->playlist_export =
					json_encode(
						array
						(
							'enabled' => $export_to_m3u->enabled,
							'path_m3u' => $export_to_m3u->path,
						)
					);
				unset($plugin_cookies->export_to_m3u);
			}
			else if (isset($plugin_cookies->export_m3u, $plugin_cookies->path_to_m3u))
			{
				$plugin_cookies->playlist_export =
					json_encode(
						array
						(
							'enabled' => $plugin_cookies->export_m3u,
							'path_m3u' => $plugin_cookies->path_to_m3u,
						)
					);

				unset($plugin_cookies->export_m3u, $plugin_cookies->path_to_m3u);
			}
			else
				$plugin_cookies->playlist_export =
					json_encode(
						array
						(
							'enabled' => ControlSwitchDefs::switch_off,
							'path_m3u' => '',
						)
					);
		}

		if (!isset($plugin_cookies->parsing_channels_opts) || $reset_to_default)
		{
			if (isset($plugin_cookies->parsing_similars_channels))
			{
				$plugin_cookies->parsing_channels_opts = json_encode(array('enable_grouping' => ($plugin_cookies->parsing_similars_channels <> 'none')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off));
				unset($plugin_cookies->parsing_similars_channels);
			}
			else
				$plugin_cookies->parsing_channels_opts = json_encode(array('enable_grouping' => ControlSwitchDefs::switch_on));
		}

		if (!isset($plugin_cookies->customs_control) || $reset_to_default)
		{
			$customs_control = json_decode(json_encode(array('check_skin_palette' => ControlSwitchDefs::switch_on, 'epg_key' => GUI_EVENT_KEY_INFO, 'clock_key' => GUI_EVENT_KEY_SELECT, 'clock_pos' => '120,80', 'repeat_key' => GUI_EVENT_KEY_CLEAR)));

			if (DUNE_FIRMWARE_BN >= 10)
			{
				if ($customs_control->epg_key == GUI_EVENT_KEY_MODE)
					$customs_control->epg_key = GUI_EVENT_KEY_INFO;

				if ($customs_control->clock_key == GUI_EVENT_KEY_MODE)
					$customs_control->clock_key = GUI_EVENT_KEY_SELECT;
			}

			$plugin_cookies->customs_control = json_encode($customs_control);
		}
		else
		{
			$customs_control = json_decode($plugin_cookies->customs_control);

			if (!isset($customs_control->repeat_key))
			{
				$customs_control->repeat_key = GUI_EVENT_KEY_CLEAR;
				$plugin_cookies->customs_control = json_encode($customs_control);
			}
		}

		if (!isset($plugin_cookies->favorites_enable) || $reset_to_default)
			$plugin_cookies->favorites_enable = ControlSwitchDefs::switch_on;

		if (!isset($plugin_cookies->tv_reminders) || $reset_to_default)
			$plugin_cookies->tv_reminders = 'a:0:{}';

		if (!isset($plugin_cookies->playback_dvb) || $reset_to_default || (strlen($plugin_cookies->playback_dvb) < 5))
		{
			$plugin_cookies->playback_dvb =
				json_encode(
					array
					(
						'enabled'	=> (isset($plugin_cookies->playback_dvb_enabled) && DVB_PLAYBACK_AVAILABLE)? $plugin_cookies->playback_dvb_enabled : ControlSwitchDefs::switch_off,
					)
				);

			if (isset($plugin_cookies->playback_dvb_enabled))
				unset($plugin_cookies->playback_dvb_enabled);
		}

		if (!DVB_PLAYBACK_AVAILABLE && ($plugin_cookies->playback_dvb == ControlSwitchDefs::switch_on))
			$plugin_cookies->playback_dvb = ControlSwitchDefs::switch_off;

		$install_disk = preg_replace('/(^\/(.*)\/.*$)/uU', '$2', DuneSystem::$properties['data_dir_path']);

		if (!isset($plugin_cookies->install_disk) || ($plugin_cookies->install_disk <> $install_disk))
			$plugin_cookies->install_disk = $install_disk;

		$hw_addr = get_mac_address();

		if (!isset($plugin_cookies->hw_addr) || ($plugin_cookies->hw_addr <> $hw_addr))
			$plugin_cookies->hw_addr = $hw_addr;
	}

	private function dump_plugin_cookies(&$plugin_cookies)
	{
		static $dumped = false;

		if ($dumped)
			return;

		$dumped = true;
		$location = json_decode($plugin_cookies->location);
		Wink()->set_location($location->id);
		$location_info = Wink()->get_location_info($location->id);

		hd_print("\n");
		hd_print('*** Plugin settings dump ***');
		$properties = json_decode(json_encode($plugin_cookies), true);

		if (ksort($properties))
			foreach($properties as $name => $value)
			{
				if ($name <> 'hw_addr')
					hd_print("$name = $value");
				else
					$hw_addr = $value;

				if ($name == 'location')
				{
					hd_print("location_id = {$location_info->mrf}-{$location_info->location_id}-{$location_info->sub_location_id}");
					hd_print("location_name = {$location_info->location_name} :: {$location_info->sub_location_name}");
				}
			}

		hd_print("*** *** *** *** *** *** ***\n");
		hd_print('***  Dune product info  ***');
		hd_print('product_id = ' . get_product_id());
		hd_print('platform_kind = ' . get_platform_kind());
		hd_print('firmware_ver = ' . DUNE_FIRMWARE_STR);

		if (isset($hw_addr))
			hd_print('hw_address = ' . $hw_addr);

		hd_print('ip_address = ' . get_ip_address());
		hd_print('pf_enabled = ' . ($this->plugin->pf_enabled? 'yes' : 'no'));
		hd_print("*** *** *** *** *** *** ***\n");
	}

	private function get_post_install_dialog_controls_defs(&$add_params)
	{
		static $all_steps = null;

		if (is_null($all_steps))
			$all_steps = $add_params['progress'];

		if (empty($all_steps))
			$all_steps = 1;

		$progress = 100 - round(($add_params['progress'] * 100)/$all_steps);

		if ($progress >= 99)
			$progress = 100;

		$defs = array();
		ControlFactory::add_vgap($defs, 20);
		ControlFactory::add_smart_label($defs, null, '<text size=' . PLUGIN_FONT_SMALL . '>' . (($progress < 100)? $add_params['message_txt'] : '') . '</text>');
		ControlFactory::add_vgap($defs, -24);
		ControlFactoryExt::add_progressbar($defs, 0, 950, $progress);
		ControlFactory::add_vgap($defs, -74);
		ControlFactory::add_smart_label($defs, null, '<gap width=980/><text>' . $progress . '%</text>');

		if ($add_params['timer'] > 0)
		{
			if ($progress < 100)
			{
				ControlFactory::add_label($defs, null, "Пожалуйста, подождите...");
				ControlFactory::add_vgap($defs, 153);
			}
			else
			{
				ControlFactory::add_multiline_label($defs, null, 'Приложение готово к запуску после перезагрузки программной оболочки медиаплеера.', 2);
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'close_splash_and_reboot_shell', 'Перезагрузить', 400);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1100);
			}
		}
		else
		{
			$first_loop = file_exists('/tmp/home_tv_was_installed_mark') || file_exists('/tmp/home_tv_was_updated_mark');

			if ($first_loop)
				$msg = 'Что-то пошло не так, подготовка к запуску не завершена! Попробуйте повторить после полной перезагрузки медиаплеера.';
			else
				$msg = 'Опять что-то пошло не так, невозможно нормально подготовить плагин к запуску. Плагин будет запущен аварийно. О проблеме, пожалуйста, сообщите разработчику: Brigadir (forum.mydune.ru)';

			ControlFactory::add_multiline_label($defs, null, $msg, 5);
			ControlFactory::add_vgap($defs, 40);

			if ($first_loop)
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'hard_reset', 'Перезагрузить', 400);
			else
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'plugin_entry', 'Запустить', 400);

			ControlFactoryExt::add_button_centered($defs, $button_defs, 1100);
		}

		ControlFactory::add_vgap($defs, 20);

		return $defs;
	}

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

	public function __construct(&$plugin)
	{
		$this->plugin = $plugin;
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

	public function get_handler_id()
	{
		return 'plugin_launcher';
	}

	public function reset_plugin_settings(&$plugin_cookies)
	{
		$this->init_plugin_cookies($plugin_cookies, true);
	}

	public function get_update_epg_action($channel_id, $day_ts, &$plugin_cookies, $post_action = null)
	{
		//if ((($this->stb_firmware->branch_num == 11) && ($this->stb_firmware->build_date >= 190919)) || ($this->stb_firmware->branch_num > 12))
		{
			//r11, r13
			$epg = $this->plugin->epg->get_day_epg($channel_id, $day_ts, $plugin_cookies);
//foreach($epg as &$data)
//{
//	$data['name'] .= '_000';
//}
//var_export($epg);
//$json_fname = get_paved_path('/tmp/ext_epg/') . "/$channel_id-" . strftime('%Y-%m-%d', $day_ts) . '.json';
//clearstatcache();
//var_export(file_get_contents($json_fname));

			if (!empty($epg))
				return ActionFactorySafe::update_epg($channel_id, true, $day_ts, $epg, $post_action);
		}

		return $post_action;
	}

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		static $add_params = array();
		static $plugin_was_installed = false;
		static $plugin_was_updated = false;
		static $need_update_playlists_cache = false;
		static $plugin_cache_was_corupted = false;

		if (!isset($user_input->control_id))
			return null;

		$add_params['dialog_frame_style'] = isset($user_input->dialog_frame_style)? $user_input->dialog_frame_style : DIALOG_FRAME_STYLE_DEFAULT;

		switch ($user_input->control_id)
		{
			case 'recent':
				//$callback = json_decode($user_input->callback_url);
				$media_url = MediaURL::decode($user_input->media_url);//$callback->{GuiAction::params}->media_url);
				$media_url->screen_id = $this->plugin->epg_events_screen->get_id();

				$this->plugin->epg_events_screen->invalidate();
				$this->plugin->epg_events_screen->program_event_data = $this->plugin->epg->get_program_event($media_url->channel_id, $media_url->start_tm);

				if (!is_array($this->plugin->epg_events_screen->program_event_data))
					return null;

				$this->plugin->epg_events_screen->program_event_tm = $media_url->start_tm;
				$action = $this->get_update_epg_action($media_url->channel_id, $this->plugin->epg->get_day_start_ts($media_url->start_tm), $plugin_cookies, ActionFactory::open_folder($media_url->get_raw_string()));

				return $action;

			case 'plugin_entry':
				DunePalettePatcher::init();
				$this->init_plugin_cookies($plugin_cookies);

				if (isset($user_input->action_id) && ($user_input->action_id == 'uninstall'))
				{
					$apps = array();
					$epg_cache_used_bytes = 0;

					if (file_exists('/config/libViewRightWebClient.so'))
						unlink('/config/libViewRightWebClient.so');

					if (file_exists('/config/home_tv_was_installed_mark'))
						unlink('/config/home_tv_was_installed_mark');

					if (file_exists('/tmp/home_tv_was_installed_mark'))
						unlink('/tmp/home_tv_was_installed_mark');

					if (file_exists('/tmp/home_tv_was_updated_mark'))
						unlink('/tmp/home_tv_was_updated_mark');

					if (file_exists('/tmp/home_tv_history_was_shown_mark'))
						unlink('/tmp/home_tv_history_was_shown_mark');

					if (file_exists('/tmp/home_tv_epg_cache_was_cleared_mark'))
						unlink('/tmp/home_tv_epg_cache_was_cleared_mark');

					if (file_exists('/tmp/home_tv_cache_was_cleared_mark'))
						unlink('/tmp/home_tv_cache_was_cleared_mark');

					if (file_exists('/tmp/home_tv_was_reloaded_mark'))
						unlink('/tmp/home_tv_was_reloaded_mark');

					if (file_exists('/tmp/home_tv_do_scan_channels'))
						unlink('/tmp/home_tv_do_scan_channels');

					foreach($this->plugin->epg->get_disk_cache_info() as $epg_cache_info)
					{
						$epg_cache_used_bytes += $epg_cache_info['used_bytes'];

						foreach($epg_cache_info['apps'] as $app)
						{
							if ($app['name'] == $this->plugin->app_name)
							{
								unlink($epg_cache_info['base_dir'] . '/apps/' . $app['tag']);
								continue;
							}

							$apps['caption'][$app['name']] = $app['caption'];
							$apps['icon_url'][$app['name']] = isset($app['icon_url'])? $app['icon_url'] : '';
							$apps['badge_icon_url'][$app['name']] = isset($app['badge_icon_url'])? $app['badge_icon_url'] : '';
							$apps['override_default_badge'][$app['name']] = isset($app['override_default_badge'])? $app['override_default_badge'] : '';
							$apps['icon_fit_scale_factor'][$app['name']] = isset($app['icon_fit_scale_factor'])? $app['icon_fit_scale_factor'] : '';
						}
					}

					if (!empty($epg_cache_used_bytes))
					{
						if (!empty($apps['caption']))
						{
							$count = 0;
							ControlFactoryExt::add_multiline_label($defs, null, "Кэш телепрограммы занимает на диске " . (($epg_cache_used_bytes > 999999)? round($epg_cache_used_bytes / 1000000, 1) . ' МБ' : (($epg_cache_used_bytes > 999)? round($epg_cache_used_bytes / 1000, 1) . ' КБ' : $epg_cache_used_bytes . ' Байт')) . ", и все еще используется плагинами.", 10);
							ControlFactoryExt::add_vgap($defs, 30);

							foreach($apps['caption'] as $app_name => $app_caption)
							{
								if (++$count > 6)
									break;

								$margin_left = ($count < 4)? 40 : 610;
								$icon_size = 50;
								ControlFactoryExt::add_vgap($defs1, ($count == 4)? -69*3 + 20 : -10);

								if (!empty($apps['badge_icon_url'][$app_name]) && (empty($apps['override_default_badge'][$app_name]) || ($apps['override_default_badge'][$app_name] == 'yes')))
								{
									ControlFactoryExt::add_smart_label($defs1, null, "<gap width=$margin_left/><icon width=$icon_size height=$icon_size>" . $apps['badge_icon_url'][$app_name] . '</icon>');
									ControlFactoryExt::add_vgap($defs1, -69);
								}

								if (!empty($apps['icon_url'][$app_name]))
								{
									$icon_size -= 4;
									ControlFactoryExt::add_smart_label($defs1, null, "<gap width=" . ($margin_left + 2) . "/><icon dy=2 width=$icon_size height=$icon_size>" . $apps['icon_url'][$app_name] . '</icon>');
									ControlFactoryExt::add_vgap($defs1, -69);
								}

								ControlFactoryExt::add_smart_label($defs1, null, "<gap width=" . ($margin_left + 68) . "/><text>$app_caption</text>");
							}

							if (($count > 3) && ($count < 6))
								ControlFactoryExt::add_vgap($defs1, (69 * (6 - $count)) - 10);

							$post_action = DunePalettePatcher::get_uninstall_plugin_action(SplashScreen::close_and_run());
							ControlFactoryExt::add_group_box($defs, $defs1, 'Приложения использующие кэш телепрограммы:', 1200);
							ControlFactoryExt::add_vgap($defs, 20);
							ControlFactoryExt::add_label($defs, null, 'Хотите высвободить занимаемое пространство в памяти?');
							ControlFactoryExt::add_vgap($defs, 40);
							ControlFactoryExt::add_custom_close_dialog_and_apply_button($button_defs, null, 'Удалить данные', 500, UserInputHandlerRegistry::create_action($this, 'clear_epg_cache', array('post_action' => serialize($post_action))));
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1200);
							ControlFactoryExt::add_custom_close_dialog_and_apply_button($button_defs, null, 'Пропустить', 500, $post_action);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1200);
							ControlFactoryExt::add_vgap($defs, 10);

							return
								SplashScreen::open_and_run(
									ActionFactorySafe::show_dialog(
										'Внимание!',
										$defs,
										false,
										1200,
										array
										(
											'initial_sel_ndx' => 1,
											'dialog_params' => array('frame_style' => $add_params['dialog_frame_style']),
										)
									)
								);
						}
						else
							$this->plugin->epg->clear_cache();
					}

					return
						SplashScreen::open_and_run(DunePalettePatcher::get_uninstall_plugin_action(SplashScreen::close_and_run()));
				}

				$add_params = array('dialog_frame_style' => $add_params['dialog_frame_style']);

				if (isset($user_input->mandratory_playback))
					$add_params['mandratory_playback'] = $user_input->mandratory_playback;

				$this->plugin->tv->parental_passed = false;
				$this->plugin->tv->parental = json_decode($plugin_cookies->parental);
				$need_update_playlists_cache = false;

				if (!file_exists(PLAYLISTS_CACHE_PATH . '/tv'))
				{
					$old_playlists_dir = LOCAL_CACHE_PATH . '/playlist';

					if (file_exists($old_playlists_dir))
						rename($old_playlists_dir, PLAYLISTS_CACHE_PATH);
					else
						foreach(glob(PLAYLISTS_CACHE_PATH . '/*') as $dir)
							if (is_dir($dir) && (basename($dir) <> 'radio'))
								foreach(glob($dir . '/*') as $file)
									if (is_file($file))
									{
										$need_update_playlists_cache = true;
										break 2;
									}
				}

				if (DEBUG_MODE_ON && !file_exists('/tmp/www/cgi-bin/register_supplier'))
				{
					$plugin_path = dirname(__FILE__);

					if (!file_exists('/tmp/www/cgi-bin/register_supplier'))
					{
						shell_exec('cp ' . "$plugin_path/.platform.android/bin/register_supplier /tmp/www/cgi-bin/register_supplier");
						shell_exec('chmod -R +x "/tmp/www/cgi-bin/register_supplier"');
					}

					shell_exec('exec /tmp/www/cgi-bin/register_supplier');
					hd_print('Debug mode activated successfully!');
				}

				$plugin_was_installed = file_exists('/tmp/home_tv_was_installed_mark') || file_exists('/config/home_tv_was_installed_mark');
				$plugin_was_updated = file_exists('/tmp/home_tv_was_updated_mark');
				$plugin_cache_was_corupted = defined('CUSTOM_EPG_RES_PATH') && !CUSTOM_EPG_SCREEN_AVAILABLE;

				ControlFactoryExt::init();
				OSDComponentFactory::init();

				if (cenc_drm_support())
				{
					$params['dialog_frame_style'] = $add_params['dialog_frame_style'];

					if (isset($user_input->action_id))
						$params['action_id'] = $user_input->action_id;

					if (isset($user_input->mandratory_playback))
						$params['mandratory_playback'] = $user_input->mandratory_playback;

					if (isset($user_input->initial_media_url))
						$params['initial_media_url'] = $user_input->initial_media_url;

					if (isset($user_input->resume_mode))
					{
						$params['resume_mode'] = $user_input->resume_mode;
						$params['resume_tv_group'] = isset($user_input->resume_tv_group)? $user_input->resume_tv_group : null;
						$params['resume_tv_channel'] = isset($user_input->resume_tv_channel)? $user_input->resume_tv_channel : null;
						$params['resume_tv_archive_tm'] = isset($user_input->resume_tv_archive_tm)? $user_input->resume_tv_archive_tm : null;
						$params['resume_tv_is_favorite'] = isset($user_input->resume_tv_is_favorite)? $user_input->resume_tv_is_favorite : false;
					}

					return
						$this->plugin->check_pf_activation(UserInputHandlerRegistry::create_action($this, 'pf_checked', $params));
				}
				else
					$this->plugin->pf_enabled = false;

			case 'pf_checked':
				$this->dump_plugin_cookies($plugin_cookies); // Дамп настроек плагина

				if (isset($user_input->action_id) && ($user_input->action_id == 'update_epfs'))
				{
					if (!$plugin_was_installed && !$plugin_was_updated)
						if (NEWGUI_FEAUTURES_AVAILABLE)
						{
							EpfsHandler::update_all_epfs(isset($user_input->first_run_after_boot) || isset($user_input->restore_from_sleep), $plugin_cookies);

							return
								EpfsHandler::invalidate_folders();
						}

					return null;
				}

				if ($need_update_playlists_cache || $plugin_was_installed || $plugin_was_updated)
				{
					if (isset($user_input->action_id))
						$add_params['action_id'] = $user_input->action_id;

					return
						SplashScreen::open_and_run(UserInputHandlerRegistry::create_action($this, 'launch', $add_params));
				}

				if (isset($user_input->resume_mode))
				{
					if (isset($user_input->mandratory_playback) && ($plugin_cookies->autoplay_enable == ControlSwitchDefs::switch_off))
					{
						$resume_state = str_replace('PLUGIN_TV_PLAYBACK', 'DEFAULT', file_get_contents('/config/resume_state.properties'), $result);

						if ($result > 0)
							file_put_contents('/config/resume_state.properties', $resume_state);

						$add_params['mandratory_playback'] = 0;
					}
					else
					{
						$media_url = MediaURL::decode();
						$media_url->group_id = isset($user_input->resume_tv_group)? $user_input->resume_tv_group : null;
						$media_url->channel_id = $user_input->resume_tv_channel;
						$media_url->archive_tm = ((time() - $user_input->resume_tv_archive_tm) < HomeTv::archive_past_sec)? $user_input->resume_tv_archive_tm : -1;
						$media_url->is_favorite = $user_input->resume_tv_is_favorite;
						$add_params['initial_media_url'] = $media_url->get_raw_string();
					}

					if (isset($user_input->mandratory_playback))
						return
							UserInputHandlerRegistry::create_action($this->plugin->tv, 'tv_play', $add_params);
				}

				return
					SplashScreen::open_and_run(UserInputHandlerRegistry::create_action($this, isset($user_input->action_id)? $user_input->action_id : 'launch', $add_params));

			case 'pf_check_successful':
				$check_successful = true;

			case 'pf_check_failed':
				$this->plugin->pf_enabled = !empty($check_successful);

				return
					unserialize($user_input->post_action);

			case 'launch':
				clearstatcache();

				if (!$this->plugin->app_update_url_valid || $need_update_playlists_cache || $plugin_was_installed || $plugin_was_updated || ($plugin_cache_was_corupted && (disk_free_space(USER_DATA_CACHE_PATH) >= 35000000)))
				{
					if (!file_exists('/tmp/home_tv_was_reloaded_mark'))
					{
						@file_put_contents('/tmp/home_tv_was_reloaded_mark', '');

						if (file_exists('/tmp/www/cgi-bin/epg'))
							unlink('/tmp/www/cgi-bin/epg');

						$add_params['timer'] = 20;
						$add_params['unpack_bg'] = ($plugin_cache_was_corupted)? 4 : 0;
						$add_params['upload_playlists'] = 0;

						if ($plugin_was_installed || $plugin_was_updated)
						{
							if (!$need_update_playlists_cache && BACKUP_PLAYLISTS_TO_CLOUD)
							{
								if (file_exists(PLAYLISTS_CACHE_PATH . '/tv'))
									foreach(glob(PLAYLISTS_CACHE_PATH . '/tv/*') as $dir)
										if (is_dir($dir) && (basename($dir) <> 'radio'))
											foreach(glob("$dir/*") as $file)
												$add_params['upload_playlists']++;
							}
							else if (BACKUP_PLAYLISTS_TO_CLOUD)
							{
								if (file_exists(LOCAL_CACHE_PATH . '/playlist'))
									rename(LOCAL_CACHE_PATH . '/playlist', PLAYLISTS_CACHE_PATH);

								foreach(glob(PLAYLISTS_CACHE_PATH . '/*') as $dir)
									if (is_dir($dir) && (basename($dir) <> 'radio'))
										foreach(glob("$dir/*") as $file)
											if (is_file($file))
												$add_params['upload_playlists']++;
							}
						}

						$add_params['timer'] += $add_params['upload_playlists'];
						$add_params['update_manifest'] = intval(!$this->plugin->app_update_url_valid ||
							(($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->parental_in_manifest) ||
							(($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_off) && $this->plugin->parental_in_manifest)||
							(($plugin_cookies->auto_resume_enable == ControlSwitchDefs::switch_on) && !$this->plugin->app_auto_resume_enable) ||
							(($plugin_cookies->auto_resume_enable == ControlSwitchDefs::switch_off) && $this->plugin->app_auto_resume_enable));
						$add_params['update_data_cache'] = 1;
						$add_params['update_playlist_cache'] = intval($need_update_playlists_cache);
						$add_params['progress'] = $add_params['unpack_bg'] + $add_params['update_manifest'] + $add_params['update_data_cache'] + $add_params['update_playlist_cache'] + $add_params['upload_playlists'];
						$add_params['message_txt'] = '';

						return
							ActionFactorySafe::show_dialog
							(
								'Подготовка приложения к запуску',
								$this->get_post_install_dialog_controls_defs($add_params),
								false,
								1100,
								array
								(
									'dialog_params' => array('frame_style' => $add_params['dialog_frame_style']),
									'actions' => array(GUI_EVENT_TIMER => UserInputHandlerRegistry::create_action($this, 'post_install_progress')),
									'timer' => ActionFactorySafe::timer(500),
								)
							);
					}

					if ($plugin_was_installed || $plugin_was_updated)
					{
						// Показ окна истории версий плагина
						if (SHOW_LIST_OF_CHANGES && $plugin_was_updated && !file_exists('/tmp/home_tv_history_was_shown_mark'))
						{
							@file_put_contents('/tmp/home_tv_history_was_shown_mark', '');

							return
								$this->plugin->settings_screen->show_dialog(SettingsDialogsDefs::whats_new, $add_params['dialog_frame_style'], UserInputHandlerRegistry::create_action($this, isset($user_input->action_id)? $user_input->action_id : 'launch', $add_params));
						}

						if (SHOW_SPECIAL_WARNING && (preg_replace('/\s*\(.*$/u', '', str_replace('.', '', $plugin_cookies->app_version)) < 310) && !file_exists('/tmp/home_tv_special_warning_was_shown_mark'))
						{
							@file_put_contents('/tmp/home_tv_special_warning_was_shown_mark', '');
							ControlFactory::add_multiline_label($defs, null, "Текущая версия плагина содержит экспериментальный хак, позволяющий воспроизводить ABS потоки. Хак протестирован на разных моделях Dune HD, хак не работает на платформах ARM от Sigma Design (Solo/Solo Lite/Duo 4K).\n\n В целях конфиденциальности прошу не шуметь на каждом углу по поводу \"внезапно заработавшей забавы\", если радуемся - то тихо, если не работает - пишем на форум mydune.ru без лишних слов и подробностей.\n\nИ еще пара слов об авторах хака, которых, возможно, Вы захотите отблагодарить:\nMityagin.Spb.Ru (forum.mydune.ru) - идея и пример реализации хака;\nddaaff (forum.mydune.ru) - адаптация под андройд платформы, упаковщик скриптов;\nBrigadir (forum.mydune.ru) - принимал участие во всем этом ;)", 12);
							ControlFactory::add_vgap($defs, 40);
							ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, $add_params, 'launch', 'Продолжить', 400);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
							ControlFactory::add_vgap($defs, 20);

							return
								ActionFactorySafe::show_dialog('Уважаемый пользователь!', $defs, false, 1400, array('dialog_params' => array('frame_style' => $add_params['dialog_frame_style'])));
						}

						if (EPG_CACHE_NEED_CLEAR && $plugin_was_updated && !file_exists('/tmp/home_tv_epg_cache_was_cleared_mark'))
							return
								UserInputHandlerRegistry::create_action($this, 'clear_epg_cache_once', $add_params);

						if (OLD_PLAYLIST_NOT_COMPATIBLE && $plugin_was_updated && !file_exists('/tmp/home_tv_cache_was_cleared_mark') && file_exists(ICONS_CACHE_PATH . '/c50x50'))
						{
							// Показ диалога необходимости очистки кэша плейлистов
							ControlFactory::add_multiline_label($defs, null, "В связи с изменениями в структуре хранимых данных, плейлисты предыдущих версий плагина теперь несовместимы. Пожалуйста, нажмите \"Продолжить\", чтобы очистить хранилище плейлистов.", 12);
							ControlFactory::add_vgap($defs, 40);
							ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, $add_params, 'clear_data_cache_once', 'Продолжить', 400);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
							ControlFactory::add_vgap($defs, 20);

							return
								ActionFactorySafe::show_dialog('Уважаемый пользователь!', $defs, false, 1400, array('dialog_params' => array('frame_style' => $add_params['dialog_frame_style'])));
						}

						if (OLD_USER_DATA_NOT_COMPATIBLE && $plugin_was_updated && !file_exists('/tmp/home_tv_cache_was_cleared_mark'))
						{
							// Показ диалога необходимости очистки кэша пользовательских данных
							ControlFactory::add_multiline_label($defs, null, "В данной версии (и далее) исправлен баг с отставанием времени расписания телепередач в источнике EPG \"Ростелеком-Москва\".\n\nВозможно установленный ранее сдвиг телепрограммы на всех каналах должен быть обнулен.\n\nНажмите \"Продолжить\", чтобы запустить процедуру исправления.", 12);
							ControlFactory::add_vgap($defs, 40);
							ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, $add_params, 'clear_data_cache_once', 'Продолжить', 400);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
							ControlFactory::add_vgap($defs, 20);

							return
								ActionFactorySafe::show_dialog('Уважаемый пользователь!', $defs, false, 1400, array('dialog_params' => array('frame_style' => $add_params['dialog_frame_style'])));
						}

						// Показ диалога успешной очистки кэша и перехода к поиску каналов
						if (OLD_PLAYLIST_NOT_COMPATIBLE && $plugin_was_updated && !file_exists('/tmp/home_tv_do_scan_channels') && (count(glob(PLAYLISTS_CACHE_PATH . '/tv/*')) == 0))
						{
							@file_put_contents('/tmp/home_tv_do_scan_channels', '');
							ControlFactory::add_multiline_label($defs, null, "Теперь осталось найти каналы и можно смотреть!\n\nПожалуйста, нажмите \"Поиск каналов\" и дождитесь окончания процедуры поиска.", 10);
							ControlFactory::add_vgap($defs, 40);
							ControlFactory::add_close_dialog_and_apply_button($button_defs, $this->plugin->tv, $add_params + array('post_action_id' => 'restart_plugin', 'close_by_return' => false), 'do_show_scan_opts', 'Поиск каналов', 400);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
							ControlFactory::add_vgap($defs, 20);

							return
								ActionFactorySafe::show_dialog('Процедура очистки успешно завершена!', $defs, false, 1400, array('dialog_params' => array('frame_style' => $add_params['dialog_frame_style'])));
						}

						if (file_exists('/config/home_tv_was_installed_mark'))
							unlink('/config/home_tv_was_installed_mark');

						if (file_exists('/tmp/home_tv_was_installed_mark'))
							unlink('/tmp/home_tv_was_installed_mark');

						if (file_exists('/tmp/home_tv_was_updated_mark'))
							unlink('/tmp/home_tv_was_updated_mark');

						if (file_exists('/tmp/home_tv_history_was_shown_mark'))
							unlink('/tmp/home_tv_history_was_shown_mark');

						if (file_exists('/tmp/home_tv_epg_cache_was_cleared_mark'))
							unlink('/tmp/home_tv_epg_cache_was_cleared_mark');

						if (file_exists('/tmp/home_tv_cache_was_cleared_mark'))
							unlink('/tmp/home_tv_cache_was_cleared_mark');

						if (file_exists('/tmp/home_tv_was_reloaded_mark'))
							unlink('/tmp/home_tv_was_reloaded_mark');

						if (file_exists('/tmp/home_tv_do_scan_channels'))
							unlink('/tmp/home_tv_do_scan_channels');
					}
					else
					{
						if (SHOW_SETUP_WIZARD && ($plugin_cookies->app_version == ''))
							return
								$this->plugin->settings_screen->show_dialog(SettingsDialogsDefs::quick_config, $add_params['dialog_frame_style'], UserInputHandlerRegistry::create_action($this->plugin->tv, 'start_plugin', $add_params));

						$plugin_cookies->app_version = $this->plugin->app_version;

						if (file_exists('/tmp/home_tv_was_reloaded_mark'))
							unlink('/tmp/home_tv_was_reloaded_mark');

						if (file_exists('/tmp/home_tv_was_installed_mark'))
							unlink('/tmp/home_tv_was_installed_mark');

						if (file_exists('/config/home_tv_was_installed_mark'))
							unlink('/config/home_tv_was_installed_mark');
					}

					if (file_exists('/tmp/home_tv_special_warning_was_shown_mark'))
					{
						unlink('/tmp/home_tv_special_warning_was_shown_mark');
						ControlFactory::add_multiline_label($defs, null, "Сейчас необходимо перезагрузить операционную систему медиаплеера!", 10);
						ControlFactory::add_vgap($defs, 40);
						ControlFactory::add_close_dialog_and_apply_button($button_defs, $this->plugin->launcher, null, 'hard_reset', 'Перезагрузить', 450);
						ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
						ControlFactory::add_vgap($defs, 10);

						return
							ActionFactorySafe::show_dialog(
								'ВНИМАНИЕ!',
								$defs,
								false,
								1300,
								array
								(
									'dialog_params' =>
										array
										(
											'frame_style' => (DUNE_FIRMWARE_BN <= 8)? DIALOG_FRAME_STYLE_DEFAULT : DIALOG_FRAME_STYLE_GLASS,
										),
								)
							);
					}
				}

				if (SHOW_SETUP_WIZARD && ($plugin_cookies->app_version == ''))
				{
					if (!file_exists('/tmp/home_tv_was_installed_mark'))
						@file_put_contents('/tmp/home_tv_was_installed_mark', '');

					return
						$this->plugin->settings_screen->show_dialog(SettingsDialogsDefs::quick_config, $add_params['dialog_frame_style'], UserInputHandlerRegistry::create_action($this->plugin->tv, 'do_need_reboot', $add_params));
				}

				$plugin_cookies->app_version = $this->plugin->app_version;
				$this->plugin->epg->clear_ram_cache();

				return
					UserInputHandlerRegistry::create_action($this->plugin->tv, 'start_plugin', $add_params);

			case 'input_pin':
				return
					$this->plugin->tv->get_input_pin_dialog_action($this, $add_params);

			case 'pin_field':
				$this->plugin->tv->parental_passed = (md5(DuneSystem::$properties['plugin_name'] . $user_input->pin_field) === $this->plugin->tv->parental->pin);

				return
					ActionFactorySafe::close_dialog_and_run(SplashScreen::open_and_run($this->plugin->check_pf_activation(UserInputHandlerRegistry::create_action($this, 'launch', $add_params))));

			case 'open_setup':
				$customs_control = json_decode($plugin_cookies->customs_control);

				if (($customs_control->check_skin_palette == ControlSwitchDefs::switch_on) &&
					($skin_palette_check_action = DunePalettePatcher::get_skin_palette_check_action(
							$open_setup_action = UserInputHandlerRegistry::create_action($this, $user_input->control_id, $add_params),
							UserInputHandlerRegistry::create_action($this->plugin->tv, 'disable_check_palette', array('post_action' => serialize($open_setup_action))),
							$user_input->dialog_frame_style)))
					return
						$skin_palette_check_action;

				if (!isset($user_input->parent_media_url))
					$this->plugin->tv->parental_passed = false;

				$this->plugin->tv->parent_media_url_str = isset($user_input->parent_media_url)? $user_input->parent_media_url : '';

				return
					SplashScreen::close_and_run(ActionFactorySafe::open_folder(SettingsScreen::get_media_url_str()));//FoldersManager::open_folder(SettingsScreen::get_media_url_str()));

			case 'post_install_progress':
				$add_params['timer'] -= 1;
				$post_action = ActionFactorySafe::change_behaviour(array(GUI_EVENT_TIMER => UserInputHandlerRegistry::create_action($this, 'post_install_progress')), ActionFactorySafe::timer(100));

				if ($add_params['update_playlist_cache'] > 0)
				{
					if (empty($add_params['message_updated']))
					{
						$add_params['message_txt'] = 'Упорядочивание файлов в кэше';
						$add_params['message_updated'] = true;

						return
							ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
					}

					foreach(glob(PLAYLISTS_CACHE_PATH . "/*") as $dir)
					{
						if (is_dir($dir) && (basename($dir) <> 'radio') && (basename($dir) <> 'tv'))
						{
							foreach(glob($dir . "/*") as $file)
							{
								hd_print("Found beyond playlists dir $dir");

								if (is_file($file))
								{
									$add_params['update_playlist_cache'] -= 1;
									hd_print("Move $file to " . PLAYLISTS_CACHE_PATH . "/tv/" . basename($dir) . "/" . basename($file));
									copy($file, get_paved_path(PLAYLISTS_CACHE_PATH . "/tv/" . basename($dir)) . "/" . basename($file));
									unlink($file);
								}
							}

							rmdir($dir);
						}
					}

					$add_params['progress'] -= 1;
					$add_params['update_playlist_cache'] = 0;
					$add_params['message_updated'] = false;

					return
						ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
				}

				if ($add_params['upload_playlists'])
				{
					if (empty($add_params['message_updated']))
					{
						$add_params['message_txt'] = 'Передача плейлистов плагина';
						$add_params['message_updated'] = true;
						$sysinfo = file('/tmp/sysinfo.txt', FILE_IGNORE_NEW_LINES);

						foreach($sysinfo as $line)
							if (preg_match('/serial_number:\s+(.+)/', $line, $matches))
							{
								$add_params['dune_serial'] = $matches[1];
								break;
							}

						return
							ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
					}

					if (empty($add_params['uploaded_playlists']))
						$add_params['uploaded_playlists'] = '.';

					while($add_params['upload_playlists'])
					{
						if (file_exists(PLAYLISTS_CACHE_PATH . '/tv'))
							foreach(glob(PLAYLISTS_CACHE_PATH . '/tv/*') as $dir)
								if (is_dir($dir))
									foreach(glob("$dir/*") as $file)
										if (!strpos($add_params['uploaded_playlists'], $file) && is_file($file))
										{
											$path = basename($dir) . '/' . basename($file) . '/' . $add_params['dune_serial'];
											http_post_document(decode_str('d8aHR0cDovL3BsdWdpbnMubXlkdW5lLnJ1L2JyaWdhZGlyL2hvbWVfdHYvYWNjZXB0LnBocA'), "dir=TV_PLAYLISTS/$path&file=" . base64_encode(file_get_contents($file)));
											$add_params['uploaded_playlists'] .= $file;
											$add_params['progress'] -= 1;
											break 3;
										}

						$add_params['upload_playlists'] = 0;
					}

					$add_params['message_updated'] = false;

					return
						ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
				}

				if ($add_params['update_data_cache'] > 0)
				{
					if (empty($add_params['message_updated']))
					{
						$add_params['message_txt'] = 'Проверка данных кэша';
						$add_params['message_updated'] = true;

						return
							ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
					}

					foreach(glob(USER_DATA_CACHE_PATH . '/*') as $user_data_file)
					{
						$changed = false;
						$user_data = unserialize(file_get_contents($user_data_file));

						foreach($user_data as &$data)
							if (isset($data['epg_id']) && !preg_match('/rt|smartlabs|vsetv|yandex@/ui', $data['epg_id']))
							{
								if (is_numeric($data['epg_id']))
									$data['epg_id'] = ((strlen($data['epg_id']) >= 5)? 'rt@' : 'vsetv@') . $data['epg_id'];
								else
									unset($data['epg_id']);

								$changed = true;
							}

						if ($changed)
							file_put_contents($user_data_file, serialize($user_data));
					}

					if (file_exists(LOCAL_CACHE_PATH . '/meta'))
					{
						shell_exec("rm -rf " . LOCAL_CACHE_PATH . '/meta/*');
						rmdir(LOCAL_CACHE_PATH . '/meta');
					}

					$add_params['progress'] -= 1;
					$add_params['update_data_cache'] = 0;
					$add_params['message_updated'] = false;

					return
						ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
				}

				if ($add_params['unpack_bg'] > 0)
				{
					if (empty($add_params['message_updated']))
					{
						$add_params['message_txt'] = 'Распаковка файлов';
						$add_params['message_updated'] = true;

						return
							ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
					}

					if (empty($add_params['unpack_run']))
					{
						$add_params['unpack_run'] = true;
						$add_params['unpacked'] = 0;
						$add_params['unpack_path'] = CUSTOM_EPG_SCREEN_BG_PATH;

						foreach(glob($add_params['unpack_path'] . '/*.aai') as $file)
							unlink($file);

						exec('$FS_PREFIX/bin/tar -xzvf ' . CUSTOM_EPG_RES_PATH . '/bg.tar.gz -C ' . $add_params['unpack_path'] . ' >/dev/null &');
					}
					else
					{
						$unpacked = count(glob($add_params['unpack_path'] . '/*.aai'));
						$add_params['unpacked'] += ($unpacked - $add_params['unpacked']);
						$add_params['progress'] -= $add_params['unpacked'];

						if ($add_params['unpacked'] >= $add_params['unpack_bg'])
						{
							$add_params['unpack_bg'] = 0;
							$add_params['message_updated'] = false;
						}
					}

					return
						ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
				}

				if ($add_params['update_manifest'] > 0)
				{
					if (empty($add_params['message_updated']))
					{
						$add_params['message_txt'] = 'Обновление манифеста плагина';
						$add_params['message_updated'] = true;

						return
							ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
					}

					// Обновление манифеста
					$parental = json_decode($plugin_cookies->parental);
					$result = @file_put_contents(
						dirname(__FILE__) . '/dune_plugin.xml',
						str_replace(
							array('{name}', '{version}', '{version_index}', '{caption}', '{label}', '{auto_resume}', 'http://127.0.0.1/cgi-bin/plugins/home_tv/'),
							array($this->plugin->app_name, $this->plugin->app_version, $this->plugin->app_version_idx, $this->plugin->app_caption, $this->plugin->app_label, ($plugin_cookies->auto_resume_enable == ControlSwitchDefs::switch_on)? 'yes' : 'no', DuneSystem::$properties['plugin_cgi_url']),
							$this->plugin->tv->get_plugin_manifest_template($parental->enabled == ControlSwitchDefs::switch_on)));

					hd_print(($result !== false)? 'Plugin manifest was updated successfully!' : 'Error! Unable to update plugin manifest!');
					$add_params['progress'] = 0;
					$add_params['update_manifest'] = 0;

					return
						ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);
				}

				if (($add_params['progress'] > 0) && ($add_params['timer'] > 0))
					$post_action = ActionFactorySafe::change_behaviour(array(GUI_EVENT_TIMER => UserInputHandlerRegistry::create_action($this, 'post_install_progress')), ActionFactorySafe::timer(500));
				else
				{
					$post_action = null;

					if ($add_params['timer'] <= 0)
					{
						if (file_exists('/tmp/home_tv_was_installed_mark') || file_exists('/tmp/home_tv_was_updated_mark'))
							@file_put_contents('/config/home_tv_was_installed_mark', '');
						else if (file_exists('/config/home_tv_was_installed_mark'))
							unlink('/config/home_tv_was_installed_mark');
					}
				}

				return
					ActionFactorySafe::reset_controls($this->get_post_install_dialog_controls_defs($add_params), $post_action);

			case 'hard_reset':
				hd_print('Do reboot stb...');
				return
					ActionFactorySafe::stb_reboot();


			case 'close_splash_and_reboot_shell':
				hd_print('Do reboot shell...');
				return
					SplashScreen::close_and_run(ActionFactorySafe::stb_shell_reboot());

			case 'input_pin_dialog_press_key_return':
				return
					ActionFactorySafe::close_dialog_and_run(SplashScreen::close_and_run());

			case 'clear_epg_cache':
				$this->plugin->epg->clear_cache();
				return
					(isset($user_input->post_action))? unserialize($user_input->post_action) : SplashScreen::close_and_run();

			case 'clear_epg_cache_once':
				if (EPG_CACHE_NEED_CLEAR)
				{
					foreach($this->plugin->epg->get_disk_cache_info() as $cache_info)
					{
						shell_exec("rm -rf " . $cache_info['base_dir'] . $cache_info['cache_path'] . "/*");
						rmdir($cache_info['base_dir'] . $cache_info['cache_path']);
						shell_exec("rm -rf " . $cache_info['base_dir'] . "/apps/*");
						rmdir($cache_info['base_dir'] . "/apps");
						rmdir($cache_info['base_dir']);
					}

					@file_put_contents('/tmp/home_tv_epg_cache_was_cleared_mark', '');

					hd_print('!!! Old EPG cache was cleared !!!');
				}
				return
					UserInputHandlerRegistry::create_action($this, 'launch', $add_params);

			case 'clear_data_cache_once':
				if (OLD_USER_DATA_NOT_COMPATIBLE)
					if (file_exists(USER_DATA_CACHE_PATH))
						foreach(glob(USER_DATA_CACHE_PATH . '/*') as $file)
							if (is_file($file))
								if ($f = unserialize(file_get_contents($file)))
								{
									foreach($f as $k => $v)
									{
										if (is_numeric('0x'.basename($k)))
											if (isset($v['epg_timeshift']))
											{
												if (count($v) == 1)
													unset($f[$k]);
												else
													unset($f[$k]['epg_timeshift']);
											}
									}

									file_put_contents($file, serialize($f));
								}
//				if (OLD_PLAYLIST_NOT_COMPATIBLE)
//				{
//					shell_exec('rm -rf ' . PLAYLISTS_CACHE_PATH . '/tv/*');
//					shell_exec('rm -rf ' . PLAYLISTS_CACHE_PATH . '/radio/*');
//					shell_exec('rm -rf ' . ICONS_CACHE_PATH . '/*');
//				}
//
//				if (OLD_USER_DATA_NOT_COMPATIBLE)
//					shell_exec('rm -rf ' . USER_DATA_CACHE_PATH . '/*');
//
//				shell_exec('rm -rf ' . META_LOCAL_CACHE_PATH . '/*');
//				shell_exec('rm -rf ' . TEMPORARY_CACHE_PATH . '/*');
				@file_put_contents('/tmp/home_tv_cache_was_cleared_mark', '');

				hd_print('!!! Cache was cleared !!!');

				return
					UserInputHandlerRegistry::create_action($this, 'launch', $add_params);

			default:
				return null;
		}
	}
}

?>