#!/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]

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<--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://wiki.xmltv.org/index.php/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 <betlit@gmx.net>. 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<betlit@gmx.net> or to one of the XMLTV mailing lists, see webpages
at http://sourceforge.net/projects/xmltv/.

=cut

use warnings;
use strict;
use DateTime;
use LWP::Simple;
use HTTP::Cookies;
use XMLTV::Version '$Id: tv_grab_ch_search.in,v 1.17 2012/05/01 16:18:23 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]
Channel List: $0 --list-channels
To show capabilities: $0 --capabilities
To show version: $0 --version

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/channels.de.html',
    'source-info-url'      => 'http://tv.search.ch/index.de.html',
    'generator-info-name'  => 'XMLTV',
    'generator-info-url'   => 'http://xmltv.org/',
};



## 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 = DateTime->now()->add( days => $opt_offset );
my $grab_stop = DateTime->now()->add ( days => $opt_offset + $opt_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;


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;
    } 
    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'} = 'utf-8';


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

## 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
my $paramstr ="";
foreach(@requests) {
    my $id = channel_id($_);
    my %channel = ('id'           => $id, 
                   'display-name' => [[$channels{$_}, $lang]]); 
    $writer->write_channel(\%channel);
     $paramstr = $paramstr."&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 = DateTime->now()->year();
my $cur_month = DateTime->now()->month();

my $url=$head->{q(source-data-url)};

	
my $ua = LWP::UserAgent->new(keep_alive => 300);	
$ua->cookie_jar(HTTP::Cookies->new());
$ua->agent("xmltv/$XMLTV::VERSION");
$ua->env_proxy;
	
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/x-www-form-urlencoded');
$req->content(substr ( $paramstr, 1));

# FIXME what is this request doing? It fills the cookie jar
$ua->request($req);
$ua->request($req);

## write out <programme> tags
grab_channels();

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


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



sub grab_channels
{
 my $grabDate = $grab_start;
 my $url = $head->{q(source-info-url)};
 
 $bar = new XMLTV::ProgressBar('grabbing channels       ', (6*$opt_days))
  if not $opt_quiet;

 grab_channel_loop:
 for (my $count = 0; $count < 6; $count++) 
 {
  my $tb = HTML::TreeBuilder->new();

  my $loop_date = $grabDate->year() . '-' . substr("0".$grabDate->month(),-2) . '-' . substr("0".$grabDate->day(),-2);
  my $req = HTTP::Request->new(GET => "$url?time=$loop_date+" . 4*$count .".00");
  $req->header('Accept' => 'text/html');
    
  $tb->parse(($ua->request($req))->content)
      or die "cannot parse content of http://tv.search.ch/?time=$loop_date+" . 4*$count .".00"; ;    
  $tb->eof;

  foreach my $tv_channel ( $tb->look_down('_tag' => 'div', 'class' => 'tv_channel') )
  {
   my $channel_id = $tv_channel->attr('id');
   if ( defined($channel_id) )
   {
    foreach my $tv_show ( $tv_channel ->look_down('_tag' => 'tr', sub { ($_[0]->as_HTML() =~ m{tv_b_}) && !($_[0]->as_HTML() =~ m{tv_before})  && !($_[0]->as_HTML() =~ m{tv_timegroup}) } ) )
    {
     my %show;
     $show{channel} = channel_id($channel_id);
     
     my $tmp = (($tv_show->look_down('_tag', 'td'))[0])->as_text();
     $show{start} = DateTime->new (
        year => $grabDate->year()
       ,month => $grabDate->month() 
       ,day   => $grabDate->day()
       ,hour  => substr($tmp,0,2) 
       ,minute => substr($tmp,3,2)
       ,second => 00
       ,time_zone => 'Europe/Zurich'
      )->strftime( "%Y%m%d%H%M%S %z" );

     $tmp  = $tv_show->as_HTML();
     if ( $tmp =~ /Untertitel fr Gehrlose/)
     {
      $show{subtitles} = [{ type => 'teletext' }];
     }
     if ( $tmp =~ /Zweikanalton/)
     {
      $show{audio}{stereo} = 'bilingual';
     }
     if ( $tmp =~ /16:9/)
     {
      $show{video}{aspect} = '16:9';
     }  
     
     foreach my $div ( $tv_show->look_down('_tag' => 'div', 
     		sub {
     			( ( $_[0]->attr ('class') eq "tv_tooltip") || ( $_[0]->attr ('class') eq "tv_tr_notooltip" ) )
     		    } )
     	     )
     {
      if ( $div->attr ('class') eq 'tv_tr_notooltip' )
      {
             $show{'title'} = [[$div->as_text(), $lang]]; 
      }
      else
      {
      
       my $title = (($div->look_down('_tag' => 'td', 'class' => 'title'))->look_down('_tag' => 'h2'))->as_text();
       my $sub_title = ($div->look_down('_tag' => 'td', 'class' => 'title'))->as_text();

       $sub_title =~ s/\Q$title \E//;
       if ( "$title" eq "$sub_title" )
       {
        $sub_title ="";
       } 

if($channel_id  =~ /tv_nickch/)

                                {

    $title =~ m/(.*?)([\s](((\d+\D+)|(\d+))))?$/;

               $title = $1;           # only get first group with the title (there is always content in it)

                # group 3 matches something like "123", "123B", "123BB" (not yet seen, but taken care of), after a title with a space, and could be prepended to sub_title

}

       foreach  my $year ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Produktionsjahr<\/th>} } ) )
       {
        $show{date} =  (($year->look_down('_tag', 'td'))->as_text());        
       }
       
       foreach  my $category ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Kategorie<\/th>} } ) )
	   {
        my $s =  (($category->look_down('_tag', 'td'))->as_text());        
        my @categories = split(m/\s*[\/]\s*/, $s);
        foreach ( @categories )
        {
         if ( $_ )
         {
          push @{$show{category}}, [$_, $lang ];
         }
        }
	   }
	   
	   foreach  my $category ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Produktionsinfos<\/th>} } ) )
       {
        my $s = (($category->look_down('_tag', 'td'))->as_text());        
        $s=~ s/\(.*//;
        my @categories = split(m/\s*[\/,]\s*/, $s);
        foreach my $category ( @categories )
        {
         if ( $category )
         {
          my $is_defined = 0;
		  foreach ( @{$show{category}} )
		  {
		    if ("${$_}[0]" eq "$category" )
		    {
		     $is_defined = 1;
		     last;
		    }
		  }
		  if ( $is_defined == 0 )
		  {
			push @{$show{category}}, [$category, $lang ];
		  }		  
         }
        }
       }	   
       

	   foreach  my $country ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Produktionsland<\/th>} } ) )
       {
        my $s =  (($country->look_down('_tag', 'td'))->as_text());        
        my @countries = split(m/\s*[\/,]\s*/, $s);
        foreach ( @countries )
        {
		  push @{$show{country}}, [$_, $lang ];         
        }
       }

       my $description =  "";
       foreach  my $desc ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Beschreibung<\/th>} } ) )
       {
        $description = (($desc->look_down('_tag', 'td'))->as_text());
        $description =~ s/ mehr... / /;
        $description =~ s/Folge verpasst(.*)voller Lnge zum kostenlosen Abruf bereit\.//;
        
       }

       foreach  my $cast ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Cast<\/th>} } ) )
       {
        my $s = (($cast->look_down('_tag', 'td'))->as_text());        
        $s=~ s/\(.*//;
        my @actors = split(m/\s*,\s*/, $s);
        $show{credits}{actor} = \@actors;
       }

       foreach my $directors ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Regisseur<\/th>} } ) )
       {
        my @directors = split(m/\s*,\s*/, (($directors->look_down('_tag', 'td'))->as_text()));
        $show{credits}{director} = \@directors;
       }

       foreach  ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Wiederholung<\/th>} } ) )
       {
        $show{'previously-shown'} = {}
       }
 
       foreach my $writers ($div->look_down('_tag' => 'tr', sub { $_[0]->as_HTML() =~ m{<th>Drehbuch<\/th>} } ) )
       {
        my @writers = split(m/\s*,\s*/, (($writers->look_down('_tag', 'td'))->as_text()));
        $show{credits}{writer} = \@writers;
       }
       $show{'title'} = [[$title, $lang]]; 
       $show{'sub-title'} = [[$sub_title, $lang]] if(length($sub_title));
       $show{desc} = [[ $description, $lang ]] if(length($description));
      }
     }
     $writer->write_programme(\%show); 

    } 
   }
  }
  $tb->delete();
  update $bar if not $opt_quiet;

 }
 $grabDate = $grabDate->add ( days => 1 );
 if( DateTime->compare ( $grab_stop, $grabDate ) > 0) 
 {
  goto grab_channel_loop;
 }
 $bar->finish()
  unless($opt_quiet);
}


