root/grabbers/abc2_website @ 668

Revision 668, 21.3 kB (checked in by lincoln, 6 years ago)

additional bugfix for [667]

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