root/grabbers/abc_website @ 587

Revision 587, 25.3 kB (checked in by lincoln, 6 years ago)

commit --set overrides for abc_website/abc2_website

  • Property svn:executable set to *
Line 
1#!/usr/bin/perl -w
2
3# ABC/ABC2 au_tv guide grabber - runs from "Shepherd" master grabber
4#  * written by ltd
5#  * uses ABC website for ABC or ABC2 data
6#  * when used in conjunction with Shepherd, shepherd can collect other channels
7#    using other grabbers
8#  * this does NOT use any config file - all settings are passed in from shepherd
9
10#  changelog:
11#    1.50  22sep06      added support for "shepherd" master grabber script
12#    1.51  02oct06      --ready option
13#    1.52  03oct06      split out abc grabber into its own grabber
14#    1.55  09oct06      formalize --cheap option
15#    1.56  20oct06      misc cleanups
16#    1.60  11nov06      fix midday time calculation
17#    1.70  16nov06      also use "printable" TV guide to determine 'station close'
18#    2.00  23nov06      simplified
19
20use strict;
21
22my $progname = "abc_website";
23my $chan_id = "ABC";
24my $version = "2.11";
25
26use LWP::UserAgent;
27use XMLTV;
28use POSIX qw(strftime mktime);
29use Getopt::Long;
30use HTML::TreeBuilder;
31use Data::Dumper;
32use Storable;
33
34#
35# constants
36#
37my $urls;
38$urls->{station_close}->{ABC} = "http://www.abc.net.au/tv/guide/abctvweekguide.htm";
39$urls->{station_close}->{ABC2} = "http://www.abc.net.au/tv/guide/abc2weekguide.htm";
40$urls->{guide}->{ABC} = "http://www.abc.net.au/tv/guide/netw";
41$urls->{guide}->{ABC2} = "http://www.abc.net.au/tv/guide/abc2";
42
43#
44# some initial cruft
45#
46
47my $script_start_time = time;
48my $gmt_offset;
49my %stats;
50my $channels, my $opt_channels, my $gaps;
51my $tv_guide;
52my $data_cache;
53my $override_settings = { };
54my @station_close_data;
55my $writer;
56my %amp = ( nbsp => ' ', qw{ amp & lt < gt > apos ' quot " } );
57
58my $ua;
59$ua = LWP::UserAgent->new('timeout' => 30, 'keep_alive' => 30, 'agent' => "Shepherd / $progname $version");
60$ua->env_proxy;
61# $ua->cookie_jar({});
62$ua->conn_cache(LWP::ConnCache->new());
63$| = 1;
64
65#
66# parse command line
67#
68
69my $opt_days =          7;                              # default
70my $opt_offset =        0;                              # default
71my $opt_timezone =      "1000";                         # default
72my $opt_outputfile =    $progname.".xmltv";             # default
73my $opt_configfile =    $progname.".conf";              # ignored
74my $opt_cache_file =    $progname.".storable.cache";
75my $opt_old_cache_file = $progname.".cache";
76my $opt_channels_file=  "";
77my $opt_gaps_file=  "";
78my $opt_no_cache =      0;
79my $opt_cheap =         0;
80my $opt_fast =          0;
81my $opt_warper =        0;
82my $opt_obfuscate =     0;
83my $opt_do_extra_days = 0;
84my $opt_set = "";
85my $opt_help =          0;
86my $opt_version =       0;
87my $opt_desc =          0;
88my $opt_dont_retry =    0;
89my $debug =             0;
90my $lang =              "en";
91my $region =            94;
92my $time_offset =       0;
93
94GetOptions(
95        'region=i'      => \$region,
96        'days=i'        => \$opt_days,
97        'offset=i'      => \$opt_offset,
98        'timezone=s'    => \$opt_timezone,
99        'channels_file=s' => \$opt_channels_file,
100        'gaps_file=s' => \$opt_gaps_file,
101        'output=s'      => \$opt_outputfile,
102        'config-file=s' => \$opt_configfile,
103        'cache-file=s'  => \$opt_cache_file,
104        'do-extra-days' => \$opt_do_extra_days,
105        'fast'          => \$opt_fast,
106        'no-cache'      => \$opt_no_cache,
107        'cheap'         => \$opt_cheap,
108        'debug+'        => \$debug,
109        'warper'        => \$opt_warper,
110        'lang=s'        => \$lang,
111        'obfuscate'     => \$opt_obfuscate,
112        'no-retry'      => \$opt_dont_retry,
113        'set=s'         => \$opt_set,
114        'help'          => \$opt_help,
115        'verbose'       => \$opt_help,
116        'version'       => \$opt_version,
117        'ready'         => \$opt_version,
118        'desc'          => \$opt_desc,
119        'v'             => \$opt_help);
120
121&help if ($opt_help);
122
123if ($opt_version || $opt_desc) {
124        printf "%s %s\n",$progname,$version;
125        printf "%s is a details-aware grabber that collects decent quality data using the ABC website for %s only.",$progname,$chan_id if $opt_desc;
126        exit(0);
127}
128
129&set_override if ($opt_set ne "");
130
131die "no channel file specified, see --help for instructions\n", if ($opt_channels_file eq "");
132
133#
134# go go go!
135#
136
137my $starttime = time;
138&read_cache if ($opt_no_cache == 0);
139
140&log(sprintf "going to %s%s %s%d%s days%s of data into %s (%s%s)",
141        ($opt_gaps_file ne "" ? "micro-gap " : ""),
142        ($opt_cheap ? "verify (cache-validate)" : "grab"),
143        ($opt_do_extra_days ? "somewhere between " : ""),
144        $opt_days,
145        ($opt_do_extra_days ? " to 28" : ""),
146        ($opt_offset ? " (skipping first $opt_offset days)" : ""),
147        $opt_outputfile,
148        ($opt_no_cache ? "without caching" : "with caching"),
149        ($opt_warper ? ", anonymously" : ""));
150
151# read channels file
152if (-r $opt_channels_file) {
153        local (@ARGV, $/) = ($opt_channels_file);
154        no warnings 'all'; eval <>; die "$@" if $@;
155} else {
156        die "WARNING: channels file $opt_channels_file could not be read: $!\n";
157}
158die "nothing to do; $chan_id not in channels lineup!\n" if (!defined $channels->{$chan_id});
159
160# if just filling in microgaps, parse gaps
161if ($opt_gaps_file ne "") {
162        if (-r $opt_gaps_file) {
163                local (@ARGV, $/) = ($opt_gaps_file);
164                no warnings 'all'; eval <>; die "$@" if $@;
165        } else {
166                die "WARNING: gaps_file $opt_gaps_file could not be read: $!\n";
167        }
168}
169
170my %writer_args = ( encoding => 'ISO-8859-1' );
171my $fh = new IO::File(">$opt_outputfile") || die "can't open $opt_outputfile: $!";
172$writer_args{OUTPUT} = $fh;
173
174$writer = new XMLTV::Writer(%writer_args);
175$writer->start( { 'source-info-name'   => "$progname $version", 'generator-info-name' => "$progname $version"} );
176$writer->write_channel( { 'display-name' => [[ $chan_id, $lang ]], 'id' => $channels->{$chan_id} } );
177
178&get_station_close($channels->{$chan_id}, $urls->{station_close}->{$chan_id});
179&get_abc_data($channels->{$chan_id}, $urls->{guide}->{$chan_id});
180&write_cache if ($opt_no_cache == 0);
181
182$writer->end;
183
184&print_stats;
185exit(0);
186
187######################################################################################################
188# help
189
190sub help
191{
192        print<<EOF
193$progname $version
194
195options are as follows:
196        --help                  show these help options
197        --days=N                fetch 'n' days of data (default: $opt_days)
198        --output=file           send xml output to file (default: "$opt_outputfile")
199        --config-file=file      (ignored - historically used by grabbers not not this one)
200        --no-cache              don't use a cache to optimize (reduce) number of web queries
201        --cheap                 validate contents of cache - fetch summary only, not details
202        --cache-file=file       where to store cache (default "$opt_cache_file")
203        --fast                  don't run slow - get data as quick as you can - not recommended
204        --debug                 increase debug level
205        --warper                fetch data using WebWarper web anonymizer service
206        --obfuscate             pretend to be a proxy servicing multiple clients
207        --do-extra-days         fetch extra (21 days) from ABC website
208        --no-retry              if webserver is rejecting our request, don't retry (default: do retry)
209        --lang=[s]              set language of xmltv output data (default $lang)
210
211        --region=N              set region for where to collect data from (default: $region)
212        --channels_file=file    where to get channel data from (if not set manually)
213        --timezone=HHMM         timezone for channel data (default: $opt_timezone)
214
215        --set (option):(1/0)    setting override options (1=enable, 0=disable)
216                do_extra_days:1/0   enable/disable fetching up to 24 days
217                fast:1/0            enable/disable extra-fast grab speed (not recommended)
218                debug:1/0           enable/disable debugging
219
220EOF
221;
222
223        exit(0);
224}
225
226######################################################################################################
227
228sub set_override
229{
230        &read_cache;
231        my ($setting, $val) = split(/:/,$opt_set);
232
233        die "--set format is (setting):(value) where value is 0 for disable, 1 for enable.\n"
234          if (($val ne "0") && ($val ne "1"));
235
236        die "unknown '--set' parameter '$setting', see --help for details.\n"
237          if (($setting ne "do_extra_days") &&
238              ($setting ne "fast") &&
239              ($setting ne "debug"));
240
241        $override_settings->{$setting} = $val;
242        printf "%s: override parameter %s: %s\n", $progname, $setting, ($val eq "0" ? "disabled" : "enabled");
243
244        &write_cache;
245        exit(0);
246}
247
248######################################################################################################
249# populate cache
250
251sub read_cache
252{
253        if (-r $opt_cache_file) {
254                my $store = Storable::retrieve($opt_cache_file);
255                $data_cache = $store->{data_cache};
256                $override_settings = $store->{override_settings};
257
258                # apply settings overrides
259                $opt_do_extra_days = 1 if ((defined $override_settings->{do_extra_days}) && ($override_settings->{do_extra_days} == 1));
260                $opt_fast = 1 if ((defined $override_settings->{fast}) && ($override_settings->{fast} == 1));
261                $debug = 1 if ((defined $override_settings->{debug}) && ($override_settings->{debug} > 0));
262        } else {
263                printf "WARNING: no programme cache $opt_cache_file - have to fetch all details\n";
264
265                # try to write to it - if directory doesn't exist this will then cause an error
266                &write_cache;
267        }
268}
269
270######################################################################################################
271# write out updated cache
272
273sub write_cache
274{
275        # cleanup old entries from cache
276        for my $cache_key (keys %{$data_cache}) {
277                my ($starttime, @rest) = split(/,/,$cache_key);
278                if ($starttime < (time-86400)) {
279                        delete $data_cache->{$cache_key};
280                        $stats{removed_items_from_cache}++;
281                }
282        }
283
284        my $store;
285        $store->{data_cache} = $data_cache;
286        $store->{override_settings} = $override_settings;
287        Storable::store($store, $opt_cache_file);
288}
289
290######################################################################################################
291
292sub get_abc_data
293{
294        my ($xmlid,$urlbase) = @_;
295        my $try_to_add_abc_detail;
296        my $unprocessed_programmes = 0;
297        my $stop_fetching = 0;
298        my @unprocessed_progname, my @unprocessed_starttime, my @unprocessed_url;
299
300        my $to_skip = $opt_offset;
301        my $daynum = 0;
302        my @gap_s, my @gap_e;
303
304        $opt_days = 28 if (($opt_do_extra_days) && ($opt_gaps_file eq "") && ($opt_offset == 0) && ($opt_days == 7));
305        my $days_left = $opt_days;
306
307DAYS:   while ($days_left > 0) {
308                my $currtime = $starttime + ($daynum * 86400);
309                $days_left--;
310                $daynum++;
311
312                if ($to_skip > 0) {
313                        $to_skip--;
314                        next;
315                }
316
317                if ($opt_gaps_file ne "") {             # micro-gap mode!
318                        my $found_gap_match = 0;
319
320                        if ((defined $gaps) && (defined $gaps->{$chan_id})) {
321                                foreach my $g (@{($gaps->{$chan_id})}) {
322                                        my ($s, $e) = split(/-/,$g);
323                                        if (($s >= $currtime) && ($s <= ($currtime+86400))) {
324                                                $found_gap_match++;
325                                                push(@gap_s,$s);
326                                                push(@gap_e,$e);
327                                                printf "including day %d channel '%s' gap start %d, gap end %d\n",
328                                                        $daynum, $chan_id, $s, $e if $debug;
329                                        }
330                                }
331                        }
332                        next if (!$found_gap_match);    # no gaps for this day - skip!
333                }
334
335                my @timeattr = localtime($currtime); # 0=sec,1=min,2=hour,3=day,4=month,5=year,6=wday,7=yday,8=isdst
336                $timeattr[0] = 0; # zero seconds
337
338                my $url = sprintf "%s/%s.htm",$urlbase, POSIX::strftime("%Y%m/%Y%m%d",localtime($currtime));
339
340                my $data;
341                my $tree;
342                my $tries = 0;
343                while (($tries < 5) && (!defined $tree)) {
344                        $tries++;
345                        &log((sprintf "fetching %s summary data: day %d of %d%s",
346                                $xmlid, $daynum, $opt_days, ($tries > 1 ? " (try $tries)" : "")));
347                        $data = &get_url($url);
348                        $tree = HTML::TreeBuilder->new_from_content($data) if ((defined $data) && ($data ne ""));
349
350                        if ((!$tree) && ($tries < 5)) {
351                                # if fetching extra days, bail out at first error
352                                if ($daynum > 7) {
353                                        &log("failed to fetch $url, assuming we only have $daynum days..");
354                                        $days_left = 0;
355                                        next DAYS;
356                                }
357
358                                # slow down ..
359                                my $waittime = ($tries*10)+int(rand(10));
360                                &log("failed to fetch $url, retrying in $waittime secs");
361                                sleep($waittime);
362                                $stats{slept_for} += $waittime;
363                        }
364                }
365                if (!defined $tree) {
366                        &log("failed to fetch $url after $tries attempts; skipping");
367
368                        die "couldn't fetch first daily page after $tries attempts, network is probably down. aborting!"
369                          if ((!defined $stats{abc_daily_pages}) || ($stats{abc_daily_pages} == 0));
370
371                        next;
372                }
373
374                my $seen_programmes = 0;
375                my $seen_pm = 0;
376
377                for ($tree->look_down('_tag' => 'div', 'class' => 'scheduleDiv')) {
378                        foreach my $tree_tr ($_->look_down('_tag' => 'tr')) {
379                                if (my $tree_row = $tree_tr->look_down('_tag' => 'th', 'scope' => 'row')) {
380                                        if ($tree_row->as_text() =~ /^(\d+):(\d+)(.)m/) {
381                                                $timeattr[2] = $1; # hour
382                                                $timeattr[1] = $2; # min
383
384                                                if ($3 eq "p") {
385                                                        # pm
386                                                        $timeattr[2] += 12 if ($timeattr[2] != 12);
387                                                        $seen_pm = 1;
388                                                }
389                                                my $found_time = mktime(@timeattr);
390
391                                                # handle programmes that are after midnight
392                                                if (($seen_pm) && ($3 eq "a")) {
393                                                        if ($timeattr[2] == 12) {
394                                                                $found_time += (12*60*60); # 12:xx am
395                                                        } else {
396                                                                $found_time += (24*60*60);
397                                                        }
398                                                }
399                                                       
400                                                if ($tree_tr->look_down('_tag' => 'td')) {
401                                                        foreach my $prog ($tree_tr->look_down('_tag' => 'a')) {
402                                                                my $programme = $prog->as_text();
403                                                                my $progurl = $prog->attr('href');
404       
405                                                                if ($progurl =~ /^\/tv\/guide\//) {
406                                                                        printf "day %d time '%s' (%s) prog: %s url: %s\n",
407                                                                                $daynum,$tree_row->as_text(),POSIX::strftime("%Y%m%d%H%M", localtime($found_time)),
408                                                                                $programme,$progurl if ($debug && $debug > 1);
409
410                                                                        $unprocessed_progname[$unprocessed_programmes] = $programme;
411                                                                        $unprocessed_starttime[$unprocessed_programmes] = $found_time;
412                                                                        $unprocessed_url[$unprocessed_programmes] = "http://www.abc.net.au".$progurl;
413                                                                        $unprocessed_programmes++;
414                                                                        $seen_programmes++;
415                                                                } else {
416                                                                        printf "ignoring prog %s because url %s is not a detail page\n",
417                                                                                $programme,$progurl if $debug;
418                                                                }
419                                                        }
420                                                }
421                                        }
422                                }
423                        }
424                }
425
426                if ($seen_programmes > 0) {
427                        $stats{abc_daily_pages}++;
428
429                        if (defined $station_close_data[$daynum]) {
430                                # get station-close time from the previously-fetched "weekly programme guide"
431
432                                $unprocessed_progname[$unprocessed_programmes] = "Station Close";
433                                $unprocessed_starttime[$unprocessed_programmes] = $station_close_data[$daynum];
434                                $unprocessed_url[$unprocessed_programmes] = "";
435                                $unprocessed_programmes++;
436                        } else {
437                                # throw away last programme from each day - we can't use it as
438                                # we don't have a 'stop' time for it
439
440                                printf "throwing away '%s' (%s) because we won't have a valid stop time\n",
441                                        $unprocessed_progname[$unprocessed_programmes-1],
442                                        POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$unprocessed_programmes-1]))
443                                        if $debug;
444                                $unprocessed_progname[$unprocessed_programmes-1] = "";
445                        }
446                } else {
447                        # if we were trying to fetch more than 7 days, stop on first day with no programmes
448                        if ($daynum > 7) {
449                                &log("failed to fetch $url, assuming we only have $daynum days..");
450                                $days_left = 0;
451                                next DAYS;
452                        }
453                }
454        }
455
456        # have 'n' days of this channel unprocessed - process it!
457        &log((sprintf "have summary data, now fetching detail pages for up to %d programmes..",$unprocessed_programmes-2));
458
459        for (my $i = 0; $i < ($unprocessed_programmes-1); $i++) {
460                next if ($unprocessed_progname[$i] eq "");
461
462                # if we are micro-gap fetching, only include programmes which match our micro gaps
463                if ($opt_gaps_file ne "") {
464                        my $found_gap_match = 0;
465                        for (my $g_num = 0; $g_num < $#gap_s; $g_num++) {
466                                $found_gap_match++
467                                  if ((($gap_s[$g_num] >= $unprocessed_starttime[$i]) &&
468                                       ($gap_s[$g_num] <= $unprocessed_starttime[$i+1])) ||
469                                      (($gap_e[$g_num] >= $unprocessed_starttime[$i]) &&
470                                       ($gap_e[$g_num] <= $unprocessed_starttime[$i+1])) ||
471                                      (($gap_s[$g_num] <= $unprocessed_starttime[$i]) &&
472                                       ($gap_e[$g_num] >= $unprocessed_starttime[$i+1])));
473                        }
474                        next if (!$found_gap_match);
475
476                        $stats{programme_gaps_used}++;
477                        printf "gap-fetching: including prog '%s', start %d, end %d\n", $unprocessed_progname[$i], 
478                                $unprocessed_starttime[$i], $unprocessed_starttime[$i+1] if $debug;
479                }
480
481                $stats{programmes}++;
482                my $prog;
483
484                my $cache_key = sprintf "%d,%d,%s,%s", $unprocessed_starttime[$i], $unprocessed_starttime[$i+1], $xmlid, $unprocessed_progname[$i];
485
486                $prog->{'channel'} =    $xmlid;
487                $prog->{'start'} =      POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$i]));
488                $prog->{'stop'} =       POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$i+1]));
489                $prog->{'title'} =      [[ $unprocessed_progname[$i], $lang ]];
490
491                if (defined $data_cache->{$cache_key}) {
492                        $stats{used_cached_data}++;
493                } else {
494                        if ((!$opt_cheap) && ($unprocessed_url[$i] ne "")) {
495                                $stats{portal_detail_pages}++;
496                                &get_one_abc_event($cache_key, $unprocessed_url[$i]);
497
498                                if (($stats{portal_detail_pages} % 25) == 1) {
499                                        &log((sprintf "  .. at %s detail page %d of %d (used %d cached entries)",
500                                                $xmlid, ($i+1), $unprocessed_programmes-2, 
501                                                (defined $stats{used_cached_data} ? $stats{used_cached_data} : 0)));
502
503                                        if (!$opt_fast) {
504                                                # slow down ..
505                                                my $waittime = 3 + int(rand(10));
506                                                sleep($waittime);
507                                                $stats{slept_for} += $waittime;
508                                        }
509                                }
510                        }
511                }
512
513                if (defined $data_cache->{$cache_key}) {
514                        $prog->{'sub-title'} = [[ $data_cache->{$cache_key}->{subtitle}, $lang ]] 
515                          if $data_cache->{$cache_key}->{subtitle};
516                        $prog->{'desc'} = [[ $data_cache->{$cache_key}->{desc}, $lang ]]
517                          if $data_cache->{$cache_key}->{desc};
518                        $prog->{'category'} = [[ $data_cache->{$cache_key}->{genre}, $lang ]]
519                          if $data_cache->{$cache_key}->{genre};
520                        $prog->{'previously-shown'} = { } if (defined $data_cache->{$cache_key}->{repeat});
521                        $prog->{'subtitles'} = [ { 'type' => 'teletext' } ] if (defined $data_cache->{$cache_key}->{cc});
522                        $prog->{'rating'} = [ [ $data_cache->{$cache_key}->{rating}, 'ABA', undef] ]
523                          if (defined $data_cache->{$cache_key}->{rating});
524                }
525
526                &cleanup($prog);
527                $writer->write_programme($prog);
528        }
529}
530
531######################################################################################################
532
533sub get_one_abc_event
534{
535        my ($cache_key, $url) = @_;
536        my $seen_programme = 0;
537
538        my $tries = 0;
539        my $tree;
540        while (($tries < 5) && (!$tree)) {
541                $tries++;
542                my $data = &get_url($url);
543                $tree = HTML::TreeBuilder->new_from_content($data) if ((defined $data) && ($data ne ""));
544
545                if ((!$tree) && ($tries < 5)) {
546                        # slow down ..
547                        my $waittime = ($tries*20)+int(rand(20));
548                        &log("failed to fetch $url on try $tries, retrying in $waittime secs");
549                        sleep($waittime);
550                        $stats{slept_for} += $waittime;
551                }
552        }
553        if (!defined $tree) {
554                &log("failed to fetch $url after $tries attempts; skipping");
555                return;
556        }
557
558        if (my $inner_tree = $tree->look_down('_tag' => 'div', 'class' => 'column2')) {
559                my $event_title = undef, my $event_subtitle = undef, my $event_description = undef, my $event_genre = undef;
560
561                if (my $prog_h2 = $inner_tree->look_down('_tag' => 'h2')) {
562                        my $full_title = $prog_h2->as_HTML();
563                        ($event_title,$event_subtitle) = split(/<br>/,$full_title);
564
565                        $event_title =~ s/(<[a-zA-Z0-9]+\>)//g; # remove html tags
566                        $event_title =~ s/(^\n|\n$)//g;         # strip trailing/leading blank lines
567
568                        if ($event_subtitle) {
569                                $event_subtitle =~ s/(<[\/a-zA-Z0-9]+\>)//g;    # remove html tags
570                                $event_subtitle =~ s/(^\n|\n$)//g;              # strip trailing/leading blank lines
571                                $data_cache->{$cache_key}->{subtitle} = $event_subtitle;
572                        }
573                }
574                       
575                my $paranum = 0;
576                my $seen_genre = 0;
577                foreach my $para ($inner_tree->look_down('_tag' => 'p')) {
578                        $paranum++;
579
580                        if (($paranum > 1) && (!($para->as_text() =~ /^Go to website/)) && (!($para->as_text() =~ /^Send to a Friend/))) {
581                                if (my $try_genre = $para->look_down('_tag' => 'a')) {
582                                        $data_cache->{$cache_key}->{genre} = $try_genre->as_text();
583                                        $seen_genre = 1;
584                                }
585
586                                if (!$seen_genre) {
587                                        $data_cache->{$cache_key}->{desc} .= $para->as_text() . "\n";
588                                } else {
589                                        $data_cache->{$cache_key}->{repeat} = 1 if ($para->as_text() =~ /Repeat/);
590                                        $data_cache->{$cache_key}->{cc} = 1 if ($para->as_text() =~ /CC/);
591                                        $data_cache->{$cache_key}->{rating} = $1 if ($para->as_text() =~ /(M|PG|G)/);
592                                }
593                        }
594                }
595
596                if (defined $data_cache->{$cache_key}->{desc}) {
597                        $data_cache->{$cache_key}->{desc} =~ s/(^\n|\n$)//g;            # strip trailing/leading blank lines
598                        $data_cache->{$cache_key}->{desc} =~ s/(^\s+|\s+$)//g;          # strip trailing/leading spaces
599                        delete $data_cache->{$cache_key}->{desc} if ($data_cache->{$cache_key}->{desc} eq "");
600                }
601
602                $seen_programme++;
603                $stats{added_cached_data}++;
604
605                &write_cache if (($opt_no_cache == 0) &&
606                  (($stats{added_cached_data} % 30) == 0)); # incrementally write
607        }
608
609        if ($seen_programme == 0) {
610                printf "WARNING: failed to parse any programme data from '%s' - blocked/rate-limited/format-changed?\n",$url;
611                $stats{failed_to_parse_portal_detail_page}++;
612        }
613}
614
615######################################################################################################
616# logic to fetch a page via http
617
618sub get_url
619{
620        my $url = shift;
621        my $response;
622        my $attempts = 0;
623        my ($raw, $page, $base);
624
625        $url =~ s#^http://#http://webwarper.net/ww/# if $opt_warper;
626        my $request = HTTP::Request->new(GET => $url);
627        $request->header('Accept-Encoding' => 'gzip');
628
629        if ($opt_obfuscate) {
630                $ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-us');
631                my $randomaddr = sprintf "203.%d.%d.%d",rand(255),rand(255),(rand(254)+1);
632                $request->header('Via' => '1.0 proxy:81 (Squid/2.3.STABLE3)');
633                $request->header('X-Forwarded-For' => $randomaddr);
634        }
635        $response = $ua->request($request);
636        if (!($response->is_success)) {
637                $stats{http_failed_requests}++;
638                return undef;
639        }
640
641        $stats{bytes_fetched} += do {use bytes; length($response->content)};
642        $stats{http_successful_requests}++;
643
644        if ($response->header('Content-Encoding') &&
645            $response->header('Content-Encoding') eq 'gzip') {
646                $stats{compressed_pages} += do {use bytes; length($response->content)};
647                $response->content(Compress::Zlib::memGunzip($response->content));
648        }
649        return $response->content;
650}
651
652######################################################################################################
653
654sub log
655{
656        my ($entry) = @_;
657        printf "%s\n", $entry;
658}
659
660######################################################################################################
661
662sub print_stats
663{
664        printf "STATS: %s v%s completed in %d seconds", $progname, $version, (time-$script_start_time);
665        foreach my $key (sort keys %stats) {
666                printf ", %d %s",$stats{$key},$key;
667        }
668        printf "\n";
669}
670
671######################################################################################################
672# descend a structure and clean up various things, including stripping
673# leading/trailing spaces in strings, translations of html stuff etc
674#   -- taken & modified from Michael 'Immir' Smith's excellent tv_grab_au
675
676sub cleanup {
677        my $x = shift;
678        if    (ref $x eq "REF")   { cleanup($_) }
679        elsif (ref $x eq "HASH")  { cleanup(\$_) for values %$x }
680        elsif (ref $x eq "ARRAY") { cleanup(\$_) for @$x }
681        elsif (defined $$x) {
682                $$x =~ s/&(#(\d+)|(.*?));/ $2 ? chr($2) : $amp{$3}||' ' /eg;
683                $$x =~ s/[^\x20-\x7f]/ /g;
684                $$x =~ s/(^\s+|\s+$)//g;
685        }
686}
687
688######################################################################################################
689
690# strptime type date parsing - BUT - if no timezone is present, treat time as being in localtime
691# rather than the various other perl implementation which treat it as being in UTC/GMT
692sub parse_xmltv_date
693{
694        my $datestring = shift;
695        my @t; # 0=sec,1=min,2=hour,3=day,4=month,5=year,6=wday,7=yday,8=isdst
696        my $tz_offset = 0;
697
698        # work out GMT offset - we only do this once
699        if (!$gmt_offset) {
700                my $tzstring = strftime("%z", localtime(time));
701
702                $gmt_offset = (60*60) * int(substr($tzstring,1,2));     # hr
703                $gmt_offset += (60 * int(substr($tzstring,3,2)));       # min
704                $gmt_offset *= -1 if (substr($tzstring,0,1) eq "-");    # +/-
705        }
706
707        if ($datestring =~ /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/) {
708                ($t[5],$t[4],$t[3],$t[2],$t[1],$t[0]) = (int($1)-1900,int($2)-1,int($3),int($4),int($5),0);
709                ($t[6],$t[7],$t[8]) = (-1,-1,-1);
710
711                # if input data has a timezone offset, then offset by that
712                if ($datestring =~ /\+(\d{2})(\d{2})/) {
713                        $tz_offset = $gmt_offset - (($1*(60*60)) + ($2*60));
714                } elsif ($datestring =~ /\-(\d{2})(\d{2})/) {
715                        $tz_offset = $gmt_offset + (($1*(60*60)) + ($2*60));
716                }
717
718                my $e = mktime(@t);
719                return ($e+$tz_offset) if ($e > 1);
720        }
721        return undef;
722}
723
724######################################################################################################
725
726sub get_station_close
727{
728        my ($xmlid,$url) = @_;
729        my $tries = 0;
730        my $tree;
731        while (($tries < 3) && (!$tree)) {
732                $tries++;
733                &log("fetching (weekly) station close data for $xmlid (attempt $tries)");
734                my $data = &get_url($url);
735                $tree = HTML::TreeBuilder->new_from_content($data) if ((defined $data) && ($data ne ""));
736
737                if ((!$tree) && ($tries < 3)) {
738                        # slow down ..
739                        my $waittime = ($tries*10)+int(rand(10));
740                        &log("failed to fetch $url, retrying in $waittime secs");
741                        sleep($waittime);
742                        $stats{slept_for} += $waittime;
743                }
744        }
745        if (!defined $tree) {
746                &log("failed to fetch $url after $tries attempts; skipping");
747                return;
748        }
749
750        my $to_skip = $opt_offset;
751        my $daynum = 0;
752        my $last_td_text;
753
754        foreach my $tree_td ($tree->look_down('_tag' => 'td')) {
755                if ($tree_td->as_text() =~ /^\.\.\.programs start at /) {
756                        if (defined $last_td_text) {
757                                if ($to_skip > 0) {
758                                        $to_skip--;
759                                } else {
760                                        # 0=sec,1=min,2=hour,3=day,4=month,5=year,6=wday,7=yday,8=isdst
761                                        my @timeattr = localtime($starttime + ($daynum*86400));
762                                        $timeattr[0] = 0; # zero seconds
763
764                                        if ($last_td_text =~ /^(\d+):(\d+)(.)m/) {
765                                                $timeattr[2] = $1; # hour
766                                                $timeattr[1] = $2; # min
767
768                                                if ($3 eq "p") {
769                                                        # pm
770                                                        $timeattr[2] += 12 if ($timeattr[2] != 12);
771                                                }
772                                                my $found_time = mktime(@timeattr);
773
774                                                if ($3 eq "a") {
775                                                        # am - must be tomorrow
776                                                        if ($timeattr[2] == 12) {
777                                                                $found_time += (12*60*60); # 12:xx am
778                                                        } else {
779                                                                $found_time += (24*60*60);
780                                                        }
781                                                }
782
783                                                $daynum++;
784                                                $station_close_data[$daynum] = $found_time;
785
786                                                printf "station close time for day %d is %s\n",
787                                                        $daynum, POSIX::strftime("%Y%m%d%H%M", localtime($found_time))
788                                                        if $debug;
789                                        }
790                                }
791                        }
792                }
793                $last_td_text = $tree_td->as_text();
794        }
795}
796
797######################################################################################################
Note: See TracBrowser for help on using the browser.