Advertisement
Guest User

tv_grab_fr_telerama_pg_0.2

a guest
Aug 22nd, 2011
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 31.01 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
  4.     if 0; # not running under some shell
  5.  
  6. =head1 NAME
  7.  
  8. tv_grab_fr_telerama - Grab TV listings for France.
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  To configure:
  13.    tv_grab_fr --configure [--config-file FILE]
  14.  To grab listings:
  15.    tv_grab_fr [--config-file FILE] [--output FILE] [--days N]
  16.     [--offset N] [--quiet] [--noautocorrect] [--perdays] [--perweeks]
  17.     [--ch_prefix prefix] [--ch_postfix postfix]
  18.  To show capabilities:
  19.    tv_grab_fr --capabilities
  20.  To show version:
  21.    tv_grab_fr --version
  22.  Help:
  23.    tv_grab_fr --help
  24.  
  25. =head1 DESCRIPTION
  26.  
  27. Output TV listings for several channels available in France (Hertzian,
  28. Cable/satellite, Canal+ Sat).  The data comes from
  29. guidetv-iphone.telerama.fr.  The default is to grab as many days as possible
  30. from the current day onwards. The program description are
  31. downloaded.
  32.  
  33. B<--configure-more-channels> Use this option to create AUTRES CHAINES list.
  34.  This allow to grab listings for some channels that are not in automatically
  35. generated lists.
  36.  
  37. B<--configure> Grab channels informations from the website and ask for
  38. channel type and names.
  39.  
  40. B<--config-file FILE> Use FILE as config file instead of the default config
  41. file. This allow to have different config files for i.e. different apps.
  42.  
  43. B<--gui OPTION> Use this option to enable a graphical interface to be used.
  44. OPTION may be 'Tk', or left blank for the best available choice.
  45. Additional allowed values of OPTION are 'Term' for normal terminal output
  46. (default) and 'TermNoProgressBar' to disable the use of Term::ProgressBar.
  47.  
  48. B<--output FILE> Write to FILE rather than standard output.
  49.  
  50. B<--days N> Grab N days starting from today, rather than as many as
  51. possible. Due to the website organization, the speed depends on
  52. the --days value Default value is 11.
  53.  
  54. B<--offset N> Start grabbing N days from today, rather than starting
  55. today.  N may be negative. Due to the website organization, N cannot
  56. be inferior to -1.Default value is 0
  57.  
  58. B<--ch_prefix S> (string): string to add at the begining of XMLTV channel id
  59. Default value is "C"
  60.  
  61. B<--ch_postfix S> (string): string to add at the end of XMLTV channel id
  62. Default value is ".telerama.fr"
  63.  
  64. B<--quiet> Suppress the progress messages normally written to standard
  65. error.
  66.  
  67. B<--noautocorrect> Disable the new time overlapping autocorrection mechanism.
  68.  
  69. B<--perdays> Actually do nothing since "per days" is already set as default
  70. grabbing mode. This option is kept in the event of "per weeks" set back as
  71. default. In this case, it could be use to activate the "per days" grabbing mode.
  72.  
  73. B<--perweeks> Actually do nothing since "per days" is already forced as default
  74.  
  75. B<--capabilities> Show which capabilities the grabber supports. For more
  76. information, see L<http://xmltv.org/wiki/xmltvcapabilities.html>
  77.  
  78. B<--version> Show the version of the grabber.
  79.  
  80. B<--help> Print a help message and exit.
  81.  
  82. =head1 SEE ALSO
  83.  
  84. L<xmltv(5)>
  85.  
  86. =head1 AUTHOR
  87.  
  88. Zubrick, zubrick@number6.ch
  89. Modified by patrick-g  pgn<dot>ltech<at>free<dot>fr
  90.  
  91. =head1 LICENSE
  92.  
  93. This program is free software: you can redistribute it and/or modify
  94. it under the terms of the GNU General Public License as published by
  95. the Free Software Foundation, either version 3 of the License, or
  96. (at your option) any later version.
  97.  
  98. This program is distributed in the hope that it will be useful,
  99. but WITHOUT ANY WARRANTY; without even the implied warranty of
  100. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  101. GNU General Public License for more details.
  102.  
  103. You should have received a copy of the GNU General Public License
  104. along with this program.  If not, see <http://www.gnu.org/licenses/>.
  105. =cut
  106.  
  107.  
  108. use XMLTV::Usage <<END
  109. $0: get French television listings in XMLTV format
  110. To configure AUTRES CHAINES list: tv_grab_fr --configure-more-channels
  111. To configure: tv_grab_fr --configure [--config-file FILE]
  112. To grab listings: tv_grab_fr [--config-file FILE] [--output FILE] [--days N]
  113.     [--offset N] [--quiet] [--noautocorrect] [--perdays] [--perweeks]
  114.     [--ch_prefix prefix] [--ch_postfix postfix]
  115. To show capabilities: tv_grab_fr --capabilities
  116. To show version: tv_grab_fr --version
  117. Help: tv_grab_fr --help
  118. END
  119.   ;
  120.  
  121. use warnings;
  122. use strict;
  123. use XMLTV::Version '$Id: tv_grab_fr_telerama,v 1.8 2011/08/20 22:30:00 zubrick Exp $ ';
  124. use XMLTV::Capabilities qw/baseline manualconfig cache/;
  125. use XMLTV::Description 'France (telerama)';
  126. use Getopt::Long;
  127. use HTML::Entities; # parse entities
  128. use IO::File;
  129. use URI;
  130. use Date::Manip;
  131. use XMLTV;
  132. use XMLTV::Ask;
  133. use XMLTV::ProgressBar;
  134. use XMLTV::Mode;
  135. use XMLTV::Config_file;
  136. use XMLTV::DST;
  137. use LWP;
  138. use XMLTV::Get_nice;
  139. use XMLTV::Memoize;
  140. use File::Temp;
  141. use LWP::Simple;
  142. use LWP::UserAgent;
  143. use POSIX;
  144. use Encode;
  145.  
  146. #***************************************************************************
  147. # Main declarations
  148. #***************************************************************************
  149. my $LANG = "fr";
  150. my $VERSION   = "20082011-02";
  151.  
  152. # FIXME: Temporary avoid XML warnings (to be investigated)
  153. #no warnings;
  154.  
  155. # Slot of hours according to the website (needed to build the URL)
  156. my @offsets = (2, 3, 4, 5, 6, 7);
  157. # Slot of days for day per day grabbing
  158. # my @days = (2, 3, 4, 5, 6, 7, 8, 9);
  159.  
  160. my $Delay = 2; # in seconds
  161. my $FailOnError = 1; # Fail on fetch error
  162.  
  163. my %errors = ();
  164. my $last_get_time;
  165.  
  166. my $progexist;
  167. my %prevprog;
  168. my $prevtitle;
  169. my $prevstart;
  170. my $prevstop;
  171.  
  172. my $channel_postfix = ".telerama.fr";
  173. my $channel_prefix = "C";
  174.  
  175. #***************************************************************************
  176. # Global variables allocation according to options
  177. #***************************************************************************
  178. XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');
  179.  
  180. ##patch: tigerlol: correction des chevauchements d'horaire
  181. my ($opt_days,  $opt_help,  $opt_output,  $opt_per_days, $opt_per_weeks, $opt_offset,  $opt_gui, $opt_quiet,  $opt_list_channels, $opt_config_file, $opt_configure, $opt_noautocorrect, $opt_morechannels, $opt_verytv );
  182. ##/patch
  183.  
  184. $opt_per_weeks = 0;
  185. $opt_quiet  = 0;
  186. # The website is able to store at least 11 days from now
  187. my $default_opt_days = 11;
  188. $opt_output = '-'; # standard output
  189. GetOptions('days=i'    => \$opt_days,
  190.      'help'      => \$opt_help,
  191.      'output=s'  => \$opt_output,
  192.      'offset=i'  => \$opt_offset,
  193.      'quiet'     => \$opt_quiet,
  194.      'configure' => \$opt_configure,
  195.      'config-file=s' => \$opt_config_file,
  196.      'gui:s'     => \$opt_gui,
  197.      'list-channels' => \$opt_list_channels,
  198.      'perdays' => \$opt_per_days,
  199.      'perweeks' => \$opt_per_weeks,
  200.      'ch_prefix=s'  => \$channel_prefix,
  201.      'ch_postfix=s'  => \$channel_postfix,
  202. ##patch: tigerlol: correction des chevauchements d'horaire
  203.      'noautocorrect' => \$opt_noautocorrect,
  204. ##Gestion des channels non declares dans les listes "officielles"
  205.      'configure-more-channels' => \$opt_morechannels,
  206.      'verytv' => \$opt_verytv
  207. ##/patch
  208.     )
  209.   or usage(0);
  210.  
  211. my $CHANNEL_GRID;
  212. my $CHANNEL_GRID_PAGE;
  213. my $CHANNEL_ICON_PAGE;
  214. my $ROOT_URL;
  215.  
  216.  
  217. my $ua = LWP::UserAgent->new;
  218.  
  219. if($opt_verytv) {
  220.     $CHANNEL_GRID = 'http://91.121.66.148/~verytv/procedures/ListeChaines.php';
  221.     $CHANNEL_GRID_PAGE = "http://91.121.66.148/~verytv/procedures/LitProgrammes1Chaine.php?date=";
  222.     $ROOT_URL  = 'http://91.121.66.148';
  223.     $ua->agent("VeryTV/2.7 CFNetwork/459 Darwin/10.0.0d3");
  224. } else {
  225.     $CHANNEL_GRID = 'http://guidetv-iphone.telerama.fr/verytv/procedures/ListeChaines.php';
  226.     $CHANNEL_GRID_PAGE = "http://guidetv-iphone.telerama.fr/verytv/procedures/LitProgrammes1Chaine.php?date=";
  227.     $CHANNEL_ICON_PAGE = "http://guidetv-iphone.telerama.fr/verytv/procedures/images/";
  228.     $ROOT_URL  = 'http://guidetv-iphone.telerama.fr';
  229.     $ua->agent("Telerama/1.2 CFNetwork/459 Darwin/10.0.0d3");
  230. }
  231. $ua->env_proxy;
  232.  
  233.  
  234. #***************************************************************************
  235. # Options processing, warnings, checks and default parameters
  236. #***************************************************************************
  237. die 'Number of days must not be negative'  if (defined $opt_days && $opt_days < 0);
  238. die 'Cannot get more than one day before current day' if (defined $opt_offset && $opt_offset < -1);
  239. usage(1) if $opt_help;
  240.  
  241. XMLTV::Ask::init($opt_gui);
  242.  
  243. # The options can be used, but we default them if not set.
  244. $opt_offset = 0 if not defined $opt_offset;
  245. $opt_days = $default_opt_days if not defined $opt_days;
  246.  
  247. # Force the per days option in all cases
  248. if ( $opt_per_weeks == 0 ) {
  249.   $opt_per_days = 1;
  250. }
  251.  
  252. if ( (($opt_offset + $opt_days) > $default_opt_days) or ($opt_offset > $default_opt_days) ) {
  253.     $opt_days = $default_opt_days - $opt_offset;
  254.     if ($opt_days < 0) {
  255.         $opt_offset = 0;
  256.         $opt_days = $default_opt_days;
  257.     }
  258.     say <<END
  259. The website does not handle more than $default_opt_days days.
  260. So the grabber is now configure with --offset $opt_offset --days $opt_days
  261. END
  262. ;
  263. }
  264.  
  265. # Info about autocorrect mode
  266. if ( !$opt_quiet ) {
  267.   if ( !$opt_configure && !$opt_morechannels ) {
  268.     if ( $opt_noautocorrect ) {
  269.       say "Autocorrect DESACTIVE! - Autocorrect DISABLED!\n";
  270.     } else {
  271.       say "Autocorrect ACTIVE! - Autocorrect ENABLED!\n";
  272.     }
  273.   }
  274. }
  275.  
  276. #***************************************************************************
  277. # Last init before doing real work
  278. #***************************************************************************
  279. my %results;
  280. my $lastdaysoffset = $opt_offset + $opt_days - 1;
  281. my $checkDummySlot = 0;
  282.  
  283. # Now detects if we are in configure mode
  284. my $mode = XMLTV::Mode::mode('grab', # default
  285.                         $opt_configure => 'configure',
  286.                         $opt_list_channels => 'list-channels',
  287.                         $opt_morechannels  => 'confmorechannels' );
  288.  
  289. # File that stores which channels to download.
  290. my $config_file = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_fr_telerama', $opt_quiet);
  291.  
  292. #***************************************************************************
  293. # Sub sections
  294. #***************************************************************************
  295. sub get_channels( );
  296. sub return_other_channels( );
  297. sub build_other_channel_filename();
  298. sub get_more_channel_icon( $ );
  299. sub process_channel_grid_page( $$$$ );
  300. sub debug_print( @ );
  301. sub get_page( $ );
  302.  
  303. # Set this to 1 of you debug strings
  304. my $DEBUG_FR = 0;
  305. # Internal debug functions
  306. sub debug_print( @ ) {
  307.   if ($DEBUG_FR) { print @_; }
  308. }
  309.  
  310. sub xmlencoding {
  311.     # encode for xml
  312.     $_[0] =~ s/</&lt;/g;
  313.     $_[0] =~ s/>/&gt;/g;
  314.     $_[0] =~ s/&/\%26/g;
  315.     return $_[0];
  316. }
  317.  
  318.  
  319. #***************************************************************************
  320. # Configure mode
  321. #***************************************************************************
  322. if ($mode eq 'configure') {
  323.     XMLTV::Config_file::check_no_overwrite($config_file);
  324.     open(CONF, ">$config_file") or die "Cannot write to $config_file: $!";
  325.  
  326.     #my $bar = new XMLTV::ProgressBar('getting channel lists', scalar grep { $_ } @gtwant) if not $opt_quiet;
  327.     my %channels_for;
  328.     my %channels = get_channels();
  329.     die 'No channels could be found' if not %channels;
  330.  
  331.  
  332.     my %asked;
  333.  
  334.     # Ask about each channel (unless already asked).
  335.     my @chs = grep { not $asked{$_}++ } sort keys %channels;
  336.     my @names = map { $channels{$_}{name} } @chs;
  337.     my @qs = map { "add channel $_?" } @names;
  338.     my @want = ask_many_boolean(1, @qs);
  339.     foreach (@chs) {
  340.         my $w = shift @want;
  341.         warn("cannot read input, stopping channel questions"), last if not defined $w;
  342.         # Print a config line, but comment it out if channel not wanted.
  343.         print CONF '#' if not $w;
  344.         print CONF "channel $_ $channels{$_}{name};$channels{$_}{icon}\n";
  345.     }
  346.  
  347.     close CONF or warn "cannot close $config_file: $!";
  348.     say("Finished configuration.");
  349.     exit();
  350. }
  351.  
  352. #***************************************************************************
  353. # "Configure more channels" mode
  354. #***************************************************************************
  355. sub display_otherchannels_list(\%) {
  356.     my %chlist = %{(shift)};
  357.  
  358.     say ">>>>>> Current list <<<<<<";
  359.     foreach my $chid (keys %chlist) {
  360.         say "Channel ID: ". $chid." - Name: " . $chlist{$chid}{name} .
  361.             " - Icon: ". $chlist{$chid}{icon};
  362.     }
  363.     say ">>>>>> List end <<<<<<";
  364. }
  365.  
  366. if ($mode eq 'confmorechannels') {
  367.     # Display info message, pointing to the forum thread
  368.     my $input_file_notempty = 0;
  369.     my %morechannels = return_other_channels();
  370.     display_otherchannels_list(%morechannels);
  371.     if ( (scalar keys  %morechannels) > 0 ) {
  372.         $input_file_notempty= 1;
  373.     }
  374.     my $choice = "";
  375.     my ($chid, $chname, $chicon);
  376.  
  377.     while ( !($choice eq "exit")) {
  378.         $choice = ask_choice( "Select command to configure OTHERCHANNELS", "add", ("add", "remove", "view list", "save&exit", "exit") );
  379.         my $exit = 0;
  380.         if ($choice eq "add" ) {
  381.             while ($exit == 0) {
  382.                 $chid = ask('Enter channel ID : ');
  383.                 $chname = ask('Enter channel name : ');
  384.                 if ( !($chid =~ /^[0-9]*$/) ) {
  385.                     say ("Enter a numeric value for channel id");
  386.                 } else {
  387.                     if ( $chname eq "" ) {
  388.                         say ("Enter a string for the name of the channel");
  389.                     } else {
  390.                         $exit = 1;
  391.                     }
  392.                 }
  393.             }
  394.             say("Testing channel $chid - $chname ...");
  395.             my $chicon = get_more_channel_icon( $chid );
  396.             $morechannels{$chid} = {'name'=>$chname, 'icon'=>$chicon};
  397.         }
  398.         if ($choice eq "remove" ) {
  399.             display_otherchannels_list(%morechannels);
  400.             my $chid = ask('Enter the channel id to remove it (see list above): ');
  401.             if ( defined $morechannels{$chid} ) {
  402.                 $chname = $morechannels{$chid}{name};
  403.                 delete $morechannels{$chid};
  404.                 say ("Channel $chname removed");
  405.             } else {
  406.                 say("Channel $chid does not exist in the list");
  407.             }
  408.         }
  409.         if ($choice eq "view list" ) {
  410.             display_otherchannels_list(%morechannels);
  411.         }
  412.         if ($choice eq "save&exit") {
  413.             my $morechannels_file = build_other_channel_filename();
  414.             # Then write the file
  415.             if ( (scalar keys  %morechannels) > 0 ) {
  416.                 open(CONFMORE, ">$morechannels_file") or die "Cannot write to $morechannels_file: $!";
  417.                 foreach $chid (keys %morechannels) {
  418.                     if (!( $morechannels{$chid}{name} eq 'DELETED' )) {
  419.                         print CONFMORE "channel $chid $morechannels{$chid}{name};$morechannels{$chid}{icon}\n";
  420.                     }
  421.                 }
  422.                 close CONFMORE or warn "cannot close $morechannels_file: $!";
  423.                 display_otherchannels_list(%morechannels);
  424.                 say ('Channel list saved. Launch now a --configure mode to add them into the legacy config');
  425.             } else {
  426.                 unlink ($morechannels_file);
  427.                 say ('No channels to be configure, file deleted.');
  428.             }
  429.             $choice = "exit";
  430.         }
  431.     }
  432.     say("Finished configuration for OTHERCHANNELS.");
  433.     exit();
  434. }
  435.  
  436. #***************************************************************************
  437. # Check mode checking and get configuration file
  438. #***************************************************************************
  439. die if $mode ne 'grab' and $mode ne 'list-channels';
  440.  
  441. my @config_lines;
  442. if ($mode eq 'grab') {
  443.     @config_lines = XMLTV::Config_file::read_lines($config_file);
  444. }
  445.  
  446. #***************************************************************************
  447. # Prepare the XMLTV writer object
  448. #***************************************************************************
  449. my %w_args;
  450. if (defined $opt_output) {
  451.     my $fh = new IO::File(">$opt_output");
  452.     die "cannot write to $opt_output: $!" if not defined $fh;
  453.     $w_args{OUTPUT} = $fh;
  454. }
  455.  
  456. $w_args{encoding} = 'UTF-8';
  457.  
  458. my $writer = new XMLTV::Writer(%w_args);
  459. $writer->start
  460.   ({ 'source-info-url'     => $ROOT_URL,
  461.      'source-data-url'     => $ROOT_URL,
  462.      'generator-info-name' => 'XMLTV',
  463.      'generator-info-url'  => 'http://mythtv-fr.org/',
  464.    });
  465.  
  466. #***************************************************************************
  467. # List channels only case
  468. #***************************************************************************
  469. if ($mode eq 'list-channels') {
  470.     # Get a list of available channels, according to the grid type
  471.     my @gts;# = sort keys %GridType;
  472.     my @gtnames;# = map { $GridType{$_} } @gts;
  473.     my @gtqs = map { "List channels for grid : $_?" } @gts;
  474.     my @gtwant = ask_many_boolean(1, @gtqs);
  475.  
  476.     my %seen;
  477.     foreach (@gts) {
  478.         my $gtw = shift @gtwant;
  479.         my $gtname = shift @gtnames;
  480.         if ($gtw) {
  481.             say  "Now getting grid : $_ \n";
  482.             my %channels = get_channels( );
  483.             die 'no channels could be found' if (scalar(keys(%channels)) == 0);
  484.             foreach my $ch_did (sort(keys %channels)) {
  485.                 my $ch_xid = "C".$ch_did.".telepoche.com";
  486.                 $writer->write_channel({ id => $ch_xid,
  487.                                          'display-name' => [ [ $channels{$ch_did}{name} ] ],
  488.                                          'icon' => [{src=>$ROOT_URL.$channels{$ch_did}{icon}}] })
  489.                 unless $seen{$ch_xid}++;
  490.             }
  491.        }
  492.      }
  493.      $writer->end();
  494.      exit();
  495. }
  496.  
  497. #***************************************************************************
  498. # Now the real grabbing work
  499. #***************************************************************************
  500. die if $mode ne 'grab';
  501.  
  502. #***************************************************************************
  503. # Build the working list of channel name/channel id
  504. #***************************************************************************
  505. my (%channels, $chicon, $chid, $chname);
  506. my $line_num = 1;
  507. foreach (@config_lines) {
  508.     ++ $line_num;
  509.     next if not defined;
  510.  
  511.     # Here we store the Channel name with the ID in the config file, as the XMLTV id = Website ID
  512.     if (/^channel:?\s+(\S+)\s+([^\#]+);([^\#]+)/) {
  513.         $chid = $1;
  514.         $chname = $2;
  515.         $chicon = $3;
  516.         $chname =~ s/\s*$//;
  517.         $channels{$line_num} = {'chid'=>$chid, 'name'=>$chname, 'icon'=>$chicon};
  518.     } else {
  519.         warn "$config_file:$line_num: bad line $_\n";
  520.     }
  521. }
  522.  
  523. #***************************************************************************
  524. # Now process the days by getting the main grids.
  525. #***************************************************************************
  526. my @to_get;
  527. warn "No working channels configured, so no listings\n" if not %channels;
  528. my $script_duration = time();
  529.  
  530. # The website stores channel information by hour area for a whole week !
  531. my $ind;
  532. foreach $ind (sort { $a <=> $b } keys %channels) {
  533.     my $chid = $channels{$ind}{chid};
  534.     my $url;
  535.     my $i;
  536.     my $dayoff;
  537.     $writer->write_channel({ id => $channel_prefix.$chid.$channel_postfix, 'display-name' => [[$channels{$ind}{name}]], 'icon' => [{src=>$channels{$ind}{icon}}]});
  538.     if ( $opt_per_days ) {
  539.         for ($i=$opt_offset; $i < $opt_offset+$opt_days; $i++ ) {
  540.             #debug_print( "i: $i\n");
  541.             $dayoff = strftime("%Y-%m-%d", gmtime(time() + 3600 * 24 * $i));
  542.             #debug_print( "dayoff  : " . gmtime(time() + 3600 * 24 * $i) ."\n");
  543.  
  544.             $url = $CHANNEL_GRID_PAGE.$dayoff."&chaine=".$chid;
  545.             push @to_get, [ $url, $chid, $i ];
  546.         }
  547.     } else {
  548.         foreach (@offsets) {
  549.             #$url = $GRID_BY_CHANNEL . "$chid&h=$_";
  550.             push @to_get, [ $url, $chid, $_ ];
  551.         }
  552.     }
  553. }
  554.  
  555.  
  556. my $bar = new XMLTV::ProgressBar('getting listings', scalar @to_get)  if not $opt_quiet;
  557. Date_Init("TZ=UTC");
  558.  
  559. foreach (@to_get) {
  560.     my ($url, $chid, $slot) = @$_;
  561.     process_channel_grid_page($writer, $chid, $url, $slot);
  562.     update $bar if not $opt_quiet;
  563. }
  564.  
  565. ##patch: tigerlol: correction des chevauchements d'horaire
  566. if ( !$opt_noautocorrect ) {
  567.     if ( $progexist ) {
  568.         # Ecriture du programme restant en memoire (au cas ou)
  569.         if ( !$results{$prevprog{start}.$chid} ) {
  570.             #print STDERR "!!!Ecriture du dernier programme sauvegarde: " . $prevtitle . "(" . $prevprog{channel} . ")\n";
  571.             $results{$prevprog{start}.$chid} = "1";
  572.             $writer->write_programme(\%prevprog);
  573.         }
  574.         $progexist = 0;
  575.     }
  576. }
  577. ##/patch
  578.  
  579. $writer->end();
  580. $bar->finish() if not $opt_quiet;
  581.  
  582. # Print the duration
  583. $script_duration = time() - $script_duration;
  584. print STDERR "Grabber process finished in " . $script_duration . " seconds.\n" if not $opt_quiet;
  585.  
  586. #***************************************************************************
  587. # Specific functions for grabbing information
  588. #***************************************************************************
  589. # Build the filename used to stored channels configured manually
  590. sub build_other_channel_filename() {
  591.     # Get the file name/path for OTHERCHANNELS
  592.     my $home = $ENV{HOME};
  593.     $home = '.' if not defined $home;
  594.     my $conf_dir = "$home/.xmltv";
  595.     (-d $conf_dir) or mkdir($conf_dir, 0777)
  596.     or die "cannot mkdir $conf_dir: $!";
  597.     return "$conf_dir/OTHERCHANNELS";
  598. }
  599.  
  600. # Return the tables of the channels built manally
  601. sub return_other_channels( ) {
  602.  
  603.     my $morechannels_file = build_other_channel_filename();
  604.  
  605.     my @morechannels_lines;
  606.     if (-e $morechannels_file && ((-s $morechannels_file)>0) ) {
  607.         @morechannels_lines = XMLTV::Config_file::read_lines($morechannels_file);
  608.     }
  609.     my %morechannels;
  610.     my ($chid, $chname, $chicon);
  611.     my $line_num = 0;
  612.  
  613.     # Build the table and display
  614.     foreach (@morechannels_lines) {
  615.         next if not defined;
  616.  
  617.         # Here we store the Channel name with the ID in the config file, as the XMLTV id = Website ID
  618.         if (/^channel:?\s+(\S+)\s+([^\#]+);([^\#]+)/) {
  619.             $chid = $1;
  620.             $chname = $2;
  621.             $chicon = $3;
  622.             $chname =~ s/\s*$//;
  623.             $morechannels{$chid} = {'name'=>$chname, 'icon'=>$chicon};
  624.         }
  625.         $line_num++;
  626.     }
  627.     return %morechannels;
  628. }
  629.  
  630. # Return the link to the icon. Parameter : channel id
  631. sub get_more_channel_icon( $ ) {
  632.     my $chid = shift;
  633.     my $today = strftime("%Y-%m-%d", localtime());
  634.     my $url;# = $CHECK_CHANNEL_URL.$chid.'/telepoche/soiree/'.$today;
  635.     print $chid;
  636.     # Get the current page
  637.     my $t = get_nice_tree($url);
  638.  
  639.     debug_print( "URL  : " . $url ."\n");
  640.     # Set by default an EMPTY logo
  641.     my $chicon = "EMPTY";
  642.  
  643.     foreach my $cellTree ( $t->look_down( "_tag", "img") ) {
  644.         my $chiconsrc = $cellTree->attr('src');
  645.         if ( $chiconsrc =~ /\/medias\/chaines\/(.*)/ ) {
  646.             $chicon = "http://telepoche.guidetele.com/medias/chaines/".$1;
  647.         }
  648.     }
  649.     $t->delete(); undef $t;
  650.     return $chicon;
  651. }
  652.  
  653. #Get the channel from a grid id, including OTHERCHANNELS mode
  654. sub get_channels( ) {
  655.     my %channels;
  656.  
  657.     # Get the current page
  658.     my $page = get_page($CHANNEL_GRID);
  659.  
  660.     debug_print( "URL  : " . $CHANNEL_GRID ."\n");
  661.     #debug_print($page);
  662.     my @lines = split(/:\$\$\$:/,Encode::from_to($page, "windows-1252", "UTF8"));
  663.     my $chicon = "";
  664.     foreach my $line ( @lines ) {
  665.         my ($chid,$chname) = split (/\$\$\$/,$line);
  666.         debug_print "Found channel : $chid - " . $chname . "\n";
  667.         my $chicon="http://localhost/logos/logo" . $chid . "gif";
  668.         $channels{$chid} = {'name' =>  $chname, 'icon' => $chicon };
  669.     }
  670.  
  671.     undef $page;
  672.     return %channels;
  673. }
  674.  
  675.  
  676. sub process_channel_grid_page( $$$$ ) {
  677.     my ($writer, $chid, $url, $slot) = @_;
  678.  
  679.     my $page = get_page($url);
  680.     debug_print("Getting URL : ".$url."\n");
  681.     #print "Getting URL : ".$url."\n";
  682.     my @lines = split(/:\$\$\$:/,$page);
  683.  
  684.     my ($chname, $title, $starthour, $endhour, $genre, $description, $specialfield, $age, $field1, $stars, $critic, $date, $field4, $day, $year, $mount, $showview);
  685.  
  686.     foreach my $line ( @lines ) {
  687.  
  688.     Encode::from_to($line, "windows-1252", "UTF8");
  689.  
  690.  
  691.     if($opt_verytv) {
  692.         ($chid, $chname, $title, $starthour, $endhour,
  693.         $genre, $description, $specialfield, $date,
  694.         $age, $stars, $showview) = split(/\$\$\$/,$line);
  695.         ($year,$mount,$day) = split(/-/,$date);
  696.         $age=0;
  697.     } else {
  698.         ($chid, $chname, $title, $starthour, $endhour,
  699.         $genre, $description, $specialfield,
  700.         $age, $field1, $stars, $critic, $date, $field4) = split(/\$\$\$/,$line);
  701.         ($day,$mount,$year) = split(/\//,$date);
  702.     }
  703.  
  704.     debug_print("date:".$date."\n");
  705.  
  706.     $date=$year.$mount.$day;
  707.     debug_print($title." - ".$starthour." - ".$endhour."\n");
  708.     debug_print("description:".$description."\n");
  709.     debug_print("genre:".$genre."\n");
  710.     debug_print("specalfield: ".$specialfield."\n");
  711.  
  712.     my ($shh,$shm,$shs) = split(/:/,$starthour);
  713.     my $imgurl= $CHANNEL_ICON_PAGE.$year.'-'.$mount.'-'.$day.'_'.$chid.'_'.$shh.':'.$shm.'.jpg';
  714.  
  715.     $starthour =~ s/://g;
  716.     $endhour =~ s/://g;
  717.  
  718.     my (@specials)=split(/\n/,$specialfield);
  719.  
  720.     my $start = $date.$starthour."";
  721.     my $stop  = $date.$endhour."";
  722.     debug_print($start.">".$stop."\n");
  723.  
  724.     if ( $stop < $start ) {
  725.         $stop  = &UnixDate(&DateCalc($stop, "+1 day"), "%Y%m%d%H%M%S");
  726.         die 'could not add one day to stop time' if not $stop;
  727.         debug_print("One day added to end of last show.\n");
  728.     }
  729.  
  730.     $start = utc_offset( $start, "+0100");
  731.     $stop  = utc_offset( $stop , "+0100");
  732.     my %prog = (channel  => $channel_prefix.$chid.$channel_postfix,
  733.                     title    => [ [ $title ] ],             # lang unknown
  734.                     start    => $start,
  735.                     stop     => $stop
  736.                     );
  737.     debug_print($start.">".$stop."\n");
  738.  
  739.     my $subgenre;
  740.     my $episode;
  741.     my $season;
  742.     my $epstring;
  743.     my $rating2;
  744.     $episode = "-1";
  745.     $season = "-1";
  746.     foreach my $special (@specials) {
  747.         if ($special =~ m/Durée ; ([0-9]+) min/) {
  748.             $prog{length} = $1;
  749.         } elsif ($special =~ /Episode : /) {
  750.             debug_print("Episode:".$special."\n");
  751.             $description = $special." - ".$description;
  752.             $special =~ s/Episode : //i;
  753.             $episode = $special;
  754.         } elsif ($special =~ /Saison : /) {
  755.             debug_print("Saison:".$special."\n");
  756.             $description = $special." - ".$description;
  757.             $special =~ s/Saison : //i;
  758.             $season = $special;
  759.         } elsif ($special =~ s/Sous-titre : //i) {  # Attention à l'ordre avec le elsif suivant
  760.             debug_print("Sous-titre:".$special."\n");
  761.             $prog{'sub-title'} = [ [ $special ] ];
  762.         } elsif ($special =~ m/Sous-titr/i) {  # présence de sous-titrage teletext
  763.             debug_print("Sous-titré:".$special."\n");
  764.             $prog{subtitles} = [ { type => 'teletext', language => ['fr'] } ]
  765.         } elsif ($special =~ m/VOST/i) {   # présence de sous-titrage dans l'image'
  766.             debug_print("Sous-titré:".$special."\n");
  767.             $prog{subtitles} = [ { type => 'onscreen', language => ['fr'] } ]
  768.         } elsif ($special =~ s/Sc.*nariste//i || $special =~ s/Sc.*nario//i) {
  769.             debug_print("Auteurs:".$special."\n");
  770.             my @writers = split(/, /,$special);
  771.             foreach my $auteur (@writers) {
  772.                 push @{$prog{credits}{writer}}, $auteur;
  773.             }
  774.         } elsif ($special =~ s/Acteurs : //i) {
  775.             debug_print("Acteurs:".$special."\n");
  776.             my @acteurs = split(/, /,$special);
  777.             foreach my $acteur (@acteurs) {
  778.                 push @{$prog{credits}{actor}}, $acteur;
  779.             }
  780.        } elsif ($special =~ s/R.alisateur : //i) {
  781.             push @{$prog{credits}{director}}, $special;
  782.       } elsif ($special =~ s/Pr.*sentateur : //i) {
  783.             my @presenters = split(/, /,$special);
  784.             foreach my $presenter (@presenters) {
  785.                 push @{$prog{credits}{presenter}}, $presenter ;
  786.             }
  787.         } elsif ($special =~ s/Invit.*s : //i) {
  788.             my @guests = split(/, /,$special);
  789.             foreach my $guest (@guests) {
  790.                 push @{$prog{credits}{guest}}, $guest ;
  791.             }
  792.         } elsif ($special =~ s/Musique : //i) {
  793.             my @musics = split(/, /,$special);
  794.             foreach my $music (@musics) {
  795. # il faut XMLTV >= 0.5.58 pour que ce champ soit reconnu
  796. # sinon ça genere un warning mais le fichier xml est quand meme ecrit.
  797.                 push @{$prog{credits}{composer}}, $music ;
  798.             }
  799.         } elsif ($special =~ m/Showview : ([0-9]+)/) {
  800.             $prog{showview} = $1;
  801.         } elsif ($special =~ s/Ann.e : //i) {
  802.             $prog{'date'} = $special;
  803.         } elsif ($special =~ /St.r.o/) {
  804.             $prog{'audio'}{stereo} = "stereo";
  805.         } elsif ($special =~ m/Dolby digital/) {
  806.             $prog{'audio'}{stereo} = "digital";
  807.         } elsif ($special =~ m/Dolby 5.1/) {
  808.             $prog{'audio'}{stereo} = "surround";
  809.         } elsif ($special =~ m/Dolby/) {
  810.             $prog{'audio'}{stereo} = "dolby";
  811.         } elsif ($special =~ m/VM/) {
  812.             $prog{'audio'}{stereo} = "bilingual";
  813.         } elsif ($special =~ m/Pays : (.*)/) {
  814.             $prog{country} = $1;
  815.        } elsif ($special =~ s/Genre : //i) {
  816.             $subgenre = $special;
  817.         } elsif ($special =~ m/Titre original : (.*)/) {
  818.             $prog{title_orig} = $1;
  819.         } elsif ( ($special =~ m/In.*dit/) || ($special =~ m/Premi.*re diffusion/) ) {
  820.             $prog{premiere} = [];
  821.         } elsif ($special =~ m/Rediffusion/) {
  822.             $prog{'previously-shown'} = {};
  823.         } elsif ($special =~ m/En 16:9/) {
  824.             $prog{video}{aspect} = "16:9";
  825.         } elsif ($special =~ m/En 4:3/) {
  826.             $prog{video}{aspect} = "4:3";
  827.         } elsif ($special =~ m/HD/) {
  828.             $prog{video}{quality} = "HDTV";
  829.         } elsif ($special =~ m/Tous publics/) {
  830.             $rating2 = 1;
  831.         }
  832.  
  833.     }
  834.  
  835.     if(($episode ne "-1") || ($season ne "-1")) {
  836.         if ($season ne "-1") {
  837.         $epstring = ($season - 1);
  838.         } else {
  839.         $epstring = 0;
  840.         }
  841.         $epstring .= ".";
  842.         if ($episode ne "-1") {
  843.             if($episode =~ /(\d+)\/(\d+)/) {
  844.                 if($2) {
  845.                     $epstring .= ($1-1)."/".$2;
  846.                 } else {
  847.                 $epstring .= ($1-1);
  848.                 }
  849.             }
  850.         }
  851.         $epstring .= ".";
  852.         push @{$prog{'episode-num'}}, [$epstring,"xmltv_ns"];
  853.     }
  854.  
  855.     push @{$prog{icon}}, {src => $imgurl};
  856.  
  857.     if (defined $subgenre) {
  858.         $prog{category} = [ [ xmlencoding(lc($genre)), $LANG ], [ xmlencoding(lc($subgenre)), $LANG ] ];
  859.     }
  860.  
  861.  
  862.     if ( $description ne "" ) {
  863.         if($critic) {
  864.             $description = $description." --  Critique : ".$critic;
  865.         }
  866.         push @{$prog{desc}}, [$description, $LANG ];
  867.     }
  868.     #$prog{showview}=$showview;
  869.  
  870.  
  871.     my $icon;
  872.     if ($age > 0 && !$rating2) {
  873.         if ($age <= 10) {
  874.             $icon = 'http://www.csa.fr/picts/visuels/picto_cat2.gif';
  875.         } elsif ($age <= 12) {
  876.             $icon = 'http://www.csa.fr/picts/visuels/picto_cat3.gif';
  877.         } elsif ($age <= 16)  {
  878.             $icon = 'http://www.csa.fr/picts/visuels/picto_cat4.gif';
  879.         } else {
  880.             $icon = 'http://www.csa.fr/picts/visuels/picto_cat5.gif';
  881.         }
  882.         $age = -$age;
  883. #       $prog{rating} = [[ $age ]];
  884. #       push @{$prog->{rating}}, [ $rating, "CSA", [ {src => $icon} ] ];
  885.         if ($icon) {
  886.             push @{$prog{rating}}, [ $age, "CSA", [ {src => $icon}] ];
  887.         } else {
  888.             push @{$prog{rating}}, [ $age, "CSA", [] ];
  889.         }
  890.     }
  891.     else {
  892.         push @{$prog{rating}}, [ "Tout public", "CSA", [] ];
  893.  
  894.     }
  895.  
  896.     # étoiles
  897.     $prog{'star-rating'} = [$stars] if ($stars);
  898.  
  899.  
  900.     $writer->write_programme(\%prog);
  901.  
  902.  }
  903.  undef $page;
  904. }
  905.  
  906. # use an integrated sub to set a specific user agent
  907. sub get_page( $ ) {
  908.     my $url = shift;
  909.  
  910.     if (defined $last_get_time) {
  911.         # A page has already been retrieved recently.  See if we need
  912.         # to sleep for a while before getting the next page - being
  913.         # nice to the server.
  914.  
  915.         my $next_get_time = $last_get_time + (rand $Delay);
  916.         my $sleep_time = $next_get_time - time();
  917.         sleep $sleep_time if $sleep_time > 0;
  918.     }
  919.  
  920.     my $r = $ua->get($url);
  921.  
  922.     # Then start the delay from this time on the next fetch - so we
  923.     # make the gap _between_ requests rather than from the start of
  924.     # one request to the start of the next.  This punishes modem users
  925.     # whose individual requests take longer, but it also punishes
  926.     # downloads that take a long time for other reasons (large file,
  927.     # slow server) so it's about right.
  928.  
  929.     $last_get_time = time();
  930.  
  931.     if ($r->is_error) {
  932.         # At the moment download failures seem rare, so the script dies if
  933.         # any page cannot be fetched.  We could later change this routine
  934.         # to return undef on failure.  But dying here makes sure that a
  935.         # failed page fetch doesn't get stored in XMLTV::Memoize's cache.
  936.         #
  937.         die "could not fetch $url, error: " . $r->status_line . ", aborting\n" if $FailOnError;
  938.         $errors{$url} = $r->status_line;
  939.         return undef;
  940.     } else {
  941.          print STDERR "Récupération de ".$url."\n";
  942.         return $r->content;
  943.     }
  944.  
  945. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement