#!/usr/bin/perl

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

=pod

=head1 NAME

tv_grab_ch_search - Grab TV listings for Switzerland (from tv.search.ch webpage).

=head1 SYNOPSIS

tv_grab_ch_search --help

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

tv_grab_ch_search [--config-file FILE] [--output FILE] [--quiet]
           [--days N] [--offset N] [--slow]

tv_grab_ch_search --list-channels

tv_grab_ch_search --capabilities

tv_grab_ch_search --version

=head1 DESCRIPTION

Output TV listings for several channels available in Switzerland and
(partly) central Europe. 
The data comes from tv.search.ch. The grabber relies on
parsing HTML so it might stop working at any time.

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

B<--configure> Ask for each available channel whether to download
and write the configuration file.

B<--config-file FILE> Set the name of the configuration file, the
default is B<~/.xmltv/tv_grab_ch_search.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 Term::ProgressBar.

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

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

B<--offset N> Start N days in the future.  The default is to start
from now on (= zero).

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

B<--slow> enables long strategy run: tv.search.ch publishes only some (vital)
information on the actual listing pages, the rest is shown in a separate
popup window. If you'd like to parse the data from these popups as well,
supply this flag. But consider that the grab process takes much longer when
doing so, since many more web pages have to be retrieved.

B<--list-channels> Write output giving <channel> elements for every
channel available (ignoring the config file), but no programmes.

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

Daniel Bittel <daniel.bittel@solnet.ch>. Inspired by tv_grab_ch by Stefan Siegl.

=head1 BUGS

If you happen to find a bug, you're requested to send a mail to me
at B<daniel.bittel@solnet.ch> or to one of the XMLTV mailing lists, see webpages
at http://sourceforge.net/projects/xmltv/.

=cut

use warnings;
use strict;
use Date::Manip;
use XMLTV::Version '$Id: tv_grab_ch_search.in,v 1.7 2008/03/25 18:43:25 betlit Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig cache/;
use XMLTV::Description 'Switzerland (tv.search.ch)';
use XMLTV::Supplement qw/GetSupplement/;
use Getopt::Long;
use HTML::TreeBuilder;
use HTML::Entities;
use URI::Escape;
use XMLTV;
use XMLTV::Ask;
use XMLTV::ProgressBar;
use XMLTV::DST;
use XMLTV::Config_file;
use XMLTV::Mode;
use XMLTV::Get_nice;
use XMLTV::Memoize;
use XMLTV::Usage<<END
$0: get Swiss television listings from tv.search.ch in XMLTV format
To configure: $0 --configure [--config-file FILE] [--gui OPTION]
To grab data: $0 [--config-file FILE] [--output FILE] [--quiet]
                 [--days N] [--offset N] [--slow]
Channel List: $0 --list-channels
To show capabilities: $0 --capabilities
To show version: $0 --version

Don't try to run this grabber between midnight and ~6 o'clock in the morning
to get data for the current day (ergo: without offset):
When viewing search.ch's website after midnight, I found they only display 
data from early in the morning of that day.
END
  ;

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



## our own prototypes first ...
sub get_channels();
sub channel_id($);
sub get_page($);
sub grab_channel($);

## attributes of xmltv root element
my $head = { 
    'source-data-url'      => 'http://tv.search.ch/programm/',
    'source-info-url'      => 'http://tv.search.ch/',
    'generator-info-name'  => 'XMLTV',
    'generator-info-url'   => 'http://membled.com/work/apps/xmltv/',
};



## the timezone tv.search.ch lives in is, CET/CEST
my constant $TZ = "+0100";
my constant $lang = "de";



## Parse argv now.  First do undocumented --cache option.
XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');



my $opt_configure;
my $opt_config_file;
my $opt_gui;
my $opt_output;
my $opt_days = 14;
my $opt_offset = 0;
my $opt_quiet = 0;
my $opt_slow = 0;
my $opt_list_channels;
my $opt_help;

GetOptions(
    'configure'      => \$opt_configure,
    'config-file=s'  => \$opt_config_file,
    'gui:s'          => \$opt_gui,
    'output=s'       => \$opt_output,
    'days=i'         => \$opt_days,
    'offset=i'       => \$opt_offset,
    'quiet'          => \$opt_quiet,
    'slow'           => \$opt_slow,    
    'list-channels'  => \$opt_list_channels,
    'help'           => \$opt_help,
) or usage(0);

usage(1) if $opt_help;

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

## make sure offset+days arguments are within range
die "neither offset nor days may be negative"
  if($opt_offset < 0 || $opt_days < 0);


## calculate global start/stop times ...
my $grab_start = DateCalc("00:00:00", "+ $opt_offset days");
my $grab_stop = DateCalc($grab_start, "+ $opt_days days");


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



## initialize config file support
my $config_file = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_ch_search', $opt_quiet);
my @config_lines;

if($mode eq 'configure') {
    XMLTV::Config_file::check_no_overwrite($config_file);
} 
elsif($mode eq 'grab' || $mode eq 'list-channels') {
    @config_lines = XMLTV::Config_file::read_lines($config_file);
} 
else { die("never heard of XMLTV mode $mode, sorry :-(") }



## hey, we can't live without channel data, so let's get those now!
my $bar = new XMLTV::ProgressBar( 'getting list of channels', 1 )
    if not $opt_quiet;

my %channels = get_channels();
$bar->update() if not $opt_quiet;
$bar->finish() if not $opt_quiet;




# Read the file with channel mappings.
my $CHANNEL_NAMES_FILE = "channel_ids";
my $str = GetSupplement( 'tv_grab_ch_search', 'channel_ids' );
my (%chid_mapping, %seen);
my $line_num = 0;
foreach (split( /\n/, $str )) {
    ++ $line_num;
    tr/\r//d;

    s/#.*//;
    next if m/^\s*$/;

    my $where = "$CHANNEL_NAMES_FILE:$line_num";
    
    my @fields = split m/:/;
    print @fields   if(@fields != 2 );
    die "$where: wrong number of fields"
      if(@fields != 2 );

    my ($xmltv_id, $search_ch_id) = @fields;
    warn "$where: search.ch id $search_ch_id seen already\n"
      if defined $chid_mapping{$search_ch_id};
    $chid_mapping{$search_ch_id} = $xmltv_id;
    
    warn "$where: XMLTV id $xmltv_id seen already\n"
      if $seen{$xmltv_id}++;
}

my @requests;

## read our configuration file now
my $line = 1;
foreach(@config_lines) {
    $line ++;
    next unless defined;

    if (/^channel:?\s+(\S+)/) {
	warn("\nConfigured channel $1 not available anymore. \nPlease reconfigure tv_grab_ch_search.\n"),
	  next unless(defined($channels{$1}));
	push @requests, $1;
    } 
    elsif (/^map:?\s+(\S+)\s+(\S+)/) {
	# Override anything set in the channel_ids file.
	$chid_mapping{$1} = $2;
    } 
    else {
	warn "$config_file:$line: bad line\n";
    }
}

## if we're requested to do so, write out a new config file ...
if ($mode eq 'configure') {
    open(CONFIG, ">$config_file") or die("cannot write to $config_file, due to: $!");

    ## now let's annoy the user, sorry, I meant ask ..
    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;
	my $chname = shift @names;
	
	warn("cannot read input, stopping to ask questions ..."), last if not defined $w;

	print CONFIG '#' if not $w; #- comment line out if user answer 'no'

	# shall we store the display name in the config file?
	# leave it in, since it probably makes it a lot easier for the
	# user to choose which channel to comment/uncommet - when manually
	# viing the config file -- are there people who do that?
	print CONFIG "channel $_ #$chname\n";
    }

    close CONFIG or warn "unable to nicely close the config file: $!";
    say("Finished configuration.");

    exit();
}



## well, we don't have to write a config file, so, probably it's some xml stuff :)
## if not, let's go dying ...
die unless($mode eq 'grab' or $mode eq 'list-channels');

my %writer_args;
if (defined $opt_output) {
    my $handle = new IO::File(">$opt_output");
    die "cannot write to output file, $opt_output: $!" unless (defined $handle);
    $writer_args{'OUTPUT'} = $handle;
}

$writer_args{'encoding'} = 'ISO-8859-1';


if( defined( $opt_days )) {
    $writer_args{offset} = $opt_offset;
	$writer_args{days} = $opt_days;
	$writer_args{cutoff} = "060000";
}

## create our writer object
my $writer = new XMLTV::Writer(%writer_args);
$writer->start($head);



if ($mode eq 'list-channels') {
    foreach (keys %channels) {
        my %channel = ('id'           => channel_id($_), 
                       'display-name' => [[$channels{$_}, $lang]]); 
        $writer->write_channel(\%channel);
    }

    $writer->end();
    exit();
}



