Advertisement
Guest User

tv_grab_fr_telerama_pg-1.14

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