This file is indexed.

/usr/bin/tv_grab_ch_search is in xmltv-util 0.5.63-2.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#!/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 für Gehörlose/)
     {
      $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 Länge 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";
}