#!/usr/bin/perl -w

=pod

=head1 NAME

tv_grab_es - Grab TV listings for Spain.

=head1 SYNOPSIS

tv_grab_es --help

tv_grab_es [--config-file FILE] --configure [--gui OPTION]

tv_grab_es [--config-file FILE] [--output FILE] [--days N]
           [--offset N] [--quiet]

tv_grab_es --list-channels

tv_grab_es --capabilities

tv_grab_es --version

=head1 DESCRIPTION

Output TV listings for several channels available in Spain.
Now supports the terrestrial analog tv listings, which is the most common tv 
viewed in Spain that currently has no EPG information. I have plans to add
Satelite listings (now the Spanish platforms are in a merger process between 
providers and also cable (the listings has to be grabbed from different sites)).
The tv listings comes from www.elpais.es 
The grabber relies on parsing HTML so it might stop working at any time.

First run B<tv_grab_es --configure> to choose, which channels you want
to download. Then running B<tv_grab_es> with no arguments will output
listings in XML format to standard output.

B<--configure> Prompt for which channels,
and write the configuration file.

B<--config-file FILE> Set the name of the configuration file, the
default is B<~/.xmltv/tv_grab_es.conf>.  This is the file written by
B<--configure> and read when grabbing.

B<--gui OPTION> Use this option to enable a graphical interface to be used.
OPTION may be 'Tk', or left blank for the best available choice.
Additional allowed values of OPTION are 'Term' for normal terminal output
(default) and 'TermNoProgressBar' to disable the use of XMLTV::ProgressBar.

B<--output FILE> Write to FILE rather than standard output.

B<--days N> Grab N days.  The default is 3.

B<--offset N> Start N days in the future.  The default is to start
from today.

B<--quiet> Suppress the progress messages normally written to standard
error.

B<--capabilities> Show which capabilities the grabber supports. For more
information, see L<http://membled.com/twiki/bin/view/Main/XmltvCapabilities>

B<--version> Show the version of the grabber.

B<--help> Print a help message and exit.

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Ramon Roca, Ramon.Roca@XCombo.com, based on tv_grab_fi, from Matti Airas.

=head1 BUGS

=cut

# Author's TODOs & thoughts
#
# this is for analog listings, for D+ satellite listings please use 
#       tv_grab_es_digital
#
# get the icons of each grabbed channel from the website
#
# findout how to setup properly the language, (catalan, basque, galician, vo)
#
# get channel ids in RFC2838 format (I don't, actually the Id comes directly
# 	web site, i don't know where to go for getting th id's for spanish
#	tv broadcasters.
#
# do the listings from another site, just in case this one breaks, the most
#	similar sites to this grabber are television.ya.com.
#	we should consider also getting them from www.terra.es or 
#	www.tvinteligente.com, they provide also some more local tv listings
#	however the grabber gets a lot more complex and needs many more urls
#	to collect the info, although it can be a little bit more complete
#       (i.e. credits, program duration...)
#
#


######################################################################
# initializations

use strict;
use XMLTV::Version '$Id: tv_grab_es,v 1.38 2006/04/12 08:19:16 fgouget Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig cache/;
use XMLTV::Description 'Spain';
use Getopt::Long;
use Date::Manip;
use HTML::TreeBuilder;
use HTML::Entities; # parse entities
use IO::File;

use XMLTV;
use XMLTV::Memoize;
use XMLTV::ProgressBar;
use XMLTV::Ask;
use XMLTV::Config_file;
use XMLTV::DST;
use XMLTV::Get_nice;
use XMLTV::Mode;
use XMLTV::Date;
# Todo: perhaps we should internationalize messages and docs?
use XMLTV::Usage <<END
$0: get Spanish television listings in XMLTV format
To configure: $0 --configure [--config-file FILE]
To grab listings: $0 [--config-file FILE] [--output FILE] [--days N]
        [--offset N] [--quiet]
To list channels: $0 --list-channels
To show capabilities: $0 --capabilities
To show version: $0 --version
END
  ;

# Attributes of the root element in output.
my $HEAD = { 'source-info-url'     => 'http://www.elpais.es/parrillatv/portada.html',
	     'source-data-url'     => "http://www.elpais.es/parrillatv/resultados.html",
	     'generator-info-name' => 'XMLTV',
	     'generator-info-url'  => 'http://membled.com/work/apps/xmltv/',
	   };
		   
# Whether zero-length programmes should be included in the output.
my $WRITE_ZERO_LENGTH = 0;

# default language
my $LANG="es";

# Global channel_data
our @ch_all;

######################################################################
# get options

# Get options, including undocumented --cache option.
XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');
my ($opt_days, $opt_offset, $opt_help, $opt_output,
    $opt_configure, $opt_config_file, $opt_gui,
    $opt_quiet, $opt_list_channels);
$opt_days  = 3; # default
$opt_offset = 0; # default
$opt_quiet  = 0; # default
GetOptions('days=i'        => \$opt_days,
	   'offset=i'      => \$opt_offset,
	   'help'          => \$opt_help,
	   'configure'     => \$opt_configure,
	   'config-file=s' => \$opt_config_file,
       'gui:s'         => \$opt_gui,
	   'output=s'      => \$opt_output,
	   'quiet'         => \$opt_quiet,
	   'list-channels' => \$opt_list_channels
	  )
  or usage(0);
die 'number of days must not be negative'
  if (defined $opt_days && $opt_days < 0);
usage(1) if $opt_help;

XMLTV::Ask::init($opt_gui);

my $mode = XMLTV::Mode::mode('grab', # default
			     $opt_configure => 'configure',
			     $opt_list_channels => 'list-channels',
			    );

# File that stores which channels to download.
my $config_file
  = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_es', $opt_quiet);

my @config_lines; # used only in grab mode
if ($mode eq 'configure') {
    XMLTV::Config_file::check_no_overwrite($config_file);
}
elsif ($mode eq 'grab') {
    @config_lines = XMLTV::Config_file::read_lines($config_file);
}
elsif ($mode eq 'list-channels') {
    # Config file not used.
}
else { die }

# Whatever we are doing, we need the channels data.
my %channels = get_channels(); # sets @ch_all
my @channels;

######################################################################
# write configuration

if ($mode eq 'configure') {
    open(CONF, ">$config_file") or die "cannot write to $config_file: $!";

    # Ask about each channel.
    my @chs = sort keys %channels;
    my @names = map { $channels{$_} } @chs;
    my @qs = map { "add channel $_?" } @names;
    my @want = ask_many_boolean(1, @qs);
    foreach (@chs) {
	my $w = shift @want;
	warn("cannot read input, stopping channel questions"), last
	  if not defined $w;
	# No need to print to user - XMLTV::Ask is verbose enough.

	# Print a config line, but comment it out if channel not wanted.
	print CONF '#' if not $w;
	my $name = shift @names;
	print CONF "channel $_ $name\n";
	# TODO don't store display-name in config file.
    }

    close CONF or warn "cannot close $config_file: $!";
    say("Finished configuration.");

    exit();
}


# Not configuration, we must be writing something, either full
# listings or just channels.
#
die if $mode ne 'grab' and $mode ne 'list-channels';

# Options to be used for XMLTV::Writer.
my %w_args;
if (defined $opt_output) {
    my $fh = new IO::File(">$opt_output");
    die "cannot write to $opt_output: $!" if not defined $fh;
    $w_args{OUTPUT} = $fh;
}
$w_args{encoding} = 'ISO-8859-1';
my $writer = new XMLTV::Writer(%w_args);
$writer->start($HEAD);

if ($mode eq 'list-channels') {
    $writer->write_channel($_) foreach @ch_all;
    $writer->end();
    exit();
}

######################################################################
# We are producing full listings.
die if $mode ne 'grab';