## 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' => 'span', 'style' => 'float:right;display:inline' )) {
        next unless(ref($_) eq "HTML::Element");
        my $channel_name = $_->as_text();
	my $id = (((($_->look_up('_tag' => 'div'))[0])->look_down('_tag' => 'input', 'type' => 'checkbox'))[0])->attr('value');

        $channels{uri_escape($id)} = $channel_name;      
    }
    $tb->delete;

    # adding the sky-channels manually... why do these sites _NEVER_ stick to their own design?
    $channels{uri_escape("skyaction")} = "SKY ACTION";
    $channels{uri_escape("skycinema")} = "SKY CINEMA";
    $channels{uri_escape("skycinema1")} = "SKY CINEMA +1";
    $channels{uri_escape("skycinema24")} = "SKY CINEMA +24";
    $channels{uri_escape("skycinemahits")} = "SKY CINEMA HITS";
    $channels{uri_escape("skycomedy")} = "SKY COMEDY";
    $channels{uri_escape("skyemotion")} = "SKY EMOTION";
    $channels{uri_escape("skyfussballbundesliga")} = "Sky Fussball Bundesliga";
    $channels{uri_escape("skykrimi")} = "SKY KRIMI";
    $channels{uri_escape("skynostalgie")} = "SKY NOSTALGIE";
    $channels{uri_escape("skyselect")} = "Sky Select";
    $channels{uri_escape("skysport1")} = "Sky Sport 1";
    $channels{uri_escape("skysport2")} = "Sky Sport 2";
    $channels{uri_escape("skysportaustria")} = "SKY SPORT AUSTRIA";
    $channels{uri_escape("skysporthd")} = "SKY SPORT HD"; 
    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";
}
