root/grabbers/abc2_website @ 486

Revision 486, 23.5 kB (checked in by lincoln, 6 years ago)

fix microgap support in abc2_website - was expecting XMLTV date/time format not epoch format

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