root/grabbers/abc_website @ 667

Revision 667, 21.2 kB (checked in by lincoln, 6 years ago)

fix regression in abc/abc2_website: when fetching extra days, only try to fetch daily page once for beyond 7 days. also put parse_xmltv_date and cleanup into common library code

  • 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.13";
25
26use LWP::UserAgent;
27use XMLTV;
28use POSIX qw(strftime mktime);
29use Getopt::Long;
30use HTML::TreeBuilder;
31use Data::Dumper;
32use Storable;
33use Shepherd::Common;
34
35#
36# constants
37#
38my $urls;
39$urls->{station_close}->{ABC} = "http://www.abc.net.au/tv/guide/abctvweekguide.htm";
40$urls->{station_close}->{ABC2} = "http://www.abc.net.au/tv/guide/abc2weekguide.htm";
41$urls->{guide}->{ABC} = "http://www.abc.net.au/tv/guide/netw";
42$urls->{guide}->{ABC2} = "http://www.abc.net.au/tv/guide/abc2";
43
44#
45# some initial cruft
46#
47
48my $script_start_time = time;
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 $tries = ($daynum > 7 ? 1 : 5);
341                &log((sprintf "Fetching %s summary data: day %d of %d",
342                        $xmlid, $daynum, $opt_days ));
343                my $data = Shepherd::Common::get_url(url => $url, retries => $tries, debug => $debug * 2);
344                my $tree = HTML::TreeBuilder->new_from_content($data) if ($data);
345
346                if (!defined $tree) {
347                        &log("failed to fetch $url after $tries attempts; skipping");
348
349                        die "couldn't fetch first daily page after $tries attempts, network is probably down. aborting!"
350                          if ((!defined $stats{abc_daily_pages}) || ($stats{abc_daily_pages} == 0));
351
352                        next;
353                }
354
355                my $seen_programmes = 0;
356                my $seen_pm = 0;
357
358                for ($tree->look_down('_tag' => 'div', 'class' => 'scheduleDiv')) {
359                        foreach my $tree_tr ($_->look_down('_tag' => 'tr')) {
360                                if (my $tree_row = $tree_tr->look_down('_tag' => 'th', 'scope' => 'row')) {
361                                        if ($tree_row->as_text() =~ /^(\d+):(\d+)(.)m/) {
362                                                $timeattr[2] = $1; # hour
363                                                $timeattr[1] = $2; # min
364
365                                                if ($3 eq "p") {
366                                                        # pm
367                                                        $timeattr[2] += 12 if ($timeattr[2] != 12);
368                                                        $seen_pm = 1;
369                                                }
370                                                my $found_time = mktime(@timeattr);
371
372                                                # handle programmes that are after midnight
373                                                if (($seen_pm) && ($3 eq "a")) {
374                                                        if ($timeattr[2] == 12) {
375                                                                $found_time += (12*60*60); # 12:xx am
376                                                        } else {
377                                                                $found_time += (24*60*60);
378                                                        }
379                                                }
380                                                       
381                                                if ($tree_tr->look_down('_tag' => 'td')) {
382                                                        foreach my $prog ($tree_tr->look_down('_tag' => 'a')) {
383                                                                my $programme = $prog->as_text();
384                                                                my $progurl = $prog->attr('href');
385       
386                                                                if ($progurl =~ /^\/tv\/guide\//) {
387                                                                        printf "day %d time '%s' (%s) prog: %s url: %s\n",
388                                                                                $daynum,$tree_row->as_text(),POSIX::strftime("%Y%m%d%H%M", localtime($found_time)),
389                                                                                $programme,$progurl if ($debug && $debug > 1);
390
391                                                                        $unprocessed_progname[$unprocessed_programmes] = $programme;
392                                                                        $unprocessed_starttime[$unprocessed_programmes] = $found_time;
393                                                                        $unprocessed_url[$unprocessed_programmes] = "http://www.abc.net.au".$progurl;
394                                                                        $unprocessed_programmes++;
395                                                                        $seen_programmes++;
396                                                                } else {
397                                                                        printf "ignoring prog %s because url %s is not a detail page\n",
398                                                                                $programme,$progurl if $debug;
399                                                                }
400                                                        }
401                                                }
402                                        }
403                                }
404                        }
405                }
406
407                if ($seen_programmes > 0) {
408                        $stats{abc_daily_pages}++;
409
410                        if (defined $station_close_data[$daynum]) {
411                                # get station-close time from the previously-fetched "weekly programme guide"
412
413                                $unprocessed_progname[$unprocessed_programmes] = "Station Close";
414                                $unprocessed_starttime[$unprocessed_programmes] = $station_close_data[$daynum];
415                                $unprocessed_url[$unprocessed_programmes] = "";
416                                $unprocessed_programmes++;
417                        } else {
418                                # throw away last programme from each day - we can't use it as
419                                # we don't have a 'stop' time for it
420
421                                printf "throwing away '%s' (%s) because we won't have a valid stop time\n",
422                                        $unprocessed_progname[$unprocessed_programmes-1],
423                                        POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$unprocessed_programmes-1]))
424                                        if $debug;
425                                $unprocessed_progname[$unprocessed_programmes-1] = "";
426                        }
427                } else {
428                        # if we were trying to fetch more than 7 days, stop on first day with no programmes
429                        if ($daynum > 7) {
430                                &log("failed to fetch $url, assuming we only have $daynum days..");
431                                $days_left = 0;
432                                next DAYS;
433                        }
434                }
435        }
436
437        # have 'n' days of this channel unprocessed - process it!
438        &log((sprintf "have summary data, now fetching detail pages for up to %d programmes..",$unprocessed_programmes-2));
439
440        for (my $i = 0; $i < ($unprocessed_programmes-1); $i++) {
441                next if ($unprocessed_progname[$i] eq "");
442
443                # if we are micro-gap fetching, only include programmes which match our micro gaps
444                if ($opt_gaps_file ne "") {
445                        my $found_gap_match = 0;
446                        for (my $g_num = 0; $g_num < $#gap_s; $g_num++) {
447                                $found_gap_match++
448                                  if ((($gap_s[$g_num] >= $unprocessed_starttime[$i]) &&
449                                       ($gap_s[$g_num] <= $unprocessed_starttime[$i+1])) ||
450                                      (($gap_e[$g_num] >= $unprocessed_starttime[$i]) &&
451                                       ($gap_e[$g_num] <= $unprocessed_starttime[$i+1])) ||
452                                      (($gap_s[$g_num] <= $unprocessed_starttime[$i]) &&
453                                       ($gap_e[$g_num] >= $unprocessed_starttime[$i+1])));
454                        }
455                        next if (!$found_gap_match);
456
457                        $stats{programme_gaps_used}++;
458                        printf "gap-fetching: including prog '%s', start %d, end %d\n", $unprocessed_progname[$i], 
459                                $unprocessed_starttime[$i], $unprocessed_starttime[$i+1] if $debug;
460                }
461
462                $stats{programmes}++;
463                my $prog;
464
465                my $cache_key = sprintf "%d,%d,%s,%s", $unprocessed_starttime[$i], $unprocessed_starttime[$i+1], $xmlid, $unprocessed_progname[$i];
466
467                $prog->{'channel'} =    $xmlid;
468                $prog->{'start'} =      POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$i]));
469                $prog->{'stop'} =       POSIX::strftime("%Y%m%d%H%M", localtime($unprocessed_starttime[$i+1]));
470                $prog->{'title'} =      [[ $unprocessed_progname[$i], $lang ]];
471
472                if (defined $data_cache->{$cache_key}) {
473                        $stats{used_cached_data}++;
474                } else {
475                        if ((!$opt_cheap) && ($unprocessed_url[$i] ne "")) {
476                                $stats{portal_detail_pages}++;
477                                &get_one_abc_event($cache_key, $unprocessed_url[$i]);
478
479                                if (($stats{portal_detail_pages} % 25) == 1) {
480                                        &log((sprintf "  .. at %s detail page %d of %d (used %d cached entries)",
481                                                $xmlid, ($i+1), $unprocessed_programmes-2, 
482                                                (defined $stats{used_cached_data} ? $stats{used_cached_data} : 0)));
483
484                                        if (!$opt_fast) {
485                                                # slow down ..
486                                                my $waittime = 3 + int(rand(10));
487                                                sleep($waittime);
488                                                $stats{slept_for} += $waittime;
489                                        }
490                                }
491                        }
492                }
493
494                if (defined $data_cache->{$cache_key}) {
495                        $prog->{'sub-title'} = [[ $data_cache->{$cache_key}->{subtitle}, $lang ]] 
496                          if $data_cache->{$cache_key}->{subtitle};
497                        $prog->{'desc'} = [[ $data_cache->{$cache_key}->{desc}, $lang ]]
498                          if $data_cache->{$cache_key}->{desc};
499                        $prog->{'category'} = [[ $data_cache->{$cache_key}->{genre}, $lang ]]
500                          if $data_cache->{$cache_key}->{genre};
501                        $prog->{'previously-shown'} = { } if (defined $data_cache->{$cache_key}->{repeat});
502                        $prog->{'subtitles'} = [ { 'type' => 'teletext' } ] if (defined $data_cache->{$cache_key}->{cc});
503                        $prog->{'rating'} = [ [ $data_cache->{$cache_key}->{rating}, 'ABA', undef] ]
504                          if (defined $data_cache->{$cache_key}->{rating});
505                }
506
507                Shepherd::Common::cleanup($prog);
508                $writer->write_programme($prog);
509        }
510}
511
512######################################################################################################
513
514sub get_one_abc_event
515{
516        my ($cache_key, $url) = @_;
517        my $seen_programme = 0;
518
519        my $data = Shepherd::Common::get_url(url => $url, debug => $debug);
520        my $tree = HTML::TreeBuilder->new_from_content($data) if ($data);
521        if (!defined $tree) {
522                &log("failed to fetch $url; skipping");
523                return;
524        }
525
526        if (my $inner_tree = $tree->look_down('_tag' => 'div', 'class' => 'column2')) {
527                my $event_title = undef, my $event_subtitle = undef, my $event_description = undef, my $event_genre = undef;
528
529                if (my $prog_h2 = $inner_tree->look_down('_tag' => 'h2')) {
530                        my $full_title = $prog_h2->as_HTML();
531                        ($event_title,$event_subtitle) = split(/<br>/,$full_title);
532
533                        $event_title =~ s/(<[a-zA-Z0-9]+\>)//g; # remove html tags
534                        $event_title =~ s/(^\n|\n$)//g;         # strip trailing/leading blank lines
535
536                        if ($event_subtitle) {
537                                $event_subtitle =~ s/(<[\/a-zA-Z0-9]+\>)//g;    # remove html tags
538                                $event_subtitle =~ s/(^\n|\n$)//g;              # strip trailing/leading blank lines
539                                $data_cache->{$cache_key}->{subtitle} = $event_subtitle;
540                        }
541                }
542                       
543                my $paranum = 0;
544                my $seen_genre = 0;
545                foreach my $para ($inner_tree->look_down('_tag' => 'p')) {
546                        $paranum++;
547
548                        if (($paranum > 1) && (!($para->as_text() =~ /^Go to website/)) && (!($para->as_text() =~ /^Send to a Friend/))) {
549                                if (my $try_genre = $para->look_down('_tag' => 'a')) {
550                                        $data_cache->{$cache_key}->{genre} = $try_genre->as_text();
551                                        $seen_genre = 1;
552                                }
553
554                                if (!$seen_genre) {
555                                        $data_cache->{$cache_key}->{desc} .= $para->as_text() . "\n";
556                                } else {
557                                        $data_cache->{$cache_key}->{repeat} = 1 if ($para->as_text() =~ /Repeat/);
558                                        $data_cache->{$cache_key}->{cc} = 1 if ($para->as_text() =~ /CC/);
559                                        $data_cache->{$cache_key}->{rating} = $1 if ($para->as_text() =~ /(M|PG|G)/);
560                                }
561                        }
562                }
563
564                if (defined $data_cache->{$cache_key}->{desc}) {
565                        $data_cache->{$cache_key}->{desc} =~ s/(^\n|\n$)//g;            # strip trailing/leading blank lines
566                        $data_cache->{$cache_key}->{desc} =~ s/(^\s+|\s+$)//g;          # strip trailing/leading spaces
567                        delete $data_cache->{$cache_key}->{desc} if ($data_cache->{$cache_key}->{desc} eq "");
568                }
569
570                $seen_programme++;
571                $stats{added_cached_data}++;
572
573                &write_cache if (($opt_no_cache == 0) &&
574                  (($stats{added_cached_data} % 30) == 0)); # incrementally write
575        }
576
577        if ($seen_programme == 0) {
578                printf "WARNING: failed to parse any programme data from '%s' - blocked/rate-limited/format-changed?\n",$url;
579                $stats{failed_to_parse_portal_detail_page}++;
580        }
581}
582
583######################################################################################################
584
585sub log
586{
587        my ($entry) = @_;
588        printf "%s\n", $entry;
589}
590
591######################################################################################################
592
593sub print_stats
594{
595        printf "STATS: %s v%s completed in %d seconds", $progname, $version, (time-$script_start_time);
596        foreach my $key (sort keys %stats) {
597                printf ", %d %s",$stats{$key},$key;
598        }
599        printf "\n";
600}
601
602######################################################################################################
603
604sub get_station_close
605{
606        my ($xmlid,$url) = @_;
607        &log("fetching (weekly) station close data for $xmlid");
608        my $data = Shepherd::Common::get_url(url => $url, debug => $debug);
609        my $tree = HTML::TreeBuilder->new_from_content($data) if ($data);
610
611        if (!defined $tree) {
612                &log("failed to fetch $url; skipping");
613                return;
614        }
615
616        my $to_skip = $opt_offset;
617        my $daynum = 0;
618        my $last_td_text;
619
620        foreach my $tree_td ($tree->look_down('_tag' => 'td')) {
621                if ($tree_td->as_text() =~ /^\.\.\.programs start at /) {
622                        if (defined $last_td_text) {
623                                if ($to_skip > 0) {
624                                        $to_skip--;
625                                } else {
626                                        # 0=sec,1=min,2=hour,3=day,4=month,5=year,6=wday,7=yday,8=isdst
627                                        my @timeattr = localtime($starttime + ($daynum*86400));
628                                        $timeattr[0] = 0; # zero seconds
629
630                                        if ($last_td_text =~ /^(\d+):(\d+)(.)m/) {
631                                                $timeattr[2] = $1; # hour
632                                                $timeattr[1] = $2; # min
633
634                                                if ($3 eq "p") {
635                                                        # pm
636                                                        $timeattr[2] += 12 if ($timeattr[2] != 12);
637                                                }
638                                                my $found_time = mktime(@timeattr);
639
640                                                if ($3 eq "a") {
641                                                        # am - must be tomorrow
642                                                        if ($timeattr[2] == 12) {
643                                                                $found_time += (12*60*60); # 12:xx am
644                                                        } else {
645                                                                $found_time += (24*60*60);
646                                                        }
647                                                }
648
649                                                $daynum++;
650                                                $station_close_data[$daynum] = $found_time;
651
652                                                printf "station close time for day %d is %s\n",
653                                                        $daynum, POSIX::strftime("%Y%m%d%H%M", localtime($found_time))
654                                                        if $debug;
655                                        }
656                                }
657                        }
658                }
659                $last_td_text = $tree_td->as_text();
660        }
661}
662
663######################################################################################################
Note: See TracBrowser for help on using the browser.