## there's only one thing, why we might exist: write out tvdata!
die unless ($mode eq 'grab');
die "No channels specified, run me with --configure flag\n" unless(scalar(@requests));



## write out <channel> tags
foreach(@requests) {
    my $id = channel_id($_);
    my %channel = ('id'           => $id, 
                   'display-name' => [[$channels{$_}, $lang]]); 
    $writer->write_channel(\%channel);
}


## the page doesn't specify the year when the programmes begin or end, thus
## we need to guess, store current year and month globally as needed for every
## programme ...
my ($cur_year, $cur_month) = ParseDate('now') =~ m/(....)(..)/;

## write out <programme> tags
$bar = new XMLTV::ProgressBar('grabbing channels       ', scalar(@requests))
  if not $opt_quiet;

foreach my $channel (@requests) {
    grab_channel $channel;
    update $bar if not $opt_quiet;
}

$bar->finish()
    unless($opt_quiet);



## hey, looks like we've finished ...
$writer->end();



## channel_id($s) :: turn site channel id into an xmltv id
sub channel_id($) {  
    for (my $s = shift) {
	$_ = lc(defined($chid_mapping{$_}) ? $chid_mapping{$_} : "$_.search.ch");
	$_ = "C$_" if /^\d/;
	return $_;
    }
}





## grab_channel($start, $laststart, $laststop, $stop)
sub grab_channel($) {
    my ($start, $laststart, $laststop, $stop);

    my $channel = shift;
    my $grabDate = $grab_start;
  grab_channel_loop:
    my $tb = HTML::TreeBuilder->new();
    my $got = 0;

    
    my $loop_date = substr($grabDate,0,4) . '-' . substr($grabDate,4,2) . '-' . substr($grabDate,6,2);
    
    $tb->parse(get_page("http://tv.search.ch/programm/station/detail.php?id=$channel&day=$loop_date"))
      or die "cannot parse content of http://tv.search.ch/programm/station/detail.php?id=$channel&day=$loop_date";    
    $tb->eof;

	if ( $opt_slow ) 
	{
     foreach my $blah (@{( ($tb->look_down('_tag' => 'table', 'width' => '100%', 'border' => 0, 'cellspacing' => 0, 'cellpadding' => 0))[3] )->extract_links()}) 
     {
		my %show;
		$show{channel} = channel_id($channel);
		
		my($link, $element, $attr, $tag) = @$blah;
		next if ( $element->as_text() eq '' );

        my @details = get_details ( $link,  $element->as_text() );
				
		my ($start_base, $start_tz) = @{ date_to_local($details[0], $TZ) };
		my ($stop_base, $stop_tz) = @{ date_to_local($details[1], $TZ) };

		$show{start} = UnixDate($start_base, '%q') . " $start_tz";
		$show{stop} = UnixDate($stop_base, '%q') . " $stop_tz";

		$details[2] =~ s/^\s+//;
    	$details[2] =~ s/\s+$//;
	
		$show{'category'} = [[$details[2], $lang]] if ( length($details[2]) ) ;

        $show{'title'} = [[$details[3], $lang]]; 
            	
        $show{'sub-title'} = [[$details[4], $lang]] if(length($details[4]));
       
	    $show{desc} = [[ $details[5], $lang ]] if(length($details[5]));
            
       
       
       
  	    if(length($details[6])) {
       		my @actors = split(m/\s*,\s*/, $details[6]);
       		$show{credits}{actor} = \@actors;
       }
       
  	    		
  	    if(length($details[7])) {
        	my @directors = split(m/\s*,\s*/, $details[7]);
        	$show{credits}{director} = \@directors;
       }
            	
       if(length($details[8])) {
			my @writers = split(m/\s*,\s*/, $details[8]);
			$show{credits}{writer} = \@writers;
       }
	
		if(length($details[9])) {
			my @presenters = split(m/\s*,\s*/, $details[9]);
			$show{credits}{presenter} = \@presenters;
       }

       $show{audio}{stereo} = $details[10] if(length($details[10]) );

	   $show{subtitles} = [{ type => $details[11] }] if(length($details[11]));

       $show{'previously-shown'} = {} if(length($details[12]));

	   $show{video}{aspect} = $details[13] if(length($details[13]) );
	   
	   $show{'country'} = [[$details[14], $lang]] if ( length($details[14]) ) ;

	   $writer->write_programme(\%show);
	 }	
	}
	else
	{
		
		
			my $mainTable = ($tb->look_down('_tag' => 'table', 'width' => '100%', 'border' => 0, 'cellspacing' => 0, 'cellpadding' => 0))[3];
			
	
			foreach ( $mainTable->look_down ('_tag' => 'td', 'width' => '100%' ) ) 
			{
			
			next if $_->as_text() eq " TV-Guide" ;
			my %show;
			$show{channel} = channel_id($channel);

			$show{'title'} = [[(( $_->look_down ('_tag' => 'a'))[0])->as_text(), $lang]];
			
			my $tmpStr = (( $_->look_down ('_tag' => 'a'))[0])->as_HTML();
			$tmpStr =~ s/(.*)const_id=(.{10,10})(.{2,2})(.{2,2})(.*)/$2:$3/;
						

			my ($start_base, $start_tz) = @{ date_to_local(parse_local_date( ( $tmpStr), $TZ), $TZ) };
			

			$show{start} = UnixDate($start_base, '%q') . " $start_tz";
			
			$tmpStr = $_->as_HTML();
			$tmpStr =~ s/(.*)<\/a>(.*)<\/td>/$2/;
			$tmpStr =~ s/\(//g;
			$tmpStr =~ s/\&nbsp;//g;
			

			my $tb2=new HTML::TreeBuilder();
    		$tb2->parse($tmpStr);
			$tmpStr = $tb2->as_text();
			$tb2->delete();

			
			my @additional_info = split('\)', $tmpStr );
			
			$show{'category'} = [[$additional_info[0], $lang]] if exists $additional_info[ 0 ];
			my $size = @additional_info;

			for (my $count = 1; $count < $size; $count++) {
			$additional_info[ $count ]  =~ s/^\s+//;
			$additional_info[ $count ]  =~ s/\s+$//;

			  $show{'previously-shown'} = {} if ( $additional_info[ $count ] eq "W" );
			}


			$writer->write_programme(\%show);
			}

	
	}
	
   
    $tb->delete();    
	
    $grabDate = &DateCalc($grabDate,"+ 1 day");
	
    if(Date_Cmp($grab_stop, $grabDate) > 0) {
		goto grab_channel_loop;
    }
	
}


## get_details ($url, $title)

sub get_details ($) {
	my $url= "http://tv.search.ch" . shift;        # no slash after .ch!
	my $title = shift;
	## http://tv.search.ch/programm/detail/index.php?const_id=.....

	my @result = ("","","","","","","","","","","","","","","");
	## start-time, end-time, genre
	## tilte, episode title, description, actors, director, 
	## writer, presenter, audio, subtitles, previously-shown, aspect ratio
 
	my $tb=new HTML::TreeBuilder();
	$tb->no_space_compacting(1);
	$tb->parse(get_page($url))
	  or die "cannot parse content of $url";	
	$tb->eof;
	
	## start and end-time
	foreach (	
	$tb->look_down('_tag' => 'table', 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0) )
	{		
		foreach ( $_->look_down('_tag' => 'tr' ))	
		{
			if ($_->as_text() =~ m/Ausstrahlung:/)
			{
			    my $broadcast_details = (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text(); 
			    
				my $tmpStr = $broadcast_details;
			    $tmpStr =~ s/^(.*),(.*),(.*) bis (.*)/$2/;
			    $tmpStr =~ s/^(.*)\.(.*)\.(.*)$/$2.$1.$3/;				    
				my $startDate = $tmpStr;
		
				$tmpStr = $broadcast_details;
			    $tmpStr =~ s/^(.*),(.*),(.*) bis (.*)/$3/;
	
				my $start = parse_local_date( ( $startDate.$tmpStr), $TZ);

				if ( Date_Cmp ($start, parse_local_date ( ( $startDate."06:00"), $TZ) ) < 0 )
				{
				 $start=DateCalc ( $start, "+ 1 day");
				}
	
				$tmpStr = $broadcast_details;
			    $tmpStr =~ s/^(.*),(.*),(.*) bis (.*)/$4/;				
				if ( $tmpStr =~ m/\(/ )
			    {
			     $tmpStr =~ s/(.*) \((.*)/$1/;
			    }
				my $stop= parse_local_date( ( $startDate.$tmpStr), $TZ);
				
														
				if ( Date_Cmp ($start, $stop ) > 0 ) { # if the end time is before the start time, the show ends after midnight.
					$stop=DateCalc ( $stop, "+ 1 day");
				}
				$result[0] = $start;
				$result[1] = $stop;
			}

			if ($_->as_text() =~ m/Genre:/)
			{
				## category
				$result[2] = (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text();
			}

			if ($_->as_text() =~ m/Titel:/)
			{
			
				## title and episode title
				my @title = split ( /         - /, (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_text());
				$result[3] = $title[0];
				$result[4] = $title[1] if (@title eq 2);
				$result[3] =~ s/([\x00-\x1F])//g;
				$result[4] =~ s/([\x00-\x1F])//g;
			}
			
			if ($_->as_text() =~ m/Inhalt:/)
			{
				## description
				$result[5] = (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text();
				$result[5] =~ s/([\x00-\x1F])//g;

			}

			if ($_->as_text() =~ m/Besetzung:/)
			{
				## actors
				foreach(@{(($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->extract_links('a')}) 
				{
        			my($link, $element, $attr, $tag) = @$_;
        			$result[6] = $result[6].$element->as_trimmed_text().",";
        		}
			}

			if ($_->as_text() =~ m/Regie:/)
			{
				## director(s)
				foreach(@{(($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->extract_links('a')}) 
				{
        			my($link, $element, $attr, $tag) = @$_;
        			$result[7] = $result[7].$element->as_trimmed_text().",";
        		}
			}
			
			if ($_->as_text() =~ m/Drehbuch:/)
			{
				## writer(s)
				foreach(@{(($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->extract_links('a')}) 
				{
			    	my($link, $element, $attr, $tag) = @$_;
			    	$result[8] = $result[8].$element->as_trimmed_text().",";
			    }
			}

			if ($_->as_text() =~ m/Moderation:/)
			{
				## presenter(s)
				$result[9] = (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text();
			}
			
		
			
			if ($_->as_text() =~ m/Besonderes:/)
			{
				## audio
			 	$result[10] = "stereo" if ((($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text() =~ m/Stereo/ );
			 	$result[10] = "surround" if ((($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text() =~ m/Dolby Surround/ );
				
				## subtitles
			 	$result[11] = "teletext" if ((($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text() =~ m/TXT-Untertitelt/ );
			 	
			 	## rerun
			 	$result[12] = "rerun" if ((($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text() =~ m/Wiederholung/ );
			 	
			 	## aspect ratio
			 	$result[13] = "16:9" if ((($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text() =~ m/16:9/ );
			}
			
			if ($_->as_text() =~ m/Land:/)
			{
				$result[14] = (($_->look_down('_tag' => 'td', 'class' => 'text' ))[1])->as_trimmed_text();
			}
			
	    }
	}    
    
	return @result;	
  
}

## get channel listing
sub get_channels() {
    my %channels;
    my $url=$head->{q(source-data-url)};

    my $tb=new HTML::TreeBuilder();
    $tb->parse(get_page($url))
	  or die "cannot parse content of $url";    
    $tb->eof;

	## getting the channels directly selectable
	foreach($tb->look_down('_tag' => 'table', 'width' => '100%', 'border' => 0, 'cellspacing' => 0, 'cellpadding' => 0, 'bgcolor' => '#ffffff' )) {
        next unless(ref($_) eq "HTML::Element");

        foreach(@{$_->extract_links('a')}) {

            my($link, $element, $attr, $tag) = @$_;
			my $channel_name = (($element->content_list())[0]->attr('alt'));
			$channel_name = (split (/zu /, $channel_name))[1];
            $link =~ m/id=(\S+)/
                or die "unable to extract chid from $link";

            $channels{uri_escape($1)} = $channel_name;
        }
    }

    
	

    $tb->delete;
    return %channels;
}



## get_page($url) :: try to download $url via http://, look for closing </body> tag or die
sub get_page($) {
    my $url = shift;
    my $retry = 0;

    local $SIG{__DIE__} = sub { die "\n$url: $_[0]" };
    
    while($retry < 2) {
        my $got = eval { get_nice($url . ($retry ? "&retry=$retry" : "")); };
        $retry ++;

        next if($@); # unable to download, doesn't look too good for us.
        return $got;
    }

    die "cannot grab webpage $url (tried $retry times). giving up. sorry";
}
