#!/usr/bin/perl

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

=pod

=head1 NAME

tv_grab_ch_bluewin - Grab TV listings for Switzerland (from fernsehen.bluewin.ch webpage).

=head1 SYNOPSIS

tv_grab_ch_bluewin --help

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

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

tv_grab_ch_bluewin --list-channels

tv_grab_de_bluewin --capabilities

tv_grab_de_bluewin --version

=head1 DESCRIPTION

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

First run B<tv_grab_ch_bluewin --configure> to choose, which channels 
you want to download. Then running B<tv_grab_ch_bluewin> 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_bluewin.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://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.
Adaption to the new design of bluewin by Ren Bhlmann.

=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 Time::Local;
use Date::Manip;
use XMLTV::Version '$Id: tv_grab_ch_bluewin.in,v 1.5 2006/11/30 09:02:38 betlit Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig cache share/;
use XMLTV::Description 'Switzerland (www.bluewin.ch)';
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 www.bluewin.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

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 Bluewins 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_group($$);

## attributes of xmltv root element
my $head = { 
    'source-data-url'      => 'http://epg.sso.bluewin.ch/de/index.php/channelview/',
    'source-info-url'      => 'http://epg.sso.bluewin.ch/de/detailview.php?action=DetailView&BroadcastID=',
    'generator-info-name'  => 'XMLTV',
    'generator-info-url'   => 'http://membled.com/work/apps/xmltv/',
};

my @groupid = ('10','11','12','13','14','15','16','17','18','20','22','25');
#my @groupid = ('12');

## the timezone fernsehen.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_list_channels;
my $opt_help;
my $opt_share;

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,
    'list-channels'  => \$opt_list_channels,
    'help'           => \$opt_help,
    'share=s'        => \$opt_share,
) 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_bluewin', $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 cant live without channel data, so lets get those now!
my $bar = new XMLTV::ProgressBar( 'getting list of channels', scalar(@groupid) )
    if not $opt_quiet;

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



# share/ directory for storing channel mapping files.  This next line
# is altered by processing through tv_grab_ch_bluewin.PL.  But we can
# use the current directory instead of share/tv_grab_ch_bluewin for
# development.
#
# The 'source' file tv_grab_ch_bluewin.in has $SHARE_DIR undef, which
# means use the current directory.  In any case the directory can be
# overridden with the --share option (useful for testing).
#
my $SHARE_DIR='/usr/share/xmltv'; # by grab/ch_bluewin/tv_grab_ch_bluewin.PL

$SHARE_DIR = $opt_share if defined $opt_share;
my $OUR_SHARE_DIR = (defined $SHARE_DIR) ? "$SHARE_DIR/tv_grab_ch_bluewin" : '.';


# Read the file with channel mappings.
(my $CHANNEL_NAMES_FILE = "$OUR_SHARE_DIR/channel_ids") =~ tr!/!/!s;
my (%chid_mapping, %seen);
my $line_num = 0;
foreach (XMLTV::Config_file::read_lines($CHANNEL_NAMES_FILE, 1)) {
    ++ $line_num;
    next unless defined;
    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, $bluewin_ch_id) = @fields;
    warn "$where: bluewin.ch id $bluewin_ch_id seen already\n"
      if defined $chid_mapping{$bluewin_ch_id};
    $chid_mapping{$bluewin_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_bluewin.\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]],
			'icon'        => [(0 => "http://epg.sso.bluewin.ch/images/tvchannel_logos/$_")]); 
        $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 %icon = ('src' => "http://epg.sso.bluewin.ch/images/tvchannel_logos/$_");
    my %channel = ('id'           => $id, 
                   'display-name' => [[$channels{$_}, $lang]],
		    'icon'        => [{'src' => "http://epg.sso.bluewin.ch/images/tvchannel_logos/$_"}]); 
    $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)*13*$opt_days)
  if not $opt_quiet;

foreach my $id (@groupid) {
    grab_channel_group($id,\@requests);
}

$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{$_} : "$_.bluewin.ch");
	$_ = "C$_" if /^\d/;
	return $_;
    }
}


