Advertisement
Guest User

tv_grab_fr_telerama_pg-1.17

a guest
Mar 31st, 2012
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 35.48 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. 1.15 Correction d'un oubli dans le traitement des numéros d'épisode, si le nombre d'épisodes
  152.      était absent, le numéro n'était pas récupéré.
  153.      Ajout du traitement du nombre de saison.
  154. 1.16 Correction du format du star-rating.
  155.       Modification regexp de récupération de l'année qui ne marchait plus
  156. 1.17 Si un fichier './logo-path.txt' existe, il est utilisé pour déterminer
  157.      le chemin vers les logos des chaines lorsqu'on utilise l'option --configure.
  158.      La version fournie est une version corrigée de lookup_tv_grab_fr_telerama.tx,
  159.      il pointe donc vers les logos de lyngsat. Il utilise la même syntaxe mais le
  160.      champ chid n'est pas utilisé. De cette façon le fichier de conf et le fichier
  161.      xml généré pointe directement vers les bons logos.
  162. =cut
  163.  
  164.  
  165. use XMLTV::Usage <<END
  166. $0: get French television listings in XMLTV format
  167. To configure AUTRES CHAINES list: $0 --configure-more-channels
  168. To configure: $0 --configure [--config-file FILE]
  169. To grab listings: tv_grab_fr [--config-file FILE] [--output FILE] [--days N]
  170.     [--offset N] [--quiet] [--perdays] [--perweeks]
  171.     [--ch_prefix prefix] [--ch_postfix postfix] [--delay N]
  172. prefix, postfix : strings, "" for null string
  173. To show capabilities : $0 --capabilities
  174. To show version      : $0 --version
  175. To view help         : $0 --help
  176. END
  177.   ;
  178.  
  179. use warnings;
  180. use strict;
  181. use XMLTV::Version '$Id: tv_grab_fr_telerama_pg,v 1.17 2012/03/31 09:06:00 patrick-g Exp $ ';
  182. #use XMLTV::Capabilities qw/baseline manualconfig cache/;
  183. use XMLTV::Capabilities qw/baseline manualconfig/;
  184. use XMLTV::Description 'France (telerama)';
  185. use Getopt::Long;
  186. use HTML::Entities; # parse entities
  187. use IO::File;
  188. use URI;
  189. use Date::Manip;
  190. use XMLTV;
  191. use XMLTV::Ask;
  192. use XMLTV::ProgressBar;
  193. use XMLTV::Mode;
  194. use XMLTV::Config_file;
  195. use XMLTV::DST;
  196. use LWP;
  197. use XMLTV::Get_nice;
  198. use XMLTV::Memoize;
  199. use File::Temp;
  200. use LWP::Simple;
  201. use LWP::UserAgent;
  202. use POSIX;
  203. use Encode;
  204.  
  205. #***************************************************************************
  206. # Main declarations
  207. #***************************************************************************
  208. my $LANG = "fr";
  209. my $VERSION   = "20120331-01";
  210.  
  211. # FIXME: Temporary avoid XML warnings (to be investigated)
  212. #no warnings;
  213.  
  214. # Grid id defined by the website according to channel types (needed to build the URL)
  215. # my %GridType = (  "ALL" => "all");
  216.  
  217. # Slot of hours according to the website (needed to build the URL)
  218. my @offsets = (2, 3, 4, 5, 6, 7);
  219. # Slot of days for day per day grabbing
  220. # my @days = (2, 3, 4, 5, 6, 7, 8, 9);
  221.  
  222. my $Delay = 2; # in seconds
  223. my $FailOnError = 1; # Fail on fetch error
  224.  
  225. my %errors = ();
  226. my $last_get_time;
  227.  
  228. # my $progexist;
  229. # my %prevprog;
  230. # my $prevtitle;
  231. # my $prevstart;
  232. # my $prevstop;
  233.  
  234. my $channel_postfix = ".telerama.fr";
  235. my $channel_prefix = "C";
  236.  
  237. # Set this to 1 of you want to print command line
  238. my $DEBUG_CMD = 0;
  239.  
  240. #***************************************************************************
  241. # Global variables allocation according to options
  242. #***************************************************************************
  243. XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');
  244.  
  245. ##patch: tigerlol: correction des chevauchements d'horaire
  246. 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, $opt_logo_path );
  247. ##/patch
  248.  
  249. # debug
  250. if ($DEBUG_CMD) { print $0." | ".join(" | ", @ARGV), "\n\n"; }
  251.  
  252. $opt_per_weeks = 0;
  253. $opt_quiet  = 0;
  254. # The website is able to store at least 11 days from now
  255. my $default_opt_days = 11;
  256. $opt_output = '-'; # standard output
  257. GetOptions('days=i' => \$opt_days,
  258.      'help'   => \$opt_help,
  259.      'output=s'  => \$opt_output,
  260.      'offset=i'  => \$opt_offset,
  261.      'quiet'     => \$opt_quiet,
  262.      'configure' => \$opt_configure,
  263.      'config-file=s' => \$opt_config_file,
  264.      'gui:s'     => \$opt_gui,
  265.      'list-channels' => \$opt_list_channels,
  266.      'perdays' => \$opt_per_days,
  267.      'perweeks' => \$opt_per_weeks,
  268.      'ch_prefix=s'  => \$channel_prefix,
  269.      'ch_postfix=s'  => \$channel_postfix,
  270. ##Gestion des channels non declares dans les listes "officielles"
  271.      'configure-more-channels' => \$opt_morechannels,
  272.      'delay=i' => \$Delay
  273.     )
  274.   or usage(0);
  275.  
  276. my $CHANNEL_GRID;
  277. my $CHANNEL_GRID_PAGE;
  278. my $CHANNEL_ICON_PAGE;
  279. my $ROOT_URL;
  280.  
  281.  
  282. my $ua = LWP::UserAgent->new;
  283.  
  284.     $CHANNEL_GRID = 'http://guidetv-iphone.telerama.fr/verytv/procedures/ListeChaines.php';
  285.     $CHANNEL_GRID_PAGE = "http://guidetv-iphone.telerama.fr/verytv/procedures/LitProgrammes1Chaine.php?date=";
  286.     $CHANNEL_ICON_PAGE = "http://guidetv-iphone.telerama.fr/verytv/procedures/images/";
  287.     $ROOT_URL  = 'http://guidetv-iphone.telerama.fr';
  288.     $ua->agent("Telerama/1.2 CFNetwork/459 Darwin/10.0.0d3");
  289.  
  290. $ua->env_proxy;
  291.  
  292.  
  293. #***************************************************************************
  294. # Options processing, warnings, checks and default parameters
  295. #***************************************************************************
  296. die 'Number of days must not be negative'  if (defined $opt_days && $opt_days < 0);
  297. die 'Cannot get more than one day before current day' if (defined $opt_offset && $opt_offset < -1);
  298. usage(1) if $opt_help;
  299.  
  300. XMLTV::Ask::init($opt_gui);
  301.  
  302. # The options can be used, but we default them if not set.
  303. $opt_offset = 0 if not defined $opt_offset;
  304. $opt_days = $default_opt_days if not defined $opt_days;
  305.  
  306. # Force the per days option in all cases
  307. if ( $opt_per_weeks == 0 ) {
  308.   $opt_per_days = 1;
  309. }
  310.  
  311. if ( (($opt_offset + $opt_days) > $default_opt_days) or ($opt_offset > $default_opt_days) ) {
  312.     $opt_days = $default_opt_days - $opt_offset;
  313.     if ($opt_days < 0) {
  314.         $opt_offset = 0;
  315.         $opt_days = $default_opt_days;
  316.     }
  317.     say <<END
  318. The website does not handle more than $default_opt_days days.
  319. So the grabber is now configure with --offset $opt_offset --days $opt_days
  320. END
  321. ;
  322. }
  323.  
  324. #***************************************************************************
  325. # Last init before doing real work
  326. #***************************************************************************
  327. my %results;
  328. my $lastdaysoffset = $opt_offset + $opt_days - 1;
  329. my $checkDummySlot = 0;
  330. my @data;
  331. my $chan;
  332. my @name_url;
  333. my %icon_map;
  334.  
  335. # Now detects if we are in configure mode
  336. my $mode = XMLTV::Mode::mode('grab', # default
  337.                         $opt_configure => 'configure',
  338.                         $opt_list_channels => 'list-channels',
  339.                         $opt_morechannels  => 'confmorechannels' );
  340.  
  341. # File that stores which channels to download.
  342. my $config_file = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_fr_telerama', $opt_quiet);
  343.  
  344. # get channel logo path in conf file
  345. #***********************************
  346. $opt_logo_path = "false";
  347.  
  348. if (-e "./logo-path.txt")
  349. {
  350.    $opt_logo_path = "true";
  351.    open(FILE, "./logo-path.txt") or die("Unable to open file");
  352.                                     @data = <FILE>;
  353.                                     close(FILE);
  354.  
  355.    foreach $chan (@data)
  356.    {
  357. #      print STDERR "Ligne Logo : " . $chan . "\n";
  358.       @name_url = split('\|', $chan);
  359. #      $xmltvid_map{$name_url[0]} = $name_url[1];
  360.       $icon_map{$name_url[0]} = $name_url[2];
  361. #      print $name_url[0]."|".$name_url[2]."\n";
  362.    }
  363. }
  364.  
  365.  
  366.  
  367.  
  368.  
  369. #***************************************************************************
  370. # Sub sections
  371. #***************************************************************************
  372. sub get_channels( );
  373. sub return_other_channels( );
  374. sub build_other_channel_filename();
  375. sub get_more_channel_icon( $ );
  376. sub process_channel_grid_page( $$$$ );
  377. sub debug_print( @ );
  378. sub get_page( $ );
  379.  
  380. # Set this to 1 of you debug strings
  381. my $DEBUG_FR = 0;
  382. # Internal debug functions
  383. sub debug_print( @ ) {
  384.   if ($DEBUG_FR) { print @_; }
  385. }
  386.  
  387. sub xmlencoding {
  388.     # encode for xml
  389.     $_[0] =~ s/</&lt;/g;
  390.     $_[0] =~ s/>/&gt;/g;
  391.     $_[0] =~ s/&/\%26/g;
  392.     return $_[0];
  393. }
  394.  
  395.     #debug_print( "my Mode  : " . $mode ."\n");
  396. #***************************************************************************
  397. # Configure mode
  398. #***************************************************************************
  399. if ($mode eq 'configure') {
  400.     XMLTV::Config_file::check_no_overwrite($config_file);
  401.     open(CONF, ">$config_file") or die "Cannot write to $config_file: $!";
  402.  
  403.     #my $bar = new XMLTV::ProgressBar('getting channel lists', scalar grep { $_ } @gtwant) if not $opt_quiet;
  404.     my %channels_for;
  405.     my %channels = get_channels();
  406.     die 'No channels could be found' if not %channels;
  407.  
  408.  
  409.     my %asked;
  410.  
  411.     # Ask about each channel (unless already asked).
  412.     my @chs = grep { not $asked{$_}++ } sort keys %channels;
  413.     my @names = map { $channels{$_}{name} } @chs;
  414.     my @qs = map { "add channel $_?" } @names;
  415.     my @want = ask_many_boolean(1, @qs);
  416.     foreach (@chs) {
  417.         my $w = shift @want;
  418.         warn("cannot read input, stopping channel questions"), last if not defined $w;
  419.         # Print a config line, but comment it out if channel not wanted.
  420.         print CONF '#' if not $w;
  421.         print CONF "channel $_ $channels{$_}{name};$channels{$_}{icon}\n";
  422.     }
  423.  
  424.     close CONF or warn "cannot close $config_file: $!";
  425.     say("Finished configuration.");
  426.     exit();
  427. }
  428.  
  429. #***************************************************************************
  430. # "Configure more channels" mode
  431. #***************************************************************************
  432. sub display_otherchannels_list(\%) {
  433.     my %chlist = %{(shift)};
  434.  
  435.     say ">>>>>> Current list <<<<<<";
  436.     foreach my $chid (keys %chlist) {
  437.         say "Channel ID: ". $chid." - Name: " . $chlist{$chid}{name} .
  438.             " - Icon: ". $chlist{$chid}{icon};
  439.     }
  440.     say ">>>>>> List end <<<<<<";
  441. }
  442.  
  443. if ($mode eq 'confmorechannels') {
  444.     # Display info message, pointing to the forum thread
  445.     my $input_file_notempty = 0;
  446.     my %morechannels = return_other_channels();
  447.     display_otherchannels_list(%morechannels);
  448.     if ( (scalar keys  %morechannels) > 0 ) {
  449.         $input_file_notempty= 1;
  450.     }
  451.     my $choice = "";
  452.     my ($chid, $chname, $chicon);
  453.  
  454.     while ( !($choice eq "exit")) {
  455.         $choice = ask_choice( "Select command to configure OTHERCHANNELS", "add", ("add", "remove", "view list", "save&exit", "exit") );
  456.         my $exit = 0;
  457.         if ($choice eq "add" ) {
  458.             while ($exit == 0) {
  459.                 $chid = ask('Enter channel ID : ');
  460.                 $chname = ask('Enter channel name : ');
  461.                 if ( !($chid =~ /^[0-9]*$/) ) {
  462.                     say ("Enter a numeric value for channel id");
  463.                 } else {
  464.                     if ( $chname eq "" ) {
  465.                         say ("Enter a string for the name of the channel");
  466.                     } else {
  467.                         $exit = 1;
  468.                     }
  469.                 }
  470.             }
  471.             say("Testing channel $chid - $chname ...");
  472.             my $chicon = get_more_channel_icon( $chid );
  473.             $morechannels{$chid} = {'name'=>$chname, 'icon'=>$chicon};
  474.         }
  475.         if ($choice eq "remove" ) {
  476.             display_otherchannels_list(%morechannels);
  477.             my $chid = ask('Enter the channel id to remove it (see list above): ');
  478.             if ( defined $morechannels{$chid} ) {
  479.                 $chname = $morechannels{$chid}{name};
  480.                 delete $morechannels{$chid};
  481.                 say ("Channel $chname removed");
  482.             } else {
  483.                 say("Channel $chid does not exist in the list");
  484.             }
  485.         }
  486.         if ($choice eq "view list" ) {
  487.             display_otherchannels_list(%morechannels);
  488.         }
  489.         if ($choice eq "save&exit") {
  490.             my $morechannels_file = build_other_channel_filename();
  491.             # Then write the file
  492.             if ( (scalar keys  %morechannels) > 0 ) {
  493.                 open(CONFMORE, ">$morechannels_file") or die "Cannot write to $morechannels_file: $!";
  494.                 foreach $chid (keys %morechannels) {
  495.                     if (!( $morechannels{$chid}{name} eq 'DELETED' )) {
  496.                         print CONFMORE "channel $chid $morechannels{$chid}{name};$morechannels{$chid}{icon}\n";
  497.                     }
  498.                 }
  499.                 close CONFMORE or warn "cannot close $morechannels_file: $!";
  500.                 display_otherchannels_list(%morechannels);
  501.                 say ('Channel list saved. Launch now a --configure mode to add them into the legacy config');
  502.             } else {
  503.                 unlink ($morechannels_file);
  504.                 say ('No channels to be configure, file deleted.');
  505.             }
  506.             $choice = "exit";
  507.         }
  508.     }
  509.     say("Finished configuration for OTHERCHANNELS.");
  510.     exit();
  511. }
  512.  
  513. #***************************************************************************
  514. # Check mode checking and get configuration file
  515. #***************************************************************************
  516. die if $mode ne 'grab' and $mode ne 'list-channels';
  517. #   debug_print( "my Mode  : " . $mode ."\n");
  518.  
  519. my @config_lines;
  520. if ($mode eq 'grab') {
  521.     @config_lines = XMLTV::Config_file::read_lines($config_file);
  522. }
  523.  
  524. #***************************************************************************
  525. # Prepare the XMLTV writer object
  526. #***************************************************************************
  527. my %w_args;
  528. if (defined $opt_output) {
  529.     my $fh = new IO::File(">$opt_output");
  530.     die "cannot write to $opt_output: $!" if not defined $fh;
  531.     $w_args{OUTPUT} = $fh;
  532. }
  533.  
  534. $w_args{encoding} = 'UTF-8';
  535. #$w_args{days} = $opt_days;
  536. #$w_args{offset} = $opt_offset;
  537. #$w_args{cutoff} = "000000";
  538.  
  539. my $writer = new XMLTV::Writer(%w_args);
  540. $writer->start
  541.   ({ 'source-info-url'   => $ROOT_URL,
  542.      'source-data-url'   => $ROOT_URL,
  543.      'generator-info-name' => 'XMLTV',
  544.      'generator-info-url'  => 'http://mythtv-fr.org/',
  545.    });
  546.  
  547. #***************************************************************************
  548. # List channels only case
  549. #***************************************************************************
  550. #   debug_print( "my Mode  : " . $mode ."\n");
  551. if ($mode eq 'list-channels') {
  552.     # Get a list of available channels, according to the grid type
  553. #   my @gts = sort keys %GridType;
  554. #   my @gtnames  = map { $GridType{$_} } @gts;
  555. #   my @gtqs = map { "List channels for grid : $_?" } @gts;
  556. #   my @gtwant = ask_many_boolean(1, @gtqs);
  557.  
  558.     my %seen;
  559. #   debug_print( "Entering list-channels\n");
  560. #   foreach (@gts) {
  561. #       debug_print( "In foreach\n");
  562. #       my $gtw = shift @gtwant;
  563. #       my $gtname = shift @gtnames;
  564. #       if ($gtw) {
  565. #           say  "Now getting grid : $_ \n";
  566.             my %channels = get_channels( );
  567.             die 'no channels could be found' if (scalar(keys(%channels)) == 0);
  568.             foreach my $ch_did (sort(keys %channels)) {
  569.                 my $ch_xid = $channel_prefix.$ch_did.$channel_postfix;
  570.                 $writer->write_channel({ id => $ch_xid,
  571.                                          'display-name' => [ [ $channels{$ch_did}{name} ] ],
  572. #                                        'icon' => [{src=>$ROOT_URL.$channels{$ch_did}{icon}}] })
  573.                                          'icon' => [{src=> $channels{$ch_did}{icon} }] })
  574.                 unless $seen{$ch_xid}++;
  575.             }
  576. #      }
  577. #    }
  578.      $writer->end();
  579.      exit();
  580. }
  581.  
  582. #***************************************************************************
  583. # Now the real grabbing work
  584. #***************************************************************************
  585. die if $mode ne 'grab';
  586.  
  587. #***************************************************************************
  588. # Build the working list of channel name/channel id
  589. #***************************************************************************
  590. my (%channels, $chicon, $chid, $chname);
  591. my $line_num = 1;
  592. foreach (@config_lines) {
  593.     ++ $line_num;
  594.     next if not defined;
  595.  
  596.     # Here we store the Channel name with the ID in the config file, as the XMLTV id = Website ID
  597.     if (/^channel:?\s+(\S+)\s+([^\#]+);([^\#]+)/) {
  598.         $chid = $1;
  599.         $chname = $2;
  600.         $chicon = $3;
  601.         $chname =~ s/\s*$//;
  602.         $channels{$line_num} = {'chid'=>$chid, 'name'=>$chname, 'icon'=>$chicon};
  603.     } else {
  604.         warn "$config_file:$line_num: bad line $_\n";
  605.     }
  606. }
  607.  
  608. #***************************************************************************
  609. # Now process the days by getting the main grids.
  610. #***************************************************************************
  611. my @to_get;
  612. warn "No working channels configured, so no listings\n" if not %channels;
  613. my $script_duration = time();
  614.  
  615. # The website stores channel information by hour area for a whole week !
  616. my $ind;
  617. foreach $ind (sort { $a <=> $b } keys %channels) {
  618.     my $chid = $channels{$ind}{chid};
  619.     my $url;
  620.     my $i;
  621.     my $dayoff;
  622.     $writer->write_channel({ id => $channel_prefix.$chid.$channel_postfix, 'display-name' => [[$channels{$ind}{name}]], 'icon' => [{src=>$channels{$ind}{icon}}]});
  623.     if ( $opt_per_days ) {
  624.         for ($i=$opt_offset; $i < $opt_offset+$opt_days; $i++ ) {
  625.             #debug_print( "i: $i\n");
  626.             $dayoff = strftime("%Y-%m-%d", gmtime(time() + 3600 * 24 * $i));
  627.             #debug_print( "dayoff  : " . gmtime(time() + 3600 * 24 * $i) ."\n");
  628.  
  629.             $url = $CHANNEL_GRID_PAGE.$dayoff."&chaine=".$chid;
  630.             push @to_get, [ $url, $chid, $i ];
  631.         }
  632.     } else {
  633.         foreach (@offsets) {
  634.             #$url = $GRID_BY_CHANNEL . "$chid&h=$_";
  635.             push @to_get, [ $url, $chid, $_ ];
  636.         }
  637.     }
  638. }
  639.  
  640.  
  641. my $bar = new XMLTV::ProgressBar('getting listings', scalar @to_get)  if not $opt_quiet;
  642. Date_Init("TZ=UTC");
  643.  
  644. foreach (@to_get) {
  645.     my ($url, $chid, $slot) = @$_;
  646.     process_channel_grid_page($writer, $chid, $url, $slot);
  647.     update $bar if not $opt_quiet;
  648. }
  649.  
  650. $writer->end();
  651. $bar->finish() if not $opt_quiet;
  652.  
  653. # Print the duration
  654. $script_duration = time() - $script_duration;
  655. print STDERR "Grabber process finished in " . $script_duration . " seconds.\n" if not $opt_quiet;
  656.  
  657. #***************************************************************************
  658. # Specific functions for grabbing information
  659. #***************************************************************************
  660. # Build the filename used to stored channels configured manually
  661. sub build_other_channel_filename() {
  662.     # Get the file name/path for OTHERCHANNELS
  663.     my $home = $ENV{HOME};
  664.     $home = '.' if not defined $home;
  665.     my $conf_dir = "$home/.xmltv";
  666.     (-d $conf_dir) or mkdir($conf_dir, 0777)
  667.     or die "cannot mkdir $conf_dir: $!";
  668.     return "$conf_dir/OTHERCHANNELS";
  669. }
  670.  
  671. # Return the tables of the channels built manally
  672. sub return_other_channels( ) {
  673.  
  674.     my $morechannels_file = build_other_channel_filename();
  675.  
  676.     my @morechannels_lines;
  677.     if (-e $morechannels_file && ((-s $morechannels_file)>0) ) {
  678.         @morechannels_lines = XMLTV::Config_file::read_lines($morechannels_file);
  679.     }
  680.     my %morechannels;
  681.     my ($chid, $chname, $chicon);
  682.     my $line_num = 0;
  683.  
  684.     # Build the table and display
  685.     foreach (@morechannels_lines) {
  686.         next if not defined;
  687.  
  688.         # Here we store the Channel name with the ID in the config file, as the XMLTV id = Website ID
  689.         if (/^channel:?\s+(\S+)\s+([^\#]+);([^\#]+)/) {
  690.             $chid = $1;
  691.             $chname = $2;
  692.             $chicon = $3;
  693.             $chname =~ s/\s*$//;
  694.             $morechannels{$chid} = {'name'=>$chname, 'icon'=>$chicon};
  695.         }
  696.         $line_num++;
  697.     }
  698.     return %morechannels;
  699. }
  700.  
  701. # Return the link to the icon. Parameter : channel id
  702. sub get_more_channel_icon( $ ) {
  703.     my $chid = shift;
  704.     my $today = strftime("%Y-%m-%d", localtime());
  705.     my $url;# = $CHECK_CHANNEL_URL.$chid.'/telepoche/soiree/'.$today;
  706.     print $chid;
  707.     # Get the current page
  708.     my $t = get_nice_tree($url);
  709.  
  710.     debug_print( "URL  : " . $url ."\n");
  711.     # Set by default an EMPTY logo
  712.     my $chicon = "EMPTY";
  713.  
  714.     foreach my $cellTree ( $t->look_down( "_tag", "img") ) {
  715.         my $chiconsrc = $cellTree->attr('src');
  716.         if ( $chiconsrc =~ /\/medias\/chaines\/(.*)/ ) {
  717.             $chicon = "http://telepoche.guidetele.com/medias/chaines/".$1;
  718.         }
  719.     }
  720.     $t->delete(); undef $t;
  721.     return $chicon;
  722. }
  723.  
  724. #Get the channel from a grid id, including OTHERCHANNELS mode
  725. sub get_channels( ) {
  726.     my %channels;
  727.  
  728.     # Get the current page
  729.     my $page = get_page($CHANNEL_GRID);
  730.  
  731.     debug_print( "URL  : " . $CHANNEL_GRID ."\n");
  732. #   debug_print($page);
  733.     my $length = Encode::from_to($page, "windows-1252", "UTF8") ;
  734. #   debug_print "\nLength : " . $length . "\n";
  735.     my @lines = split(/:\$\$\$:/,$page);
  736. #   debug_print "\nFound lines : " . @lines . "\n";
  737.     my $chicon = "";
  738.     foreach my $line ( @lines ) {
  739. #       debug_print "Found line : " . $line . "\n";
  740.         my ($chid,$chname) = split (/\$\$\$/,$line);
  741.         if ( $chname eq "" ) {
  742.             $chname = "???"
  743.         }
  744.         debug_print "Found channel : " . $chid . " - " . $chname . "\n";
  745.  
  746.       if ($opt_logo_path eq "true")
  747.       {
  748.          my $iconloc="";
  749.  
  750.          if ($icon_map{$chname})
  751.          {
  752.             $iconloc=$icon_map{$chname};
  753.             $iconloc =~ s/\s+$//;
  754.             $iconloc =~ s/^\s+//;
  755.             if ($iconloc ne "none")
  756.             {
  757.                $chicon=$iconloc;
  758.             }
  759.             else
  760.             {
  761.    #            print STDERR "Chaine : ".$chname." pas de logo \n";
  762.                $chicon="http://localhost/logos/logo" . $chid . ".gif";
  763.             }
  764.          }
  765.          else
  766.          {
  767.    #         print STDERR "Chaine : ".$chname." inconnue \n";
  768.             $chicon="http://localhost/logos/logo" . $chid . ".gif";
  769.          }
  770.       }
  771.       else
  772.       {
  773. #         print STDERR "Chaine : ".$chname." pas de logo \n";
  774.          $chicon="http://localhost/logos/logo" . $chid . ".gif";
  775.       }
  776.         $channels{$chid} = {'name' =>  $chname, 'icon' => $chicon };
  777. #      print "icon : ".$channels{$chid}{icon}." \n";
  778.     }
  779.  
  780.     undef $page;
  781.     return %channels;
  782. }
  783.  
  784.  
  785. sub process_channel_grid_page( $$$$ ) {
  786.     my ($writer, $chid, $url, $slot) = @_;
  787.  
  788.     my $page = get_page($url);
  789.     debug_print("Getting URL : ".$url."\n");
  790.     #print "Getting URL : ".$url."\n";
  791.     my @lines = split(/:\$\$\$:/,$page);
  792.  
  793.     my ($chname, $title, $starthour, $endhour, $genre, $description, $specialfield, $age, $field1, $stars, $critic, $date, $field4, $day, $year, $mount, $showview);
  794.  
  795.     foreach my $line ( @lines ) {
  796.  
  797.         Encode::from_to($line, "windows-1252", "UTF8");
  798.  
  799.  
  800.         ($chid, $chname, $title, $starthour, $endhour,
  801.         $genre, $description, $specialfield,
  802.         $age, $field1, $stars, $critic, $date, $field4) = split(/\$\$\$/,$line);
  803.         ($day,$mount,$year) = split(/\//,$date);
  804.  
  805.         debug_print("date:".$date."\n");
  806.  
  807.         $date=$year.$mount.$day;
  808.         debug_print($title." - ".$starthour." - ".$endhour."\n");
  809.         debug_print("description:".$description."\n");
  810.         debug_print("genre:".$genre."\n");
  811.         debug_print("specalfield: ".$specialfield."\n");
  812.  
  813.         my ($shh,$shm,$shs) = split(/:/,$starthour);
  814.         my $imgurl= $CHANNEL_ICON_PAGE.$year.'-'.$mount.'-'.$day.'_'.$chid.'_'.$shh.':'.$shm.'.jpg';
  815.  
  816.         $starthour =~ s/://g;
  817.         $endhour =~ s/://g;
  818.  
  819.         my (@specials)=split(/\n/,$specialfield);
  820.  
  821.         my $start = $date.$starthour."";
  822.         my $stop  = $date.$endhour."";
  823.         debug_print($start.">".$stop."\n");
  824.  
  825.         if ( $stop < $start ) {
  826.             $stop  = &UnixDate(&DateCalc($stop, "+1 day"), "%Y%m%d%H%M%S");
  827.             die 'could not add one day to stop time' if not $stop;
  828.             debug_print("One day added to end of last show.\n");
  829.         }
  830.  
  831.         $start = utc_offset( $start, "+0100");
  832.         $stop  = utc_offset( $stop , "+0100");
  833.         my %prog = (channel  => $channel_prefix.$chid.$channel_postfix,
  834.                         title   => [ [ $title ] ],           # lang unknown
  835.                         start   => $start,
  836.                         stop     => $stop
  837.                         );
  838.         debug_print($start.">".$stop."\n");
  839.  
  840.         my $subgenre;
  841.         my $episode;
  842.         my $season;
  843.         my $episode_text;
  844.         my $season_text;
  845.         my $epstring;
  846.         my $rating2;
  847.         $episode = "-1";
  848.         $season = "-1";
  849.         $episode_text = "-1";
  850.         $season_text = "-1";
  851.         foreach my $special (@specials) {
  852.             if ($special =~ m/Durée ; ([0-9]+) min/) {
  853.                 $prog{length} = $1;
  854.             } elsif ($special =~ /Episode : /) {
  855.                 debug_print("Episode:".$special."\n");
  856. #           $description = $special." - ".$description;
  857.                 $episode_text = $special;
  858.                 $special =~ s/Episode : //i;
  859.                 $episode = $special;
  860.             } elsif ($special =~ /Saison : /) {
  861.                 debug_print("Saison:".$special."\n");
  862. #           $description = $special." - ".$description;
  863.                 $season_text = $special;
  864.                 $special =~ s/Saison : //i;
  865.                 $season = $special;
  866.             } elsif ($special =~ s/Sous-titre : //i) {  # Attention à l'ordre avec le elsif suivant
  867.                 debug_print("Sous-titre:".$special."\n");
  868.                 $prog{'sub-title'} = [ [ $special ] ];
  869.             } elsif ($special =~ m/Sous-titr/i) {  # présence de sous-titrage teletext
  870.                 debug_print("Sous-titré:".$special."\n");
  871.                 $prog{subtitles} = [ { type => 'teletext', language => ['fr'] } ]
  872.             } elsif ($special =~ m/VOST/i) {   # présence de sous-titrage dans l'image'
  873.                 debug_print("Sous-titré:".$special."\n");
  874.                 $prog{subtitles} = [ { type => 'onscreen', language => ['fr'] } ]
  875.             } elsif ($special =~ s/Sc.*nariste//i || $special =~ s/Sc.*nario//i) {
  876.                 debug_print("Auteurs:".$special."\n");
  877.                 my @writers = split(/, /,$special);
  878.                 foreach my $auteur (@writers) {
  879.                     push @{$prog{credits}{writer}}, $auteur;
  880.                 }
  881.             } elsif ($special =~ s/Acteurs : //i) {
  882.                 debug_print("Acteurs:".$special."\n");
  883.                 my @acteurs = split(/, /,$special);
  884.                 foreach my $acteur (@acteurs) {
  885.                     push @{$prog{credits}{actor}}, $acteur;
  886.                 }
  887.         } elsif ($special =~ s/R.alisateur : //i) {
  888.                 push @{$prog{credits}{director}}, $special;
  889.         } elsif ($special =~ s/Pr.*sentateur : //i) {
  890.                 my @presenters = split(/, /,$special);
  891.                 foreach my $presenter (@presenters) {
  892.                     push @{$prog{credits}{presenter}}, $presenter ;
  893.                 }
  894.             } elsif ($special =~ s/Invit.*s : //i) {
  895.                 my @guests = split(/, /,$special);
  896.                 foreach my $guest (@guests) {
  897.                     push @{$prog{credits}{guest}}, $guest ;
  898.                 }
  899.             } elsif ($special =~ s/Musique : //i) {
  900.                 my @musics = split(/, /,$special);
  901.                 foreach my $music (@musics) {
  902.     # il faut XMLTV >= 0.5.58 pour que ce champ soit reconnu
  903.     # sinon ça genere un warning mais le fichier xml est quand meme ecrit.
  904.                     push @{$prog{credits}{composer}}, $music ;
  905.                 }
  906.             } elsif ($special =~ m/Showview : ([0-9]+)/) {
  907.                 $prog{showview} = $1;
  908.             } elsif ($special =~ s/Année : //i) {
  909.                 $prog{'date'} = $special;
  910.             } elsif ($special =~ /St.r.o/) {
  911.                 $prog{'audio'}{stereo} = "stereo";
  912.             } elsif ($special =~ m/Dolby digital/) {
  913.                 $prog{'audio'}{stereo} = "digital";
  914.             } elsif ($special =~ m/Dolby 5.1/) {
  915.                 $prog{'audio'}{stereo} = "surround";
  916.             } elsif ($special =~ m/Dolby/) {
  917.                 $prog{'audio'}{stereo} = "dolby";
  918.             } elsif ($special =~ m/VM/) {
  919.                 $prog{'audio'}{stereo} = "bilingual";
  920.             } elsif ($special =~ m/Pays : (.*)/) {
  921.                 $prog{country} = $1;
  922.         } elsif ($special =~ s/Genre : //i) {
  923.                 $subgenre = $special;
  924.             } elsif ($special =~ m/Titre original : (.*)/) {
  925.                 $prog{title_orig} = $1;
  926.             } elsif ( ($special =~ m/In.*dit/) || ($special =~ m/Premi.*re diffusion/) ) {
  927.                 $prog{premiere} = [];
  928.             } elsif ($special =~ m/Rediffusion/) {
  929.                 $prog{'previously-shown'} = {};
  930.             } elsif ($special =~ m/En 16:9/) {
  931.                 $prog{video}{aspect} = "16:9";
  932.             } elsif ($special =~ m/En 4:3/) {
  933.                 $prog{video}{aspect} = "4:3";
  934.             } elsif ($special =~ m/HD/) {
  935.                 $prog{video}{quality} = "HDTV";
  936.             } elsif ($special =~ m/Tous publics/) {
  937.                 $rating2 = 1;
  938.             }
  939.  
  940.         }
  941.  
  942.         if($episode ne "-1") {
  943.             $description = $episode_text." - ".$description;
  944.         }
  945.         if($season ne "-1") {
  946.             $description = $season_text." - ".$description;
  947.         }
  948.  
  949.         $epstring = "";
  950.         if(($episode ne "-1") || ($season ne "-1")) {
  951.             if ($season ne "-1") {
  952.                 if($season =~ /(\d+)\/(\d+)/) {
  953.                     $epstring .= ($1-1)."/".$2;
  954.                 } else {
  955.                     if($season =~ /(\d+)/) {
  956.                             $epstring .= ($1-1);
  957.                     }
  958.                 }
  959.             }
  960.             $epstring .= ".";
  961.  
  962.             if ($episode ne "-1") {
  963.                 if($episode =~ /(\d+)\/(\d+)/) {
  964.                     $epstring .= ($1-1)."/".$2;
  965.                 } else {
  966.                     if($episode =~ /(\d+)/) {
  967.                         $epstring .= ($1-1);
  968.                     }
  969.                 }
  970.             }
  971.             $epstring .= ".";
  972.             push @{$prog{'episode-num'}}, [$epstring,"xmltv_ns"];
  973.         }
  974.  
  975.         push @{$prog{icon}}, {src => $imgurl};
  976.  
  977.         if (defined $subgenre) {
  978.             $prog{category} = [ [ xmlencoding(lc($genre)), $LANG ], [ xmlencoding(lc($subgenre)), $LANG ] ];
  979.         }
  980.  
  981.  
  982.         if ( $description ne "" ) {
  983.             if($critic) {
  984.                 $description = $description." --  Critique : ".$critic;
  985.             }
  986.             push @{$prog{desc}}, [$description, $LANG ];
  987.         }
  988.         #$prog{showview}=$showview;
  989.  
  990.  
  991.         my $icon;
  992.         if ($age > 0 && !$rating2) {
  993.             if ($age <= 10) {
  994.                 $icon = 'http://www.csa.fr/picts/visuels/picto_cat2.gif';
  995.             } elsif ($age <= 12) {
  996.                 $icon = 'http://www.csa.fr/picts/visuels/picto_cat3.gif';
  997.             } elsif ($age <= 16)  {
  998.                 $icon = 'http://www.csa.fr/picts/visuels/picto_cat4.gif';
  999.             } else {
  1000.                 $icon = 'http://www.csa.fr/picts/visuels/picto_cat5.gif';
  1001.             }
  1002.             $age = -$age;
  1003.     #       $prog{rating} = [[ $age ]];
  1004.     #      push @{$prog->{rating}}, [ $rating, "CSA", [ {src => $icon} ] ];
  1005.             if ($icon) {
  1006.                 push @{$prog{rating}}, [ $age, "CSA", [ {src => $icon}] ];
  1007.             } else {
  1008.                 push @{$prog{rating}}, [ $age, "CSA", [] ];
  1009.             }
  1010.         }
  1011.         else {
  1012.             push @{$prog{rating}}, [ "Tout public", "CSA", [] ];
  1013.  
  1014.         }
  1015.  
  1016.         # étoiles
  1017.         $prog{'star-rating'} = [$stars."/5"] if ($stars);
  1018.  
  1019.  
  1020.         $writer->write_programme(\%prog);
  1021.  
  1022.     }
  1023.  undef $page;
  1024. }
  1025.  
  1026. # use an integrated sub to set a specific user agent
  1027. sub get_page( $ ) {
  1028.     my $url = shift;
  1029.  
  1030.     if (defined $last_get_time) {
  1031.         # A page has already been retrieved recently.  See if we need
  1032.         # to sleep for a while before getting the next page - being
  1033.         # nice to the server.
  1034.  
  1035.         my $next_get_time = $last_get_time + (rand $Delay);
  1036.         my $sleep_time = $next_get_time - time();
  1037.         sleep $sleep_time if $sleep_time > 0;
  1038.     }
  1039.  
  1040.     my $r = $ua->get($url);
  1041.  
  1042.     # Then start the delay from this time on the next fetch - so we
  1043.     # make the gap _between_ requests rather than from the start of
  1044.     # one request to the start of the next.  This punishes modem users
  1045.     # whose individual requests take longer, but it also punishes
  1046.     # downloads that take a long time for other reasons (large file,
  1047.     # slow server) so it's about right.
  1048.  
  1049.     $last_get_time = time();
  1050.  
  1051.     if ($r->is_error) {
  1052.         # At the moment download failures seem rare, so the script dies if
  1053.         # any page cannot be fetched.  We could later change this routine
  1054.         # to return undef on failure.  But dying here makes sure that a
  1055.         # failed page fetch doesn't get stored in XMLTV::Memoize's cache.
  1056.         #
  1057.         die "could not fetch $url, error: " . $r->status_line . ", aborting\n" if $FailOnError;
  1058.         $errors{$url} = $r->status_line;
  1059.         return undef;
  1060.     } else {
  1061.          print STDERR "Récupération de ".$url."\n";
  1062.         return $r->content;
  1063.     }
  1064.  
  1065. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement