#!/usr/bin/perl -w
#
# Copyright G. Westcott - February 2013
#
# This code is distributed under the GNU General Public License v2 (GPLv2) .
#
#   For extended help information run
#         tv_grab_uk_guardian  --info
# 

my $_version 	= '$Id: tv_grab_uk_guardian,v 1.11 2014/08/04 08:31:55 bilbo_uk Exp $';


eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use Data::Dumper;

use strict;
use warnings;
use XMLTV::ProgressBar;
use XMLTV::Options qw/ParseOptions/;
use XMLTV::Configure::Writer;
use XMLTV::Supplement 0.005065 qw/SetSupplementRoot GetSupplementDir GetSupplementLines/;
use XMLTV::Get_nice qw/get_nice_tree/;

use File::Path;
use POSIX qw(strftime);
use DateTime;
use Encode;

use HTTP::Cache::Transparent;

# Although we use HTTP::Cache::Transparent, this undocumented --cache
# option for debugging is still useful since it will _always_ use a
# cached copy of a page, without contacting the server at all.
#
use XMLTV::Memoize; XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');

use subs qw(debug warning);
my $warnings = 0;


# ------------------------------------------------------------------------------------------------------------------------------------- #
# Grabber details
my $VERSION 								= $_version;
my $GRABBER_NAME 						= 'tv_grab_uk_guardian';
my $GRABBER_DESC 						= 'UK - The Guardian (tvlistings.guardian.co.uk)';
my $GRABBER_URL 						= 'http://wiki.xmltv.org/index.php/XMLTVProject';
my $ROOT_URL                = 'http://tvlistings.theguardian.com/text-only/';
my $SOURCE_NAME							= 'The Guardian';
my $SOURCE_URL							= 'http://tvlistings.theguardian.com/';
#
my $generator_info_name 		= $GRABBER_NAME;
my $generator_info_url 			= $GRABBER_URL;
my $source_info_name				= $SOURCE_NAME;
my $source_info_url					= $SOURCE_URL;



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Use XMLTV::Options::ParseOptions to parse the options and take care of the basic capabilities that a tv_grabber should
my ($opt, $conf) = ParseOptions({ 
			grabber_name 			=> $GRABBER_NAME,
			capabilities 			=> [qw/baseline manualconfig apiconfig cache/],
			stage_sub 				=> \&config_stage,
			listchannels_sub 	=> \&fetch_channels,
			version 					=> $VERSION,
			description 			=> $GRABBER_DESC,
});

#print Dumper($conf); exit;

# any overrides?
if (defined( $conf->{'generator-info-name'} )) { $generator_info_name = $conf->{'generator-info-name'}->[0]; }
if (defined( $conf->{'generator-info-url'} ))  { $generator_info_url  = $conf->{'generator-info-url'}->[0]; }
if (defined( $conf->{'source-info-name'} )) 	 { $source_info_name 		= $conf->{'source-info-name'}->[0]; }
if (defined( $conf->{'source-info-url'} ))  	 { $source_info_url 		= $conf->{'source-info-url'}->[0]; }



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Initialise the web page cache
init_cachedir( $conf->{cachedir}->[0] );
HTTP::Cache::Transparent::init( { 
    BasePath => $conf->{cachedir}->[0],
    NoUpdate => 60*60,			# cache time in seconds
		MaxAge => 24,						# flush time in hours
    Verbose => $opt->{debug},
} );


# ------------------------------------------------------------------------------------------------------------------------------------- #
# Check we have all our required conf params
config_check();

# Load the conf file containing mapped channels and categories information
my %mapchannelhash;
my %mapcategoryhash;
loadmapconf();
#print Dumper(\%mapchannelhash, \%mapcategoryhash); exit;



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Progress Bar :)
my $bar = new XMLTV::ProgressBar({
  name => "Fetching listings",
  count => (scalar @{$conf->{channel}}) * $opt->{days}
}) unless ($opt->{quiet} || $opt->{debug});



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Data store before being written as XML
my $programmes = ();
my $channels = ();

# Get the schedule(s) from The Guardian
fetch_listings();

# print Dumper($programmes);

# Progress Bar
$bar->finish() && undef $bar if defined $bar;



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Filter out programmes outside of requested period (see man page)
my %w_args;
if (($opt->{offset} != 0) || ($opt->{days} != -999)) {
  $w_args{offset} = $opt->{offset};
  $w_args{days} = ($opt->{days} == -999) ? 100 : $opt->{days};
  $w_args{cutoff} = '000000';			# e.g. '060000'
}



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Generate the XML
my $encoding = 'UTF-8';
my $credits = { 'generator-info-name' => $generator_info_name,
								'generator-info-url' 	=> $generator_info_url,
								'source-info-name' 		=> $source_info_name,
								'source-info-url' 		=> $source_info_url };
	
XMLTV::write_data([ $encoding, $credits, $channels, $programmes ], %w_args);
# Finished!



# ------------------------------------------------------------------------------------------------------------------------------------- #
# Signal that something went wrong if there were warnings.
exit(1) if $warnings;

# All data fetched ok.
debug "Exiting without warnings.";
exit(0);


# #############################################################################
# # THE MEAT #####################################################################
# ------------------------------------------------------------------------------------------------------------------------------------- #

sub fetch_listings {
		# Fetch listings per channel
		
		foreach my $channel_id (@{$conf->{channel}}) {
				# Officially:
				# http://tvlistings.theguardian.com/text-only/?c=5-star
				# http://tvlistings.theguardian.com/text-only/?tvgDayOffset=1f&tvgBroadcaster=UKSkyCable&tvgRegion=London&tvgFlagFilter=&tvgChannelName=5+Star
				# But this works:
				# http://tvlistings.theguardian.com/text-only/?c=5-star&tvgDayOffset=1f&tvgBroadcaster=UKSkyCable&tvgRegion=London&tvgFlagFilter=
				
				my $baseurl = $ROOT_URL.'?tvgBroadcaster=UKSkyCable&tvgRegion=London&tvgFlagFilter=';
				
				# Now grab listings for each channel on each day, according to the options in $opt
				for (my $i=$opt->{offset}; $i < ($opt->{offset} + $opt->{days}); $i++) {
					my $theday = DateTime->today->add (days => $i)->set_time_zone('Europe/London');
					
					# Construct the listings url
					# my $url = $baseurl . '&tvgDayOffset=' . $i . 'f' . '&tvgChannelName=' . $channel_id;
					my $url = $baseurl . '&tvgDayOffset=' . $i . 'f' . '&c=' . $channel_id;
					#debug "Fetching: $url";

					# If we need to map the fetched channel_id to a different value
					my $xmlchannel_id = $channel_id;
					if (defined(&map_channel_id)) { $xmlchannel_id = map_channel_id($channel_id); }
					
					# Fetch the page
					my $tree = XMLTV::Get_nice::get_nice_tree($url, \&utf8);
					#	$tree->dump; exit;
					
					# Scrub the page
					if ($tree) {
						
						# 6-Dec-2013 : we must find a workaround for a bug in The Guardian's website. When asking for a regionalised channel (e.g. BBC2) 
						#  their website is displaying not only "BBC 2" but also "BBC 2 Northern Ireland (Digital)" & "BBC 2 Scotland (Digital)"
						#  concatenated one after each other with no break.  Been broken for nearly 2 weeks now.
						#  I've reported it to their web team but no response.
						#
						#        my $channelname = $tree->look_down('_tag' => 'div', 'class' => 'tvg_channelname');					# e.g. "5 Star - channel number 176"
						#        my $channelnum = $channelname->look_down('_tag' => 'span', 'class' => 'tvg_channelnumber');	# e.g. " - channel number 176"
						#        my @shows = $channelname->parent->look_down('_tag' => 'span', 'class' => 'tvg_show');
						#        $channelname = $channelname->as_text;		
						#
						# begin workaround
						#
						# It looks like I can find the correct schedule block by comparing the 'tvg_channelname' block header with the page title:
						# get the page title  
						#    <title>BBC 2 TV listings | TV and radio | The Guardian </title>
						my $channeltitle = $tree->look_down('_tag' => 'title')->as_text;
						$channeltitle =~ m/^(.*\|\|)?(.*)\sTV listings/i and $channeltitle = $2;
						debug "TITLE= ".$channeltitle;
						
						# get the channel schedule(s) name
						my @channelscheds = $tree->look_down('_tag' => 'div', 'class' => 'tvg_channelname');	 # e.g. "5 Star - channel number 176"
						my $channelsched;
						foreach (@channelscheds) {
							debug $_->as_text;
							next if ($_->as_text !~ m/\Q$channeltitle - channel number/);
							debug "FOUND= ".$_->as_text;
							$channelsched = $_;
							last;
						}
						my $channelname = (defined $channelsched ? $channelsched->as_text : $channeltitle);
						debug $channelname;
						
						# build the schedule from all the right nodes until we hit another 'tvg_channelname'
						my @shows; 
						my $show = $channelsched;
						if (defined $show) {
							do {
								$show = $show->right();
								if ( $show && $show->tag() eq 'span' && $show->attr('class') eq 'tvg_show' ) {
									push @shows, $show;
								}
							} while defined $show && !( $show->tag() eq 'div' && $show->attr('class') eq 'tvg_channelname' );
						}
						#
						# end workaround
						
						
						if (@shows) {
							foreach my $show (@shows) {
								# 	$show->dump;
								
								my %prog = ();
									
								# channel
								$prog{'channel'} = $xmlchannel_id;
								
								# title
								my $showtitle = $show->look_down('_tag' => 'span', 'class' => 'tvg_show_title');
								$prog{'title'} = [[ encode('utf-8', $showtitle->as_text), 'en' ]];
								
								# start
								my $showstart = $show->look_down('_tag' => 'span', 'class' => 'tvg_show_start');
								my @show_hhmm = split(/:/, $showstart->as_text);
								my $showtime = $theday->clone;
								$showtime->set(hour => $show_hhmm[0], minute => $show_hhmm[1], second => 0);
								$prog{'start'} = $showtime->strftime("%Y%m%d%H%M%S %z");
								
								# category
								#		<span class="tvg_show_category">Advertisement/Shopping</span>
								my $showcategory = $show->look_down('_tag' => 'span', 'class' => 'tvg_show_category');
								my @showcategory = split(/\//, $showcategory->as_text);
								my @showcategories = ();
								foreach my $category (@showcategory) {
									# category translation?
									#	if (defined(&map_category)) { $category = map_category($category); }
									push @showcategories, [ encode('utf-8', $category) ];
								}
								$prog{'category'} = [ @showcategories ] if (scalar @showcategories > 0);
								
								# desc
								$showcategory->detach;
								my $showdesc = $show->look_down('_tag' => 'div', 'class' => 'tvg_show_description');
								if ($showdesc) {
									my $_showdesc = $showdesc->as_text;
									$_showdesc .= '.' if ( (length $_showdesc) && (substr $_showdesc,-1,1 ne '.') );	# addend a fullstop
									if (length $_showdesc) {
										$prog{'desc'} = [[ encode('UTF-8', $_showdesc), 'en' ]];
									}
								}

								# year
								# ?????????????
								
								
								
								
								
								# flags
								# <span class="tvg_show_flags">[SUB]</span>
								my $showflags = $show->look_down('_tag' => 'span', 'class' => 'tvg_show_flags');
								if ($showflags && $showflags->as_text =~ '\[SUB\]') {
									push @{$prog{'subtitles'}}, {'type' => 'teletext'};
								}
								if ($showflags && $showflags->as_text =~ '\[SUB AD\]') {
									push @{$prog{'subtitles'}}, {'type' => 'deaf-signed'};
								}
								if ($showflags && $showflags->as_text =~ '\[REP\]') {
									push @{$prog{'previously-shown'}}, {};
								}
								
								# episode title / number
								# <div class="tvg_show_episode_title">Series 2. Episode 2/3</div>
								# <div class="tvg_show_episode_title">Series 2. Episode 6/23: Black Gold and Red Blood</div>
								my $showepisode = $show->look_down('_tag' => 'div', 'class' => 'tvg_show_episode_title');
								if ($showepisode) {
									my ($showsxx, $showexx, $showeof, $showep) = ( $showepisode->as_text =~ /^(?:Series (\d+)[., :]+)?(?:Episode (\d+)(?:\/(\d+))?[: ]?)?(.*)$/ );
									# scan the description for any "Part x of x." info
									my ($showpxx, $showpof) = ( $showdesc->as_text =~ /Part (one|two|three|four|five|six|seven|eight|nine|\d+)(?: of (one|two|three|four|five|six|seven|eight|nine|\d+))?/ );
									my $showepnum = make_ns_epnum($showsxx, $showexx, $showeof, $showpxx, $showpof);
									if ($showepnum && $showepnum ne '...') {
										$prog{'episode-num'} = [[ $showepnum, 'xmltv_ns' ]];
									}
									#debug "--$showepnum-- ".$showepisode->as_text;
									
									if ($showep) { $prog{'sub-title'} = [[ encode('utf-8', $showep), 'en' ]]; }
								}
							
								# director
								# never seen one but let's assume they're in the description
								my ($directors) = ( $showdesc->as_text =~ /(?:Directed by|Director) ([^\.]*)\.?/ );
								if ($directors) {
									$directors =~ s/ (with|and) /,/ig;
									$directors =~ s/ (singer|actor|actress) //ig;			# strip these words
									$directors =~ s/,,/,/g;	# delete empties
									$directors = encode('utf-8', $directors);	# encode names into utf-8
									#debug $directors;
									my @directors = split(/,/, $directors);
									s{^\s+|\s+$}{}g foreach @directors;	# strip leading & trailing spaces
									$prog{'credits'}->{'director'} = \@directors  if (scalar @directors > 0);
								}
								
								# actors
								# these are buried in the description  :-(
								my ($actors) = ( $showdesc->as_text =~ /(?:starring)([^\.]*)\.?/i );
								if ($actors) {
									$actors =~ s/ (also|starring|with|and) /,/ig;		# may be used to separate names
									$actors =~ s/ (singer|actor|actress) //ig;			# strip these words
									$actors =~ s/,,/,/g;	# delete empties
									$actors = encode('utf-8', $actors);	# encode names into utf-8
									#debug $actors;
									my @actors = split(/,/, $actors);
									s{^\s+|\s+$}{}g foreach @actors;	# strip leading & trailing spaces
									$prog{'credits'}->{'actor'} = \@actors  if (scalar @actors > 0);
								}
								
								
								# debug Dumper \%prog;
								push(@{$programmes}, \%prog);
								
							}

						} else {
							# no schedule found
							warning 'No schedule found';
						}
						
						# Add to the channels hash
						$channels->{$channel_id} = { 'id'=> $xmlchannel_id , 'display-name' => [[$channelname, 'en']]  };

					} else {
						# tree conversion failed
						warning 'Could not parse the page';
					}

					$bar->update if defined $bar;
				}
		}
}


# #############################################################################
# # THE VEG ######################################################################
# ------------------------------------------------------------------------------------------------------------------------------------- #

sub make_ns_epnum {
		# Convert an episode number to its xmltv_ns compatible - i.e. reset the base to zero
		# Input = series number, episode number, total episodes,  part number, total parts,
		#  e.g. "1, 3, 6, 2, 4" >> "0.2/6.1/4",    "3, 4" >> "2.3."
		#
		my ($s, $e, $e_of, $p, $p_of) = @_;
		#	debug Dumper(@_);

		# "Part x of x" may contaain integers or words (e.g. "Part 1 of 2", or "Part one")
		$p = text_to_num($p) if defined $p;
		$p_of = text_to_num($p_of) if defined $p_of;
		
		# re-base the series/episode/part numbers
		$s-- if (defined $s && $s > 0);
		$e-- if (defined $e && $e > 0);
		$p-- if (defined $p && $p > 0);
		
		# make the xmltv_ns compliant episode-num
		my $episode_ns = '';
		$episode_ns .= $s if defined $s;
		$episode_ns .= '.';
		$episode_ns .= $e if defined $e;
		$episode_ns .= '/'.$e_of if defined $e_of;
		$episode_ns .= '.';
		$episode_ns .= $p if defined $p;
		$episode_ns .= '/'.$p_of if defined $p_of;
		
		#debug "--$episode_ns--";
		return $episode_ns;
}
	
sub text_to_num {
		# Convert a word number to int e.g. 'one' >> '1'
		#
		my ($text) = @_;
		if ($text !~ /^[+-]?\d+$/) {	# standard test for an int
			my %nums = (one => 1, two => 2, three => 3, four => 4, five => 5, six => 6, seven => 7, eight => 8, nine => 9);
			return $nums{$text} if exists $nums{$text};
		}
		return $text
}

sub map_channel_id {
		# Map the fetched channel_id to a different value (e.g. our PVR needs specific channel ids)
		# mapped channels should be stored in a file called  tv_grab_uk_guardian.map.conf
		# containing lines of the form:  map==fromchan==tochan  e.g. 'map==5-star==5STAR'
		#
		my ($channel_id) = @_;
		my $mapchannels = \%mapchannelhash;
		if (%mapchannelhash && exists $mapchannels->{$channel_id}) { 
			return $mapchannels->{$channel_id} ; 
		}
		return $channel_id;
}

sub map_category {
		# Map the fetched category to a different value (e.g. our PVR needs specific genres)
		# mapped categories should be stored in a file called  tv_grab_uk_guardian.map.conf
		# containing lines of the form:  cat==fromcategory==tocategory  e.g. 'cat==General Movie==Film'
		#
		my ($category) = @_;
		my $mapcategories = \%mapcategoryhash;
		if (%mapcategoryhash && exists $mapcategories->{$category}) { 
			return $mapcategories->{$category} ; 
		}
		return $category;
}

sub loadmapconf {
		# Load the conf file containing mapped channels and categories information
		# 
		# This file contains 2 record types:
		# 	lines starting with "map" are used to 'translate' the incoming channel id to those required by your PVR
		#			e.g. 	map==dave==DAVE     will output "DAVE" in your XML file instead of "dave"
		# 	lines starting with "cat" are used to translate categories (genres) in the incoming data to those required by your PVR
		# 		e.g.  cat==Science Fiction==Sci-fi			will output "Sci-Fi" in your XML file instead of "Science Fiction"
		#
		my $mapchannels = \%mapchannelhash;
		my $mapcategories = \%mapcategoryhash;
		#		
		my $supplementdir = $ENV{XMLTV_SUPPLEMENT} || GetSupplementDir();
		SetSupplementRoot($supplementdir);
		my $lines = GetSupplementLines($GRABBER_NAME, $GRABBER_NAME . '.map.conf');
		foreach my $line (@$lines) { 
				my ($type, $mapfrom, $mapto, $trash) = $line =~ /^(.*)==(.*)==(.*?)([\s\t]*#.*)?$/;
				SWITCH: {
						lc($type) eq 'map' && do { $mapchannels->{$mapfrom} = $mapto; last SWITCH; };
						lc($type) eq 'cat' && do { $mapcategories->{$mapfrom} = $mapto; last SWITCH; };
					warning "Unknown type in map file: \n $line";
				}
			}
		# debug Dumper ($mapchannels, $mapcategories);
}

sub fetch_channels {
	my ($opt, $conf) = @_;
  
	my $channel_list       			= $ROOT_URL.'all-channels/';
	my $channel_link_regexp 		= "^\\.\\.\\/.*";
	my $channel_link_id  				= "^\\.\\.\\/\\?c=(.*)";
	my $channel_link_url 				= "^\\.\\.\\/(.*)";

  my $result;
  my $channels = {};

  my $bar = new XMLTV::ProgressBar({
    name => "Fetching channels",
    count => 1
  }) unless ($opt->{quiet} || $opt->{debug});

  # Get the page containing the list of channels 
	my $tree = XMLTV::Get_nice::get_nice_tree($channel_list, \&utf8);
	#		$tree->dump;
  my $_channels = $tree->look_down('_tag' => 'span', 'id' => '_ctl0_main_channelList');
	my @channels = $_channels->look_down('_tag' => 'a', 'href' => qr/$channel_link_regexp/);
			#		debug $_channels->as_HTML;
			#		foreach  my $xchannel (@channels) { debug $xchannel->as_HTML; }

  $bar->update() && $bar->finish && undef $bar if defined $bar;

  $bar = new XMLTV::ProgressBar({
    name => "Parsing result",
    count => scalar @channels
  }) unless ($opt->{quiet} || $opt->{debug});

  # Map the list of channels to a hash XMLTV::Writer will understand
  foreach my $channel (@channels) {
    if ($channel->as_text()) {
      my ($id) = $channel->attr('href') =~ /$channel_link_id/;
			my ($url) = $channel->attr('href') =~ /$channel_link_url/;
			my ($name) = $channel->as_text();

      $channels->{"$id"} = {
        id => "$id",
        'display-name' => [[ encode('utf-8', $name), 'en' ]],
        url => [ $ROOT_URL.$url ]
      };

    }

    $bar->update() if defined $bar;
  }

  $bar->finish() && undef $bar if defined $bar;

  # Notifying the user :)
  $bar = new XMLTV::ProgressBar({
    name => "Reformatting",
    count => 1
  }) unless ($opt->{quiet} || $opt->{debug});

  # Let XMLTV::Writer format the results as a valid xmltv file
  my $writer = new XMLTV::Writer(OUTPUT => \$result, encoding => 'utf-8');
  $writer->start({'generator-info-name' => $generator_info_name});
  $writer->write_channels($channels);
  $writer->end();

  $bar->update() && $bar->finish() if defined $bar;

  return $result;
}

sub config_stage {
		my( $stage, $conf ) = @_;
		die "Unknown stage $stage" if $stage ne "start";

		my $result;
		my $writer = new XMLTV::Configure::Writer( OUTPUT => \$result, encoding => 'utf-8' );
		$writer->start( { grabber => $GRABBER_NAME } );
		$writer->write_string( {
				id => 'cachedir', 
				title => [ [ 'Directory to store the cache in', 'en' ] ],
				description => [ 
				 [ $GRABBER_NAME.' uses a cache with files that it has already '. 
					 'downloaded. Please specify where the cache shall be stored. ', 
					 'en' ] ],
				default => get_default_cachedir(),
		 } );

		$writer->end( 'select-channels' );

		return $result;
}

sub config_check {
		if (not defined( $conf->{cachedir} )) {
				print STDERR "No cachedir defined in configfile " . 
										 $opt->{'config-file'} . "\n" .
										 "Please run the grabber with --configure.\n";
				exit 1;
		}

		if (not defined( $conf->{'channel'} )) {
				print STDERR "No channels selected in configfile " .
										 $opt->{'config-file'} . "\n" .
										 "Please run the grabber with --configure.\n";
				exit 1;
		}
}

sub get_default_dir {
    my $winhome = $ENV{HOMEDRIVE} . $ENV{HOMEPATH} 
			if defined( $ENV{HOMEDRIVE} ) 
					and defined( $ENV{HOMEPATH} ); 
    
    my $home = $ENV{HOME} || $winhome || ".";
    return $home;
}

sub get_default_cachedir {
    return get_default_dir() . "/.xmltv/cache";
}

sub init_cachedir {
    my( $path ) = @_;
    if( not -d $path ) {
        mkpath( $path ) or die "Failed to create cache-directory $path: $@";
    }
}

sub utf8 {
		# Catch the error:
		#    "Parsing of undecoded UTF-8 will give garbage when decoding entities at /usr/lib/perl5/site_perl/5.8.8/XMLTV/Get_nice.pm line 57."
		# (e.g. http://eli.thegreenplace.net/2007/07/20/parsing-of-undecoded-utf-8-will-give-garbage-when-decoding-entities/ )
		#
		my ($html) = @_;
		return decode('UTF-8', $html); 
}

sub debug ( $$ ) {
    my( $message, $nonewline ) = @_;
    print STDERR $message if $opt->{debug};
    print STDERR "\n" if $opt->{debug} && (!defined $nonewline || $nonewline != 1);
}

sub warning ( $ ) {
    my( $message ) = @_;
    print STDERR $message . "\n";
    $warnings++;
}

# #############################################################################

__END__

=pod

=head1 NAME

tv_grab_uk_guardian - Grab TV listings for UK from The Guardian website.

=head1 DESCRIPTION

Output TV listings in XMLTV format for many channels available in UK.
The data come from L<http://theguardian.co.uk>

First you must run B<tv_grab_uk_guardian --configure> to choose which channels
you want to receive.

Then running B<tv_grab_uk_guardian> with no arguments will get a listings in XML
format for the channels you chose for available days including today.

=head1 OPTIONS

Please see B<tv_grab_uk_guardian  --help>

=head1 INSTALLATION

The file F<tv_grab_uk_guardian.map.conf> has two purposes.  Firstly you can map 
the channel ids used by the site into something more meaningful to your PVR. E.g.

      map==bbc-1-south==BBC 1	

will change "bbc-1-south" to "BBC 1" in the output XML.

Note: the lines are of the form "map=={channel id}=={my name}".

The second purpose is to likewise translate genre names.  So if your PVR doesn"t 
have a category for "Science Fiction" but uses "Sci-fi" instead, then you can 
specify

      cat==Science Fiction==Sci-fi

and the output XML will have "Sci-fi".


IMPORTANT: the downloaded "tv_grab_uk_guardian.map.conf" contains example lines 
to illustrate the format - you should edit this file to suit your own purposes!

=head1 ERROR HANDLING

If the grabber fails to download data for some channel on a specific day, 
it will print an errormessage to STDERR and then continue with the other
channels and days. The grabber will exit with a status code of 1 to indicate 
that the data is incomplete. 

=head1 ENVIRONMENT VARIABLES

The environment variable HOME can be set to change where configuration
files are stored. All configuration is stored in $HOME/.xmltv/. On Windows,
it might be necessary to set HOME to a path without spaces in it.

=head1 SUPPORTED CHANNELS

For information on supported channels, see 
L<http://tvlistings.guardian.co.uk/text-only/all-channels/>

=head1 XMLTV VALIDATION

B<tv_validate_grabber> may report an error similar to:

      "Line 5 Invalid channel-id BBC 1"
	
This is a because ValidateFile.pm insists the channel-id adheres to RFC2838 
despite the xmltv.dtd only saying "preferably" not "SHOULD".  
(Having channel ids of the form "bbc1.bbc.co.uk" will be rejected by many PVRs 
since they require the data to match their own list.)

It may also report:

      "tv_sort failed on the concatenated data. Probably due to 
         overlapping data between days."
	
Both these errors can be ignored.

=head1 DISCLAIMER

The Guardian website"s license for these data does not allow non-personal use.

Certainly any commercial use of listings data obtained by using this grabber 
will breach copyright law, but if you are just using the data for your own 
personal use then you are probably fine.

By using this grabber you aver you are using the listings data for your own 
personal use only and you absolve the author(s) from any liability under 
copyright law or otherwise.

=head1 AUTHOR

Geoff Westcott. This documentation and parts of the code
based on various other tv_grabbers from the XMLTV-project.

=head1 SEE ALSO

L<xmltv(5)>.

=cut


DATA
====
<div class="tvg_channelname">5 Star<span class="tvg_channelnumber"> - channel number 176</span></div>

<span class="tvg_show" id="323533229">
	<span class="tvg_show_start">00:00</span>
	<span class="tvg_show_title">Teleshopping</span>
	<div class="tvg_show_wrapper">
		<div class="tvg_show_description">Buying goods from the comfort of home
			<span class="tvg_show_category">Advertisement/Shopping</span>
		</div>
	</div>
</span>

<span class="tvg_show" id="323709189">
	<span class="tvg_show_start">15:30</span>
	<span class="tvg_show_title">Winter Road Rescue</span>
	<span class="tvg_show_flags">[SUB]</span>
	<div class="tvg_show_wrapper">
		<div class="tvg_show_episode_title">Series 2. Episode 2/3</div>
		<div class="tvg_show_description">As torrential rain in the south-west of England brings some of the worst flooding in living memory, the RAC's Ian Devonshire and Sean Kimberlin are on high alert as they come to the rescue of stranded motorists. In the Highlands, plough driver Stevie Booth faces a new route and a race against time to get the roads clear of snow and ice. Across the UK, as freezing temperatures follow the rain, the roads become treacherous and RAC patrolman Joe Ryan-Howes comes to the aid of a driver whose vehicle has skidded on sheet ice into a fence
			<span class="tvg_show_category">Documentary</span>
		</div>
	</div>
</span>

<span class="tvg_show" id="323709187">
	<span class="tvg_show_start">18:25</span>
	<span class="tvg_show_title">The Legend of Zorro</span>
	<span class="tvg_show_flags">[SUB]</span>
	<div class="tvg_show_wrapper">
		<div class="tvg_show_description">The masked hero investigates a mysterious explosion linked to a French count, who is plotting to prevent California joining the United States - and discovers his wife, who walked out on their marriage when he refused to hang up his sword, is somehow involved. Swashbuckling adventure sequel, starring Antonio Banderas, Catherine Zeta-Jones, Rufus Sewell, Alberto Reyes and Adrian Alonso
			<span class="tvg_show_category">Film/Adventure</span>
		</div>
	</div>
</span>