# Read configuration
my $line_num = 1;
foreach (@config_lines) {
    ++ $line_num;
    next if not defined;
    if (/^channel:?\s+(\S+)\s+([^\#]+)/) {
	my $ch_did = $1;
	my $ch_name = $2;
	$ch_name =~ s/\s*$//;
	push @channels, $ch_did;
	$channels{$ch_did} = $ch_name;
    }
    else {
	warn "$config_file:$line_num: bad line\n";
    }
}

######################################################################
# begin main program

# Assume the listings source uses CET (see BUGS above).
my $now = DateCalc(parse_date('now'), "$opt_offset days");
die "No channels specified, run me with --configure\n"
  if not keys %channels;
my @to_get;


# the order in which we fetch the channels matters
foreach my $ch_did (@channels) {
    my $ch_name=$channels{$ch_did};
    my $ch_xid="$ch_did.elpais.es";
    my $ch_num=$ch_did + 0;
    $writer->write_channel({ id => $ch_xid,
			     'display-name' => [ [ $ch_name ],
						 [ $ch_num ] ] });
    my $day=UnixDate($now,'%Q');
    for (my $i=0;$i<$opt_days;$i++) {
        push @to_get, [ $day, $ch_xid, $ch_did ];
        #for each day
        $day=nextday($day); die if not defined $day;
    }
}

# This progress bar is for both downloading and parsing.  Maybe
# they could be separate.
#
my $bar = new XMLTV::ProgressBar('getting listings', scalar @to_get)
  if not $opt_quiet;
foreach (@to_get) {
	foreach (process_table($_->[0], $_->[1], $_->[2])) {
		$writer->write_programme($_);
	}
	update $bar if not $opt_quiet;
}
$bar->finish() if not $opt_quiet;
$writer->end();

######################################################################
# subroutine definitions

# Use Log::TraceMessages if installed.
BEGIN {
    eval { require Log::TraceMessages };
    if ($@) {
	*t = sub {};
	*d = sub { '' };
    }
    else {
	*t = \&Log::TraceMessages::t;
	*d = \&Log::TraceMessages::d;
	Log::TraceMessages::check_argv();
    }
}

####
# process_table: fetch a URL and process it
#
# arguments:
#    Date::Manip object giving the day to grab
#    xmltv id of channel
#    elpais.es id of channel
#
# returns: list of the programme hashes to write
#
sub process_table {
    my ($date, $ch_xmltv_id, $ch_es_id) = @_;

    my $today = UnixDate($date, '%Y%m%d');
    my $url = "http://www.elpais.es/parrillatv/resultados.html?franja=&tipo=&canal=$ch_es_id&dia=$today";
    t $url;
    local $SIG{__WARN__} = sub {
	warn "$url: $_[0]";
    };

    # parse the page to a document object
    my $tree = get_nice_tree $url;
    my @program_data = get_program_data($tree);
    my $bump_start_day=0;

    my @r;
    while (@program_data) {
	my $cur = shift @program_data;
	my $next = shift @program_data;
	unshift @program_data,$next if $next;
	
	my $p = make_programme_hash($date, $ch_xmltv_id, $ch_es_id, $cur, $next);
	if (not $p) {
	    require Data::Dumper;
	    my $d = Data::Dumper::Dumper($cur);
	    warn "cannot write programme on $ch_xmltv_id on $date:\n$d\n";
	}
	else {
	    push @r, $p;
	}

	if (!$bump_start_day && bump_start_day($cur,$next)) {
	    $bump_start_day=1;
	    $date = UnixDate(DateCalc($date,"+ 1 day"),'%Q');
	}
    }
    return @r;
}

sub make_programme_hash {
    my ($date, $ch_xmltv_id, $ch_es_id, $cur, $next) = @_;

    my %prog;

    $prog{channel}=$ch_xmltv_id;
    $prog{title}=[ [ $cur->{title}, $LANG ] ];
    $prog{"sub-title"}=[ [ $cur->{subtitle}, $LANG ] ] if defined $cur->{subtitle};
    $prog{category}=[ [ $cur->{category}, $LANG ] ];

    t "turning local time $cur->{time}, on date $date, into UTC";
    eval { $prog{start}=utc_offset("$date $cur->{time}", '+0100') };
    if ($@) {
	warn "bad time string: $cur->{time}";
	return undef;
    }
    t "...got $prog{start}";
    # FIXME: parse description field further

    $prog{desc}=[ [ $cur->{desc}, $LANG ] ] if defined $cur->{desc};

    return \%prog;
}
sub bump_start_day {
    my ($cur,$next) = @_;
    if (!defined($next)) {
	return undef;
    }
    my $start = UnixDate($cur->{time},'%H:%M');
    my $stop = UnixDate($next->{time},'%H:%M');
    if (Date_Cmp($start,$stop)>0) {
	return 1;
    } else {
	return 0;
    }
}


#
# program data is split as follows:
# - as 22/4/2003 elpais.es have changed again the page, now the table that 
#   that contains the listings have a single header, so now we only look
#   once for it and use the time to findout where the listings ends.
sub get_program_data {
    my ($tree) = @_;
    my @data;

    my @txt_elems = get_txt_elems($tree);

    # Actually time and title are required, but we don't check that.

    my $index = 0;
    while ($index <= scalar (@txt_elems-4)) {
	if (       ($txt_elems[$index] eq "Hora")
		&& ($txt_elems[$index + 1] eq "Programa")
		&& ($txt_elems[$index + 2] eq "Canal")
		&& ($txt_elems[$index + 3] eq "Tipo") ) 
		{
	   t "Program listing comes below";
	   $index = $index + 4;
	   while ( $txt_elems[$index] =~ /^\d\d:\d\d/ ) {
		t "Program found: Hora: $txt_elems[$index] Programa: $txt_elems[$index+1]";
                # Look for duplicate start time, that occurs sometimes
                # at elpais.es when a new program is lately scheduled but seems
                # that they forget to remove the previous listing
                # If it happens, we just grab the last program.
                if ( $txt_elems[$index] =~ $txt_elems[$index + 5] ) {
                        $index = $index + 5;
                }

                my $p_stime     = $txt_elems[$index];
                my @p_str       = split (/:/,$txt_elems[$index + 1]);
                my $p_title     = $p_str[0];
		for ($p_title) { s/^\s+//; s/\s+$// }
                my @strsub      = split (/\"/,$p_str[1])
		  if (defined $p_str[1]);
                my $p_subtitle;
                if (defined $strsub[0]) {
		    if ( $strsub[0] =~ " " ) {
                        $p_subtitle = $strsub[1];
		    }
		    else {
                        $p_subtitle = $p_str[1];
		    }
		    undef $p_subtitle
		      if defined $p_subtitle and $p_subtitle eq '';
		}
                my $p_category  = $txt_elems[$index + 3];
                my $p_desc;
                if (not ( $txt_elems[$index + 4] =~ /^\d\d:\d\d/ ) ) {
                # Program has Description
                        $p_desc = $txt_elems[$index + 4];
                        $index = $index + 5;
                } else {
                # Program don't have Description
                        $index = $index + 4;
                }
                my %h = (       time =>         $p_stime,
                                category=>      $p_category,
                                title=>         $p_title,
                                desc =>         $p_desc );
		$h{subtitle} = $p_subtitle if defined $p_subtitle;
                push @data, \%h;
#               t "Next time?: $txt_elems[$index]";
           } # end while prof the program
        }
        t $txt_elems[$index];
        $index = $index + 1;
    }
    return @data;
}
sub get_txt_elems {
    my ($tree) = @_;

    my @txt_elem;
    my @txt_cont = $tree->look_down(
                        sub { ($_[0]->descendants() eq 0  ) },       
			sub { defined($_[0]->attr ("_content") ) } );
	foreach my $txt (@txt_cont) {
        	my @children=$txt->content_list;
		if (defined($children[0])) {
                  for (my $tmp=$children[0]) {
			s/^\s+//;s/\s+$//;
			push @txt_elem, $_;
                      }
                }
	}
    return @txt_elem;
}

# get channel listing
sub get_channels {
    my $bar = new XMLTV::ProgressBar('getting list of channels', 1)
	if not $opt_quiet;
    my %channels;
    my $url="http://www.elpais.es/parrillatv/portada.html";
    t $url;

    my $tree = get_nice_tree $url;
    my @menus = $tree->find_by_tag_name("_tag"=>"select");

    foreach my $elem (@menus) {
	my $cname = $elem->attr('name');
	if ($cname eq "canal") {
	    my @ocanals = $elem->find_by_tag_name("_tag"=>"option");
	    @ocanals = sort @ocanals;
	    foreach my $opt (@ocanals) {
		if (not $opt->attr('value') eq "") {
		    my @str = split (/-/,$opt->attr('value'));
		    my $channel_id = $str[0];
		    my $channel_name=$str[1];
		    my $channel_num = $channel_id;
		    if (length $channel_id eq 1) {
			$channel_id = "0" . $channel_id
		    }
		    $channels{$channel_id}=$channel_name;
		    push @ch_all, { 'display-name' => [ [ $str[1], $LANG ],
						        [ $channel_num ] ],
				    'id'=> "$channel_id.elpais.es" };
		}
	    }
	}
    }
    die "no channels could be found" if not keys %channels;
    update $bar if not $opt_quiet;
    $bar->finish() if not $opt_quiet;
    return %channels;
}


# Bump a YYYYMMDD date by one.
sub nextday {
    my $d = shift;
    my $p = parse_date($d);
    my $n = DateCalc($p, '+ 1 day');
    return UnixDate($n, '%Q');
}