sub array_contains($$) {

    my $reqs = shift;
    my $element = shift;

    foreach (@$reqs) {
	
        if ($_ eq $element) {
            return 1;
        }
    }
    return 0;
}

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

    my $group = shift;   
    my $requests = shift;

    my $channel;

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

    my $loop_date = timelocal(0,0,6,substr($grabDate,6,2),substr($grabDate,4,2)-1,substr($grabDate,0,4));     

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

    $url = "$url?action=ChannelView&SupergroupID=".$group."&date=$loop_date&segments=11111";
	
    $tb->parse(get_page($url))
      or die "cannot parse content of $url";    
    $tb->eof;

    my $col=0;

    my @channels;

    #We need to know the channel order

    foreach($tb->look_down('_tag' => 'div', 'class' => 'segment_logo' )) {
        next unless(ref($_) eq "HTML::Element");

        my $chan = $_;
	
        my $img=undef;
	
        foreach($chan->look_down('_tag' => 'img')) {
	    next unless(ref($_) eq "HTML::Element");

	    if (ref($img) eq "HTML::Element") {
                die "Multiple img tags!";
            }
	    if ($_->attr('title')) {
                $img=$_;
            }
        }

        my $channel_name = $img->attr('title');
        my $logo = $img->attr('src');
        $logo =~ m/tvchannel_logos\/(.+\.[a-z][a-z][a-z])/ or die "unable to extract logo";
        $logo = $1;

        push(@channels,$logo);
	$col++;
    }

    $col=0;
    
    foreach($tb->look_down('_tag' => 'div', 'class' => 'segment')) {
        next unless(ref($_) eq "HTML::Element");

        if (not array_contains($requests,$channels[$col])) {
            my $len =@channels;
            $col = ($col+1) % $len;
            next;
        }

        	$bar->update() if not $opt_quiet;

	my $segment = $_;

 	my @classes=("segment_content","segment_content_2"); 
    foreach(@classes) { 	
	
	foreach($segment->look_down('_tag' => 'div', 'class' => $_)) { 
            next unless(ref($_) eq "HTML::Element");


            my $segment_content = $_;

	    my $id=undef;

            for (@{$segment_content->extract_links('a')}) {
		if ($id) {
                    die "Multiple link tags!";
		}
                my($link, $element, $attr, $tag) = @$_;
		$link =~ m/\(([0-9]+)\)/ or die "Unable to extract id!";
		$id = $1;
            }

            if (not $id) {
		#$segment_content->dump();
		next;
                die "Unable to get id!";
	    }


            my $prog_time=$segment_content->look_down('_tag' => 'div', 'class' => 'programm_time ');
            if (ref($prog_time) ne "HTML::Element") {
               die "Time tag not found";
            }
            my @content = $prog_time->content_list();
            my $time = $content[0];

            if (not $time) {
                die "Unable to get time!";
	    }

	    

            my ($hh,$mm) = split(/:/,$time);
            my $realstartdate = $grabDate;
            if ($hh<6) {
                $realstartdate = &DateCalc($realstartdate,"+ 1 day");
            }
            my $file_date = substr($realstartdate,6,2).'.'.substr($realstartdate,4,2). '.'.substr($realstartdate,0,4);

	    my @details = get_details($id,$channels[$col],$file_date,$time); 

            my $realenddate = $realstartdate;

            my $emm;
            my $ehh;
            if (length($details[4])) {
                ($ehh,$emm) = split(/:/,$details[4]);
            }
            else {
                $emm=$mm;
                $ehh=($hh+1)%24;
            }
            
            if ($ehh<$hh) {
                $realenddate = &DateCalc($realenddate,"+ 1 day");
            }
            if (length($ehh)<2) { 
                $ehh="0$ehh"; 
            } 

            my %show;
	    $show{channel} = channel_id($channels[$col]);


            my $startdate = substr($realstartdate,0,4) . substr($realstartdate,4,2) . substr($realstartdate,6,2);
            my $enddate = substr($realenddate,0,4) . substr($realenddate,4,2) . substr($realenddate,6,2);

            $show{start} = "$startdate".$hh.$mm."00 $TZ";
            $show{stop} = "$enddate".$ehh.$emm."00 $TZ";
            $show{category} = [[$details[2],$lang]];
            $show{'title'} = [[$details[0],$lang]];
            if (length($details[1])) {
                $show{'sub-title'} = [[$details[1],$lang]];
            }
            if (length($details[5])) {
                $show{'year'} = [[$details[5],$lang]];
            }


	    $writer->write_programme(\%show);

       }        
     }

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

## get_details ($id, $channel, $date, $time)
sub get_details ($$$$) {
	my $id= shift;
        my $channel = shift;
        my $date = shift;
        my $time = shift;

	my $url=$head->{q(source-info-url)} . $id;

	my @result = ("","","","","","","","","","","","","");
	## tilte, episode title, cat, description, endtime, year, actors, director, 
	## writer, presenter, audio, subtitles, previously-shown
        my $len = @result;
        for (my $i=0; $i<$len;$i++) {
            $result[$i]="";
        }
 
	my $tb=new HTML::TreeBuilder();
	$tb->parse(get_page($url))
	  or die "cannot parse content of $url";	
	$tb->eof;

        my $tit1 = $tb->look_down('_tag' => 'span', 'class' => 'tit1');
        if (ref($tit1) ne "HTML::Element") {
           die "Title tag not found";
        }

        my @content = $tit1->content_list();
        $result[0] = $content[0];
        chop($result[0]);
        chomp($result[0]);

        foreach($tit1->look_down('_tag' => 'wbr')) {
            my $stit = $_;
            if (ref($stit) eq "HTML::Element") {
               $stit = $stit->right();
            }
            if (length($stit)) {
               if (length($result[1])) {
                   chop($result[1]);
                   chomp($result[1]);
                   $result[0].="- $result[1]";
               }
               $result[1] = $stit;
            }
        }

        my $titd = $tb->look_down('_tag' => 'span', 'class' => 'titdblue');
        if (ref($titd) ne "HTML::Element") {
           die "Category tag not found";
        }

        @content = $titd->content_list();
	$content[0] =~ m/([^:]+):/ or die "unable to extract category";
        $result[2] = $1;

        if ($content[0] =~ m/([1-2][0-9][0-9][0-9])/) {
            $content[5] = $1;
        }


        my $desc = $tb->look_down('_tag' => 'div', 'class' => 'text');
        if (ref($desc) ne "HTML::Element") {
           die "Text tag not found";
        }

        @content = $desc->content_list();
        $result[3] = $content[$#content];

        #<table border="0" cellpadding="0" cellspacing="5" width="100%" style="border: 1px solid #99ccff;"
        my $bc = $tb->look_down('_tag' => 'table', 'border' => '0', 'cellspacing' => '5', 'width' => '100%');
        @content = $bc->content_list();
        foreach(@content) {
            next unless(ref($_) eq "HTML::Element");

            my $check = $_->look_down('_tag' => 'img', 'src' => '/images/tvchannel_logos/'.$channel);
            if (ref($check) ne "HTML::Element") {
                next;
            }

            if (not $_->as_text() =~ m/$date.*$time \- ([0-2][0-9]:[0-6][0-9])/) {
                next;
            }

            $result[4] = $1;
            

        }

    
    $tb->delete();
    
	return @result;
}

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

    my $tb=new HTML::TreeBuilder();
    
    ## getting the channels directly selectable
    foreach(@groupid) {

        $tb->parse(get_page($url ."?action=ChannelView&SupergroupID=".$_."&date=1164430800&segments=00000")) 
            or die "cannot parse content of $url";    
        $tb->eof;

        foreach($tb->look_down('_tag' => 'div', 'class' => 'segment_logo' )) {
            next unless(ref($_) eq "HTML::Element");

            my $chan = $_;
	
            my $img=undef;
	
            foreach($chan->look_down('_tag' => 'img')) {
	        next unless(ref($_) eq "HTML::Element");

	        if (ref($img) eq "HTML::Element") {
	            die "Multiple img tags!";
                }
	        if ($_->attr('title')) {
	            $img=$_;
                }
            }

            my $channel_name = $img->attr('title');
            my $logo = $img->attr('src');
            $logo =~ m/tvchannel_logos\/(.+\.[a-z][a-z][a-z])/ or die "unable to extract logo";
            $logo = $1;

            $channels{$logo} = $channel_name;
        }
	$bar->update() if not $opt_quiet;
	

    }

    $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";
}
