Advertisement
Guest User

tv_grab_fr_telerama_pg

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