root/shepherd @ 57

Revision 57, 63.6 kB (checked in by lincoln, 7 years ago)

Bugfix: don't call postprocessors that aren't ready, rework accept-data-or-not postprocessor logic

Line 
1#!/usr/bin/perl -w
2
3# "Shepherd"
4
5my $version = '0.2.10';
6
7# A wrapper for various Aussie TV guide data grabbers
8#
9# Use --help for command-line options.
10# See shepherd.txt for details.
11#
12#  A current version of this script, plus a README file, might be here:
13#  http://www.whuffy.com/tv_grab_au/
14#
15# Changelog:
16# 0.1.0   : Basic self-updating and grabber management
17# 0.2.0   : --configure
18# 0.2.1   : Has a home in ~/.shepherd/
19# 0.2.2   : --check
20# 0.2.3   : Bugfix: archives correctly
21# 0.2.5   : Multi-grabber (potentially with partial data)
22# 0.2.6   : Postprocessor support
23# 0.2.7   : Changed online file structure
24# 0.2.8   : Integrated reconciler
25# 0.2.9   : Grabber config support
26# 0.2.10  : Bugfix: don't call postprocessors that aren't ready,
27#           rework accept-data-or-not postprocessor logic
28
29BEGIN { *CORE::GLOBAL::die = \&my_die; }
30
31use strict;
32
33use LWP::Simple;
34use Sort::Versions;
35use Cwd;
36use Getopt::Long;
37use Data::Dumper;
38use XMLTV;
39use XMLTV::Ask;
40use DateTime::Format::Strptime;
41use POSIX qw(strftime);
42use Time::HiRes qw(gettimeofday tv_interval);
43
44# ---------------------------------------------------------------------------
45# --- Global Variables
46# ---------------------------------------------------------------------------
47
48my $progname = 'shepherd';
49
50my $HOME = 'http://www.whuffy.com/shepherd';
51
52my $invoked = Cwd::realpath($0);
53
54# By default, Shepherd runs from ~/.shepherd/. If it's not run as a user,
55# it will try /opt/shepherd/ instead.
56my $CWD = ($ENV{HOME} ? $ENV{HOME} . "/." : "/opt/") . $progname;
57-d $CWD or mkdir $CWD or die "Cannot create directory $CWD: $!";
58chdir($CWD);
59
60my $ARCHIVE_DIR = "$CWD/archive";
61
62
63#### analyzer settings ####
64
65my $timeslot_size = (15 * 60);                  # 15 minute slots
66my $channel_ok_threshold_percent = 90;          # 90% these may need to be
67                                                # tweaked but look ok for now
68my $postprocessor_ok_threshold_percent = 80;    # 80% these may need to be
69                                                # tweaked but look ok for now
70my $postprocessor_disable_failure_threshold = 5;# number of times a
71                                                # postprocessor has to fail
72                                                # in a row before it is
73                                                # automatically disabled
74
75#### reconciler settings ####
76my %reclogic;
77
78# when setting the upper-bounds of a timeslot to look for overlapping
79# programmes between grabbers, cap the upper time window that we are prepared
80# to tolerate programmes ending within.
81# disabled by default (max overrides percent for upper bounds)
82
83$reclogic{compare_overlapping_programmes_extra_overtime_duration_percent} = 5;
84$reclogic{compare_overlapping_programmes_extra_overtime_max} = 0;
85
86# if there is a conflict between two grabbers, choose the grabber
87# with the MOST programmes in the timeslot WITHOUT COUNTING
88# any programmes of <= $reclogic{min_time_override_for_duplicate}
89
90$reclogic{min_time_override_for_duplicate} = (5 * 60);  # default = 5 minutes
91
92# when we've selected one grabber to insert data from, we look at all the other
93# grabbers for overlapping fields we can use to augment our primary grabber
94# set some thresholds for when to consider programming to be the 'same'
95# (with fuzz -/+ 5 mins max), -/+ 2.5mins for programmes <= 15 mins
96
97$reclogic{duplicate_programme_augment_data_short_cutoff} = (15*60); # <=15mins = short, >15mins = long
98$reclogic{duplicate_programme_augment_data_long_duration_threshold} = (5*60); # +/-5 mins
99$reclogic{duplicate_programme_augment_data_short_duration_threshold} = (2.5*60); # +/- 2min30
100
101# for any programmes we didn't choose, reset the starttime up to a maximum
102# window of 5 minutes to the same value as our "chosen" endtime.
103# if can't readjust, then ignore (remove) that programme
104
105$reclogic{readjust_starttime_for_nonmatched_programmes} = (5*60);
106
107#### end reconciler settings ####
108
109my $opt;
110my $pref_order;
111my $mirror_site;
112my $made_changes = 0;
113my $debug = 1;
114my $recdebug = 0;
115my $components = { };
116my $gscore;
117my $region;
118my $channels;
119my $config_file =   "$CWD/$progname.conf";
120my $channels_file = "$CWD/channels.conf";
121my $days = 7;
122
123# postprocessing
124my $title_translation_table = { };
125my $langs = [ 'en' ];
126my $num_timeslots;
127my $plugin_data = { };
128my $channel_data = { };
129my $starttime, my $endtime;
130my $input_postprocess_file = "$CWD/reconciled_output_pre_postprocessors.xml";
131my $grabber_data_percent = 0;
132
133# OBSOLETE: will be removed
134my $grabbers;
135my $postprocessors;
136my $preferred;
137
138# ---------------------------------------------------------------------------
139# --- Setup
140# ---------------------------------------------------------------------------
141
142print ucfirst($progname) . " v$version\n\n";
143#print "Cwd: $CWD.\n";
144
145# Any options Shepherd doesn't understand, we'll pass to the grabber(s)
146Getopt::Long::Configure(qw/pass_through/);
147
148get_initial_command_line_options();
149
150help() if ($opt->{help});
151
152unless ($opt->{configure})
153{
154    read_config_file();
155    read_channels_file();
156}
157
158get_remaining_command_line_options();
159
160if ($opt->{status})
161{
162    status();
163    exit;
164}
165
166if ($opt->{show_config})
167{
168    show_config();
169    exit;
170}
171
172if ($opt->{enable})
173{
174    enable($opt->{enable});
175}
176
177if ($opt->{disable})
178{
179    disable($opt->{disable});
180}
181
182if ($opt->{setorder})
183{
184    set_order(0, $opt->{setorder}); 
185}
186
187if ($opt->{check})
188{
189    check();
190}
191
192if ($opt->{enable} or
193    $opt->{disable} or
194    $opt->{setorder} or
195    $opt->{check} or
196    $opt->{mirror})
197{
198    set_order(1) if $made_changes;
199    write_config_file() if $made_changes;
200    status();
201    exit;
202}
203
204# ---------------------------------------------------------------------------
205# --- Update
206# ---------------------------------------------------------------------------
207
208unless ($opt->{noupdate})
209{
210    update($progname, $version);
211    set_order(1) if $made_changes;
212    write_config_file() if (($made_changes) && (! $opt->{configure}))
213}
214
215if ($opt->{configure})
216{
217    configure();
218}
219
220# ---------------------------------------------------------------------------
221# --- Go!
222# ---------------------------------------------------------------------------
223
224unless ($opt->{update})
225{
226    calc_date_range();
227    grab_data();
228    reconcile_data();
229    postprocess_data();
230    output_data();
231}
232
233print "Done.\n";
234
235status();
236write_config_file();
237
238# ---------------------------------------------------------------------------
239# --- Subroutines
240# ---------------------------------------------------------------------------
241
242# -----------------------------------------
243# Subs: Grabbing
244# -----------------------------------------
245
246sub grab_data
247{
248    my $used_grabbers = 0;
249    my $found_data_percent = 0;
250
251    print "\nGrabber stage:\n";
252
253    my $grabber;
254   
255    while ($grabber = choose_grabber())
256    {
257        $used_grabbers++;
258
259        $components->{$grabber}->{lastdata} = time;
260        $components->{$grabber}->{laststatus} = "unknown";
261
262        printf "\nSHEPHERD: Using grabber: (%d) %s\n", $used_grabbers, $grabber;
263
264        my $output = "$CWD/grabbers/$grabber/output.xmltv";
265
266        my $comm = "$CWD/grabbers/$grabber/$grabber " .
267                   "--region $region " .
268                   "--channels_file $channels_file " .
269                   "--output $output";
270
271        # NOTE: ideally a grabber could be instructed to fetch partial data through --channel, --starttime & --endtime
272        # we don't have that for now so instead whenever there is missing data, ALL 7 days for all channels will be collected
273        # FIXME FUTURE: call grabbers just with what we want...
274        $comm .= " --days $days" if ($days);
275        $comm .= " --offset $opt->{offset}" if ($opt->{offset});
276        $comm .= " --debug" if ($debug);
277        $comm .= " @ARGV" if (@ARGV);
278
279        if ((defined $opt->{dontcallgrabbers}) && ($opt->{dontcallgrabbers})) {
280            printf "SHEPHERD: not calling grabber because of --dontcallgrabbers option, but will instead use existing $output\n";
281        } else {
282            print "SHEPHERD: Excuting command: $comm\n";
283            chdir "$CWD/grabbers/$grabber/";
284            system($comm);
285            chdir $CWD;
286        }
287
288        # soak up the data we just collected
289        &soak_up_data($grabber, $output, "grabber");
290        $components->{$grabber}->{laststatus} = $plugin_data->{$grabber}->{laststatus};
291
292        # check to see if we have all the data we want
293        $found_data_percent = &analyze_plugin_data($channel_ok_threshold_percent, "AGGREGATE GRABBER");
294
295        last if ($found_data_percent >= $channel_ok_threshold_percent);
296    }
297
298
299    if ($used_grabbers == 0)
300    {
301        print "No valid grabbers installed/enabled!\n";
302        return;
303    }
304
305    if ($found_data_percent < $channel_ok_threshold_percent)
306    {
307        print "SHEPHERD: Ran through ALL grabbers but still missing data!!! :(\n";
308        $grabber_data_percent = $found_data_percent;
309        return;
310    }
311}
312
313sub choose_grabber
314{
315    unless (defined $gscore)
316    {
317        foreach (query_grabbers())
318        {
319            unless ($components->{$_}->{disabled})
320            {
321                $gscore->{$_} = 0;
322            }
323        }
324    }
325
326    my $total = score_grabbers();
327
328    return undef unless ($total);
329
330    if ($debug)
331    {
332        print "Grabber selection probabilities:\n";
333        foreach (keys %$gscore)
334        {
335            printf "%15s %6.1f%% %12s\n", 
336                   $_, 100 * $gscore->{$_} / $total, "($gscore->{$_} pts)";
337        }
338    }
339
340    return undef unless (scalar keys %$gscore);
341
342    my $r = int(rand($total));
343#    print "Total score: $total.\nRand: $r.\n";
344
345    my $c = 0;
346    foreach (keys %$gscore)
347    {
348        next if (!$gscore->{$_});
349        if ($r >= $c and $r < ($c + $gscore->{$_}))
350        {
351            delete $gscore->{$_};
352            print "Selected $_.\n" if ($debug);
353            return $_;
354        }
355        $c += $gscore->{$_};
356    }
357    die "ERROR: failed to choose grabber.";
358}
359
360sub score_grabbers
361{
362    my ($score, $total, $niceness, $granularity, $m);
363
364    my $missing = detect_missing_data();
365
366    foreach my $grabber (keys %$gscore)
367    {
368        # for each slot, say whether we can fill it or not -- that is,
369        # whether we support this channel and this day #.
370       
371        my $hits = 0;
372        foreach (@$missing)
373        {
374            my ($ch, $day) = split(/:/);
375            my $result = (can_support_channel($grabber, $ch)
376                          and
377                          can_support_day($grabber, $day));
378            $hits += $result;
379#           print "$grabber vs $ch:$day: " . ($result ? "OK" : "no") . "\n";
380        }
381        $niceness = $components->{$grabber}->{config}->{niceness};
382        unless ($niceness)
383        {
384            print "WARNING: Grabber $grabber has no niceness support " .
385                  "specified in config.\n";
386            $niceness = 5;
387        }
388        $granularity = $components->{$grabber}->{config}->{granularity};
389        unless (defined $granularity)
390        {
391            print "WARNING: Grabber $grabber has no granularity support " .
392                "specified in config.\n";
393            $granularity = '';
394        }
395        # TODO: use granularity more intelligently ('c' vs 'd') -- Max.
396        $granularity = length ($granularity);
397        my $total_channeldays = $days * scalar (keys %$channels);
398        $granularity *= int((($total_channeldays - 1 ) / scalar(@$missing))/2);
399
400        $score = $hits * ($niceness + $granularity);
401        print "Grabber $grabber can fill $hits empty slots with $niceness niceness and $granularity granularity: scoring $score pts.\n";
402        $gscore->{$grabber} = $score;
403        $total += $score;
404    }
405    return $total;
406}
407
408sub can_support_channel
409{
410    my ($grabber, $ch) = @_;
411
412    my $channels_supported = $components->{$grabber}->{config}->{channels};
413    unless (defined $channels_supported)
414    {
415        print "WARNING: Grabber $grabber has no channel support " .
416              "specified in config.\n";
417        $channels_supported = '';
418    }
419
420    return 1 unless ($channels_supported); # Empty string means we support all
421   
422    my $match = ($channels_supported =~ /\b$ch\b/);
423#    $match ||= 0;
424    my $exceptions = ($channels_supported =~/^-/);
425#    $exceptions ||= 0;
426#       print "M: " . Dumper ($match) . "E:" . Dumper ($exceptions) . "\n";
427#    print "Can $grabber support channel $ch: " . ($match != $exceptions ? 1 : 0) .
428        #      " (match $match, exceptions: $exceptions).\n";
429    return ($match != $exceptions);
430}
431
432sub can_support_day
433{
434    my ($grabber, $day) = @_;
435
436    my $days_supported = $components->{$grabber}->{config}->{max_days};
437    unless ($days_supported)
438    {
439        print "WARNING: Grabber $grabber has no max_days support " .
440              "specified in config.\n";
441        $days_supported = 2;
442    }
443#    print "Can $grabber support day $day: " . ($day <= $days_supported) . ".\n";
444    return $day <= $days_supported;
445}
446
447#
448# Build a little hash of what channel/day data we're currently missing.
449# I think granularity of one day is good for now; could possibly be
450# made more fine-grained if we think grabbers will support that.
451#
452sub detect_missing_data
453{
454    my @missing;
455
456    my $timeslots_per_day = (24 * 60 * 60) / $timeslot_size;
457
458    foreach my $ch (keys %$channels)
459    {
460        if (defined $channel_data->{$ch})
461        {
462            my $slotnum;
463            for ($slotnum = 0; $slotnum < $num_timeslots-1; $slotnum++) 
464            {
465                if (!@{$channel_data->{$ch}->{timeslots}}[$slotnum])
466                {
467                    my $day = int($slotnum / $timeslots_per_day) + 1;
468                    push @missing, "$ch:$day";
469                    $slotnum += $timeslots_per_day -
470                                ($slotnum % $timeslots_per_day);
471
472                }
473            }
474        }
475        else
476        {
477            for my $i (1 .. $days)
478            {
479                push (@missing, "$ch:$i");
480            }
481        }
482
483    }
484
485    print "Need data for @missing.\n" if ($debug);
486    return \@missing;
487}
488
489
490# interpret xmltv data from this grabber/postprocessor
491sub soak_up_data
492{
493    my ($plugin, $output, $plugintype) = @_;
494
495    if (! -r $output) {
496        printf "SHEPHERD: Warning: plugin '%s' output file '%s' does not exist\n",$plugin,$output;
497        return;
498    }
499
500    my $parse_start_time = [gettimeofday];
501    printf STDERR "SHEPHERD: Started parsing XMLTV from '%s' in '%s' .. any errors below are from parser:\n",$plugin,$output;
502    eval { $plugin_data->{$plugin}->{xmltv} = XMLTV::parsefiles($output); };
503    printf STDERR "SHEPHERD: Completed XMLTV parsing from '%s' in %0.2f seconds\n",$plugin,tv_interval($parse_start_time);
504
505    if (defined $plugin_data->{$plugin}->{xmltv}) {
506        $plugin_data->{$plugin}->{valid} = 1;
507
508        my $xmltv = $plugin_data->{$plugin}->{xmltv};
509        my ($encoding, $credits, $chan, $progs) = @$xmltv;
510        $plugin_data->{$plugin}->{total_duration} = 0;
511        $plugin_data->{$plugin}->{programmes} = 0;
512
513        my $strptime = new DateTime::Format::Strptime( pattern => "%Y%m%d%H%M %z");
514        my $alt_strptime = new DateTime::Format::Strptime( pattern => "%Y%m%d%H%M"); # alternate format 1: oztivo doesn't seem to output timezone
515        my $seen_channels_with_data = 0;
516
517        # iterate thru channels
518        foreach my $ch (sort keys %{$channels}) {
519            my $seen_progs_on_this_channel = 0;
520
521            # iterate thru programmes per channel
522            foreach my $prog (@$progs) {
523                next if ($prog->{channel} ne $channels->{$ch});
524
525                my $t1 = $strptime->parse_datetime($prog->{start});
526                $t1 = $alt_strptime->parse_datetime($prog->{start}) if (!$t1);
527
528                my $t2 = $strptime->parse_datetime($prog->{stop});
529                $t2 = $alt_strptime->parse_datetime($prog->{stop}) if (!$t2);
530
531                next if (!$t1 || !$t2); # if we can't parse stop/start then clearly THIS data is bunk!
532
533                # store t1 and t2 times in the xmltv data for later on (shh.. ton't tell anyone..)
534                $prog->{start_epoch} = $t1->epoch;
535                $prog->{stop_epoch} = $t2->epoch;
536
537                # store plugin-specific stats
538                $plugin_data->{$plugin}->{programmes}++;
539                $plugin_data->{$plugin}->{total_duration} += ($t2->epoch - $t1->epoch);
540                $seen_progs_on_this_channel++;
541                $plugin_data->{$plugin}->{earliest_data_seen} = $t1->epoch if (!defined $plugin_data->{$plugin}->{earliest_data_seen});
542                $plugin_data->{$plugin}->{earliest_data_seen} = $t1->epoch if ($t1->epoch < $plugin_data->{$plugin}->{earliest_data_seen});
543                $plugin_data->{$plugin}->{latest_data_seen} = $t2->epoch if (!defined $plugin_data->{$plugin}->{latest_data_seen});
544                $plugin_data->{$plugin}->{latest_data_seen} = $t2->epoch if ($t2->epoch > $plugin_data->{$plugin}->{latest_data_seen});
545
546                # store channel-specific stats
547                $channel_data->{$ch}->{programmes}++;
548                $channel_data->{$ch}->{total_duration} += ($t2->epoch - $t1->epoch);
549
550                # store timeslot info
551                next if ($t1->epoch > $endtime);        # programme starts after timeslots we are interested .. nice that we have it ... but we really don't care about it!
552                next if ($t2->epoch < $starttime);      # programme ends  before timeslots we are interested .. nice that we have it ... but we really don't care about it!
553                my $start_slotnum;
554                if ($t1->epoch >= $starttime) {
555                    $start_slotnum = int(($t1->epoch - $starttime) / $timeslot_size);
556                } else {
557                    $start_slotnum = 0;
558                }
559                my $end_slotnum;
560                if ($t2->epoch < $endtime) {
561                    $end_slotnum = int(($t2->epoch - $starttime) / $timeslot_size);
562                } else {
563                    $end_slotnum = ($num_timeslots-1);
564                }
565
566                # add this programme into the global timeslots table for this channel
567                foreach my $slotnum ($start_slotnum..$end_slotnum) {
568                    $channel_data->{$ch}->{timeslots}[$slotnum]++;
569                }
570            }
571
572            $seen_channels_with_data++ if ($seen_progs_on_this_channel > 0);
573        }
574
575        # print some stats about what we saw!
576        printf "SHEPHERD: %s '%s' returned data for %d channels, %d programmes, %dd%02dh%02dm%02ds duration, %s%s\n",
577            ucfirst($plugintype), $plugin, $seen_channels_with_data, $plugin_data->{$plugin}->{programmes},
578            int($plugin_data->{$plugin}->{total_duration} / 86400),             # days
579            int(($plugin_data->{$plugin}->{total_duration} % 86400) / 3600),    # hours
580            int(($plugin_data->{$plugin}->{total_duration} % 3600) / 60),       # mins
581            int($plugin_data->{$plugin}->{total_duration} % 60),                # sec
582            (defined $plugin_data->{$plugin}->{earliest_data_seen} ? (strftime "%a %e %b %H:%M - ", localtime($plugin_data->{$plugin}->{earliest_data_seen})) : 'no data'),
583            (defined $plugin_data->{$plugin}->{latest_data_seen} ? (strftime "%a %e %b %H:%M", localtime($plugin_data->{$plugin}->{latest_data_seen})) : '');
584        $plugin_data->{$plugin}->{laststatus} = sprintf "%dch/%dpr/%dhrs %s-%s",
585            $seen_channels_with_data, $plugin_data->{$plugin}->{programmes},
586            int($plugin_data->{$plugin}->{total_duration} / 3600),
587            (defined $plugin_data->{$plugin}->{earliest_data_seen} ? (strftime "%a%d%b%H:%M", localtime($plugin_data->{$plugin}->{earliest_data_seen})) : 'no'),
588            (defined $plugin_data->{$plugin}->{latest_data_seen} ? (strftime "%a%d%b%H:%M", localtime($plugin_data->{$plugin}->{latest_data_seen})) : 'data');
589
590    } else {
591        printf "WARNING: Plugin %s didn't seem to return any valid XMLTV!\n",$plugin;
592        delete $plugin_data->{$plugin}->{valid};
593    }
594}
595
596
597# analyze grabber data - do we have all the data we want?
598# returns percent of data found
599sub analyze_plugin_data
600{
601    my ($threshold,$analysistype) = @_;
602    my $total_data_percent = 0, my $total_channels = 0;
603    my $statusstring = "";
604
605    # iterate across each channel
606    foreach my $ch (sort keys %{$channels}) {
607        $total_channels++;
608        if (defined $channel_data->{$ch}) {
609            my $data_in_channel = 0;
610            for my $slotnum (0..($num_timeslots-1)) {
611                $data_in_channel++ if ((defined $channel_data->{$ch}->{timeslots}[$slotnum]) && ($channel_data->{$ch}->{timeslots}[$slotnum] > 0));
612            }
613
614            # do we have enough data for this channel?
615            my $data_in_channel_percent = $data_in_channel / ($num_timeslots-1) * 100;
616            if ($data_in_channel_percent >= $threshold) {
617                $statusstring .= sprintf "%s: %0.1f%% [complete], ",$ch,$data_in_channel_percent;
618            } else {
619                $statusstring .= sprintf "%s: %0.1f%% [hungry], ",$ch,$data_in_channel_percent;
620            }
621            $total_data_percent += $data_in_channel_percent;
622        } else {
623            $statusstring .= sprintf "%s: 0%% [starving], ",$ch;
624        }
625    }
626
627    if ($total_channels > 0) {
628        $total_data_percent = $total_data_percent / $total_channels;
629    } else {
630        $total_data_percent = 0;
631    }
632
633    # print some stats about what our analysis says!
634    printf "SHEPHERD: %s ANALYSIS: %sTOTAL %0.2f%% %s %0.2f%%: %s\n",
635        uc($analysistype), $statusstring, $total_data_percent,
636        ($total_data_percent >= $channel_ok_threshold_percent ? ">" : "<"), $channel_ok_threshold_percent,
637        (($total_data_percent < $channel_ok_threshold_percent) ? "WANT MORE DATA" : "COMPLETE");
638    return $total_data_percent;
639}
640
641
642# work out date range we are expecting data to be in
643sub calc_date_range
644{
645    # normalize starttime to beginning of hour
646    my $now = time;
647    my ($sec,$min,@rest) = localtime($now);
648
649    $starttime = $now - ((60 * $min) + $sec);
650
651    if ($days) {
652        $endtime = $starttime + ($days * 86400);
653    } else {
654        $endtime = $starttime + (7*86400);
655    }
656    $starttime += (86400 * $opt->{offset}) if ($opt->{offset});
657
658    $num_timeslots = ($endtime - $starttime) / $timeslot_size;
659}
660
661# -----------------------------------------
662# Subs: Reconciling data
663# -----------------------------------------
664
665# for all the data we have, try to pick the best bits!
666sub reconcile_data
667{
668    printf "\nReconciling data:\n\n";
669
670    my @proglist = [ ];
671    my @position_pointer = [ ];
672    my @grabber_order = [ ];
673    my $num_grabbers = 0;
674    my $pref_order;
675
676    printf "Preference for whose data we prefer as follows:\n";
677    foreach my $proggy (sort { $components->{$a}->{order} <=> $components->{$b}->{order} } query_grabbers()) {
678        if ((!$components->{$proggy}->{disabled}) && ($plugin_data->{$proggy}) && ($plugin_data->{$proggy}->{valid})) {
679            $grabber_order[$num_grabbers] = $proggy;
680            my $orig_prog = $plugin_data->{$proggy}->{xmltv}->[3];
681            my $prognum = 0;
682            foreach my $new_prog (sort order_channel_time @{$orig_prog}) {
683                $proglist[$num_grabbers]->[$prognum] = $new_prog;
684                $prognum++;
685            }
686
687            printf "  %d. %s (%d programmes)\n",($num_grabbers+1),$proggy,$prognum;
688            $num_grabbers++;
689        }
690    }
691
692    my %writer_args = ( encoding => 'ISO-8859-1' );
693    my $fh = new IO::File(">$input_postprocess_file") || die "can't open outputfile $input_postprocess_file: $!";
694    $writer_args{OUTPUT} = $fh;
695    my $writer = new XMLTV::Writer(%writer_args);
696
697    $writer->start({'source-info-url' => "about:blank", 'source-info-name' => "$progname $version", 'generator-info-name' => "$progname $version"} );
698
699    for my $ch (sort keys %$channels) {
700        $writer->write_channel({'display-name' => [[ $ch, "en" ]], 'id' => $channels->{$ch}} );
701    }
702
703    for my $ch (sort keys %$channels) {
704        printf "Reconciling channel: %s (%s)\n",$ch,$channels->{$ch};
705
706        #
707        # 1. position pointers to first piece of data for this channel
708        #
709
710        printf "REC#1: processing channel %s\n",$channels->{$ch} if $recdebug;
711        my $position_pointer;
712        for (my $i=0; $i < $num_grabbers; $i++) {
713            $position_pointer[$i] = 0;
714            while ((defined $proglist[$i]->[($position_pointer[$i])]) && ($proglist[$i]->[($position_pointer[$i])]->{'channel'} ne $channels->{$ch})) {
715                $position_pointer[$i]++;
716            }
717            if (!defined $proglist[$i]->[($position_pointer[$i])]) {
718                $position_pointer[$i] = -1;
719                printf "REC#1: no programmes found for channel %s from gradder %d\n",$channels->{$ch},$i if $recdebug;
720            } else {
721                printf "REC#1: advanced position_pointer to %d for grabber %d (first programme is \"%s\", start %d, stop %d)\n",
722                    $position_pointer[$i],$i,${XMLTV::best_name($langs,$proglist[$i]->[($position_pointer[$i])]->{title})}[0],
723                    $proglist[$i]->[($position_pointer[$i])]->{start_epoch},$proglist[$i]->[($position_pointer[$i])]->{stop_epoch} if $recdebug;
724            }
725        }
726
727        my $all_done_on_this_channel;
728        do {
729            #
730            # 2. find 'earliest' programme from all the choices
731            #
732
733            $all_done_on_this_channel = 1; # unless proven otherwise
734            my $earliest_programme_time = undef;
735            my $earliest_programme_slot = undef;
736            for (my $i=0; $i < $num_grabbers; $i++) {
737                next if ($position_pointer[$i] == -1); # skip if no programmes on this channel from this grabber
738                my $this_programme = $proglist[$i]->[($position_pointer[$i])];
739
740                if ((!defined $this_programme) || (!defined $this_programme->{title}) || ($this_programme->{channel} ne $channels->{$ch})) {
741                    # no more programmes on this channel for this grabber!
742                    printf "REC#2: no more programmes on grabber %d for this channel\n",$i if $recdebug;
743                    $position_pointer[$i] = -1;
744                } else {
745                    if ((!defined $earliest_programme_time) || ($earliest_programme_time > $this_programme->{'start_epoch'})) {
746                        $earliest_programme_time = $this_programme->{'start_epoch'};
747                        $earliest_programme_slot = $i;
748                        printf "REC#2: earliest programme (so far) on grabber %d, start %d (end %d) programme \"%s\"\n",
749                            $i,$this_programme->{start_epoch},$this_programme->{stop_epoch},${XMLTV::best_name($langs,$this_programme->{title})}[0] if $recdebug;
750                    } else {
751                        printf "REC#2:    programme on grabber %d was not earlier start %d (end %d) programme \"%s\"\n",
752                            $i,$this_programme->{start_epoch},$this_programme->{stop_epoch},${XMLTV::best_name($langs,$this_programme->{title})}[0] if $recdebug;
753                    }
754                }
755            }
756            if (!defined $earliest_programme_slot) {
757                # no programmes available on ANY grabber for this channel, skip this channel
758                printf "REC#2: no programmes on any grabbers for channel %s, skipping this channel\n",$channels->{$ch} if $recdebug;
759            } else {
760                #
761                # 3a. compare how many programmes on other grabbers overlap with it
762                # TODO (FUTURE): enhance this to do "majority voting" acrosa all grabbers based on identical start/stop
763                # TODO (FUTURE): where star/stop times match exactly but title names dont, record the mapping for known-as_to_most-preferred-title so we can use this in future transformations
764
765                my $preferred_programme = $proglist[$earliest_programme_slot]->[($position_pointer[$earliest_programme_slot])];
766                my $startpoint = $preferred_programme->{'start_epoch'};
767                my $stoppoint = $preferred_programme->{'stop_epoch'};
768                my $duration = $stoppoint - $startpoint;
769                my $extraduration = 0;
770                $extraduration = int($duration * ($reclogic{compare_overlapping_programmes_extra_overtime_duration_percent}/100)) if ($reclogic{compare_overlapping_programmes_extra_overtime_duration_percent} > 0);
771                $extraduration = $reclogic{compare_overlapping_programmes_extra_overtime_max} if ($extraduration > $reclogic{compare_overlapping_programmes_extra_overtime_max}); # upper limit
772                $stoppoint += $extraduration;
773                printf "REC#3: comparing other grabbers to see how many programmes fit in timeslot %d to %d (%d+%d)\n",$startpoint,$stoppoint,$duration,$extraduration if $recdebug;
774
775                my $max_progs_found = 0;
776                my $max_progs_slot = undef;
777                for (my $i=0; $i < $num_grabbers; $i++) {
778                    next if ($i == $earliest_programme_slot);
779                    next if ($position_pointer[$i] == -1);
780                    my $position_offset = 0;
781                    my $progs_found = 0;
782
783                    while ((defined $proglist[$i]->[($position_pointer[$i]+$position_offset)]) &&
784                           ($proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'channel'} eq $channels->{$ch}) &&
785                           ($proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start_epoch'} >= $startpoint) &&
786                           ($proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'stop_epoch'} <= $stoppoint)) {
787                        my $this_prog_duration = $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'stop_epoch'} - $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start_epoch'};
788
789                        printf "REC#3a.  programme on grabber %d matched (start %d end %d), \"%s\"%s\n", $i,
790                            $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start_epoch'},
791                            $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'stop_epoch'},
792                            ${XMLTV::best_name($langs,$proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'title'})}[0],
793                            ($this_prog_duration <= $reclogic{min_time_override_for_duplicate} ? 
794                            ", but ignored because of min_time_override_for_duplicate ($reclogic{min_time_override_for_duplicate} sec)" : "") if $recdebug;
795
796                        $progs_found++ if ($this_prog_duration > $reclogic{min_time_override_for_duplicate});
797                        $position_offset++;
798                    }
799
800                    printf "REC#3a:  %d programmes on grabber %d within timeslot\n",$progs_found,$i if $recdebug;
801                    if ($progs_found > $max_progs_found) {
802                        $max_progs_found = $progs_found;
803                        $max_progs_slot = $i;
804                    }
805                }
806
807                # 3b. if there are 2 or more programmes on other channels, use those - otherwise use this one
808                if ((!defined $max_progs_slot) || ($max_progs_found <= 1)) {
809                    printf "REC#3b: no grabbers with more programmes in timeslot found\n" if $recdebug;
810                } else {
811                    printf "REC#3b: grabber %d has %d programmes between %d and %d - using THAT grabber as our preference now!\n",
812                        $max_progs_slot,$max_progs_found,$startpoint,$stoppoint if $recdebug;
813                    $earliest_programme_slot = $max_progs_slot;
814                }
815
816                #
817                # 4. populate our "reconciled" programme list with the programming chosen
818                #
819
820                my $chosen_prog = $proglist[$earliest_programme_slot]->[($position_pointer[$earliest_programme_slot])];
821                my $chosen_prog_name = ${XMLTV::best_name($langs,$chosen_prog->{'title'})}[0];
822                $startpoint = $chosen_prog->{'start_epoch'};
823                $stoppoint = $chosen_prog->{'stop_epoch'};
824                my $new_prog_entry = $chosen_prog;
825
826                printf "REC#4: chosen programme is from grabber %d: start %d, end %d, duration %d: \"%s\"\n",
827                    $earliest_programme_slot,$startpoint,$stoppoint,($stoppoint-$startpoint),$chosen_prog_name if $recdebug;
828
829                #
830                # 5a. see if we have it duplicated from multiple grabbers, first with exact match
831                # 5b. then with fuzz -/+ 5 mins max, -/+ 2.5mins for programmes <= 15 mins
832               
833                my $start1, my $start2, my $stop1, my $stop2;
834
835                if (($stoppoint - $startpoint) <= $reclogic{duplicate_programme_augment_data_short_cutoff}) {
836                    $start1 = $startpoint - $reclogic{duplicate_programme_augment_data_short_duration_threshold};
837                    $start2 = $startpoint + $reclogic{duplicate_programme_augment_data_short_duration_threshold};
838                    $stop1 = $stoppoint - $reclogic{duplicate_programme_augment_data_short_duration_threshold};
839                    $stop2 = $stoppoint + $reclogic{duplicate_programme_augment_data_short_duration_threshold};
840                } else {
841                    $start1 = $startpoint - $reclogic{duplicate_programme_augment_data_long_duration_threshold};
842                    $start2 = $startpoint + $reclogic{duplicate_programme_augment_data_long_duration_threshold};
843                    $stop1 = $stoppoint - $reclogic{duplicate_programme_augment_data_long_duration_threshold};
844                    $stop2 = $stoppoint + $reclogic{duplicate_programme_augment_data_long_duration_threshold};
845                }
846                if ($start2 >= $stop1) {
847                    $start2 = $startpoint;
848                    $stop1 = $stoppoint;
849                }
850
851                printf "REC#5a: looking in other grabbers for matching programmes within timeslot start %d and end %d (%d)\n",$startpoint,$stoppoint,($stoppoint-$startpoint) if $recdebug;
852                for (my $i=0; $i < $num_grabbers; $i++) {
853                    next if ($i == $earliest_programme_slot);
854                    next if ($position_pointer[$i] == -1);
855                    if ((defined $proglist[$i]->[($position_pointer[$i])]) &&
856                        ($proglist[$i]->[($position_pointer[$i])]->{'channel'} eq $channels->{$ch}) &&
857                        ($proglist[$i]->[($position_pointer[$i])]->{'start_epoch'} == $startpoint) &&
858                        ($proglist[$i]->[($position_pointer[$i])]->{'stop_epoch'} == $stoppoint)) {
859                        # winner .. matches our criteria ...
860                        my $match_prog = $proglist[$i]->[($position_pointer[$i])];
861                        my $match_prog_name = ${XMLTV::best_name($langs,$match_prog->{'title'})}[0];
862
863                        printf "REC#5a:   found programme on grabber %d: start %d, end %d: \"%s\"\n", $i,
864                            $match_prog->{'start_epoch'},$match_prog->{'stop_epoch'},$match_prog_name if $recdebug;
865
866                        if ($chosen_prog_name ne $match_prog_name) {
867                            # names differ - save it in our translation table for future reference!
868                            $title_translation_table->{$grabber_order[$i]}->{$match_prog_name} = $chosen_prog_name;
869                            printf "REC#5a: title-translation: higher-preference grabber '%s' called programme \"%s\" compared to '%s' calling it \"%s\"\n",
870                                $grabber_order[$earliest_programme_slot],$chosen_prog_name,$grabber_order[$i],$chosen_prog_name if $recdebug;
871                        }
872
873                        foreach my $field (keys %{$match_prog}) {
874                            next if ($field eq "start_epoch");
875                            next if ($field eq "stop_epoch");
876                            if (!defined $new_prog_entry->{$field}) {
877                                printf "REC#5a:      adding field \"%s\"\n",$field if $recdebug;
878                                $new_prog_entry->{$field} = $match_prog->{$field};
879                                # TODO (FUTURE): should we add to programme description to say where we got what data from?
880                            }
881                        }
882                    }
883                }
884
885                printf "REC#5b: looking in other grabbers for matching programmes within timeslot start %d-%d (%d) and end %d-%d (%d)\n",
886                    $start1,$start2,($start2-$start1),$stop1,$stop2,($stop2-$stop1) if $recdebug;
887
888                for (my $i=0; $i < $num_grabbers; $i++) {
889                    next if ($i == $earliest_programme_slot);
890                    next if ($position_pointer[$i] == -1);
891
892                    if ((defined $proglist[$i]->[($position_pointer[$i])]) &&
893                        ($proglist[$i]->[($position_pointer[$i])]->{'channel'} eq $channels->{$ch}) &&
894                        ($proglist[$i]->[($position_pointer[$i])]->{'start_epoch'} >= $start1) &&
895                        ($proglist[$i]->[($position_pointer[$i])]->{'start_epoch'} < $start2) &&
896                        ($proglist[$i]->[($position_pointer[$i])]->{'stop_epoch'} >= $stop1) &&
897                        ($proglist[$i]->[($position_pointer[$i])]->{'stop_epoch'} < $stop2)) {
898                        # winner .. matches our criteria ...
899                        my $match_prog = $proglist[$i]->[($position_pointer[$i])];
900
901                        printf "REC#5b:   found programme on grabber %d: start %d, end %d: \"%s\"\n", $i,
902                            $match_prog->{'start_epoch'},$match_prog->{'stop_epoch'},
903                            ${XMLTV::best_name($langs,$match_prog->{'title'})}[0] if $recdebug;
904
905                        foreach my $field (keys %{$match_prog}) {
906                            # 5b. pick fields from each one in order of our preferences
907                            next if ($field eq "start_epoch");
908                            next if ($field eq "stop_epoch");
909                            if (!defined $new_prog_entry->{$field}) {
910                                printf "REC#5b:      adding field \"%s\"\n",$field if $recdebug;
911                                $new_prog_entry->{$field} = $match_prog->{$field};
912                                # TODO (FUTURE): should we add to programme description to say where we got what data from?
913                            }
914                        }
915                    }
916                }
917
918                #
919                # 6.  write out new entry
920                #
921
922                printf "REC#6: writing out programme entry\n" if $recdebug;
923                &cleanup($new_prog_entry);
924
925                # scrub programme for known bogosities
926
927                # oztivo typically inserts blank 'director' details into 'credits' .. scrub them
928                if ((defined $new_prog_entry->{'credits'}) &&
929                    (defined $new_prog_entry->{'credits'}->{'director'}) &&
930                    (defined $new_prog_entry->{'credits'}->{'director'}->[0])) {
931                    my @director_list = $new_prog_entry->{'credits'}->{'director'}->[0];
932                    for my $i (0 .. $#director_list) {
933                        delete $new_prog_entry->{'credits'}->{'director'}->[$i] if ((defined $director_list[$i]) && ($director_list[$i] eq ""));
934                    }
935                }
936
937                # want to keep epoch start/stop for our own processing, but stop XMLTV whining about it in write_programme
938                # so temporarily remove them & reinsert them back afterwards
939                my ($orig_start_epoch,$orig_end_epoch) = ($new_prog_entry->{'start_epoch'},$new_prog_entry->{'stop_epoch'});
940                delete $new_prog_entry->{'start_epoch'};
941                delete $new_prog_entry->{'stop_epoch'};
942
943                # write out
944                $writer->write_programme($new_prog_entry);
945                ($new_prog_entry->{'start_epoch'},$new_prog_entry->{'stop_epoch'}) = ($orig_start_epoch,$orig_end_epoch);
946
947                # 7a. remove all programmes that end before this endtime
948                for (my $i=0; $i < $num_grabbers; $i++) {
949                    next if ($position_pointer[$i] == -1);
950                    while ((defined $proglist[$i]->[($position_pointer[$i])]) &&
951                           ($proglist[$i]->[($position_pointer[$i])]->{'channel'} eq $channels->{$ch}) &&
952                           ($proglist[$i]->[($position_pointer[$i])]->{'stop_epoch'} <= $stoppoint)) {
953                        printf "REC#7a: removing programme on grabber %d slot %d since it ends before inserted start: start %d end %s: \"%s\"\n",
954                            $i, $position_pointer[$i],
955                            $proglist[$i]->[($position_pointer[$i])]->{'start_epoch'},
956                            $proglist[$i]->[($position_pointer[$i])]->{'stop_epoch'},
957                            ${XMLTV::best_name($langs,$proglist[$i]->[($position_pointer[$i])]->{'title'})}[0] if $recdebug;
958                        delete $proglist[$i]->[($position_pointer[$i])];
959                        $position_pointer[$i]++;
960                    }
961                }
962
963                # 7b. adjust starttimes of any programmes to match endtime (with fuzz of +5 mins max)
964                for (my $i=0; $i < $num_grabbers; $i++) {
965                    next if ($position_pointer[$i] == -1);
966                    my $position_offset = 0;
967                    while ((defined $proglist[$i]->[($position_pointer[$i]+$position_offset)]) &&
968                           ($proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'channel'} eq $channels->{$ch}) &&
969                           ($proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start_epoch'} < $stoppoint)) {
970                        my $this_prog = $proglist[$i]->[($position_pointer[$i]+$position_offset)];
971                        if (($this_prog->{'start_epoch'} + $reclogic{readjust_starttime_for_nonmatched_programmes}) >= $stoppoint) {
972                            printf "REC#7b: adjusting starttime on grabber %d slot %d since it starts <5mins before inserted end:\n",
973                                $i,($position_pointer[$i]+$position_offset) if $recdebug;
974                            printf "REC#7b:    orig: start %d end %d, now: start %d end %d: \"%s\"\n",
975                                $this_prog->{'start_epoch'}, $this_prog->{'stop_epoch'}, $stoppoint, $this_prog->{'stop_epoch'},
976                                ${XMLTV::best_name($langs,$this_prog->{'title'})}[0] if $recdebug;
977                            $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start_epoch'} = $stoppoint;
978                            $proglist[$i]->[($position_pointer[$i]+$position_offset)]->{'start'} = sprintf "%s",(strftime "%Y%m%d%H%M", localtime($stoppoint));
979                            $position_offset++;
980                        } else {
981                            printf "REC#7b: removing grabber %d slot %d programme because it started too long before chosen programme: start %d end %d: \"%s\"\n",
982                                $i, ($position_pointer[$i]+$position_offset), $this_prog->{'start_epoch'}, $this_prog->{'stop_epoch'},
983                                ${XMLTV::best_name($langs,$this_prog->{'title'})}[0] if $recdebug;
984                            $position_pointer[$i]++;
985                        }
986                    }
987                }
988            }
989
990            # 8. check that we still have at least one pointer on current channel
991            for (my $i=0; $i < $num_grabbers; $i++) {
992                next if ($position_pointer[$i] == -1);
993                printf "REC#8: grabber %d is now at slot %d\n",$i,$position_pointer[$i] if $recdebug;
994                if ((defined $proglist[$i]->[($position_pointer[$i])]) &&
995                    ($proglist[$i]->[($position_pointer[$i])]->{'channel'} eq $channels->{$ch})) {
996                    $all_done_on_this_channel = 0;
997                    printf "REC#8:   grabber %d is at slot %d is still on channel \"%s\"\n",$i,$position_pointer[$i],$channels->{$ch} if $recdebug;
998                }
999            }
1000            printf "REC#9:\n" if $recdebug;
1001        } until ($all_done_on_this_channel);
1002    }
1003    $writer->end();
1004}
1005
1006# sorting helper routine - sort by channel then by start-time
1007sub order_channel_time {
1008        my $chanresult = $a->{channel} cmp $b->{channel};
1009        return $chanresult if ($chanresult != 0);
1010        return ($a->{start_epoch} <=> $b->{start_epoch});
1011}
1012
1013# descend a structure and clean up various things, including stripping
1014# leading/trailing spaces in strings, translations of html stuff etc
1015#   -- taken & modified from Michael 'Immir' Smith's excellent tv_grab_au
1016my %amp;
1017BEGIN { %amp = ( nbsp => ' ', qw{ amp & lt < gt > apos ' quot " } ) }
1018
1019sub cleanup {
1020    my $x = shift;
1021    if    (ref $x eq "REF")   { cleanup($_) }
1022    elsif (ref $x eq "HASH")  { cleanup(\$_) for values %$x }
1023    elsif (ref $x eq "ARRAY") { cleanup(\$_) for @$x }
1024    elsif (defined $$x) {
1025        $$x =~ s/&(#(\d+)|(.*?));/ $2 ? chr($2) : $amp{$3}||' ' /eg; # scrub html
1026        # $$x =~ s/[^\x20-\x7f]/ /g;    # disabled (we want to keep non-std chars)
1027        $$x =~ s/(^\s+|\s+$)//g;        # strip leading/trailing spaces
1028    }
1029}
1030
1031# -----------------------------------------
1032# Subs: Postprocessing
1033# -----------------------------------------
1034
1035sub postprocess_data
1036{
1037    # for our first postprocessor, we feed it ALL of the XMLTV files we have
1038    # as each postprocessor runs, we feed in the output from the previous one
1039    # Shepherd checks the "completeness" of the data that comes out of a postprocessor & automatically
1040    # reverts back to the previous postprocessor if it was shown to be bad
1041
1042    # first time around: feed in reconciled data ($input_postprocess_file)
1043
1044    printf "\nPostprocessing stage:\n";
1045
1046    foreach my $postprocessor (sort { $components->{$a} <=> $components->{$b} } query_postprocessors()) {
1047        next if ($components->{$postprocessor}->{disabled});
1048        next if (!$components->{$postprocessor}->{ready});
1049
1050        $components->{$postprocessor}->{lastdata} = time;
1051        $components->{$postprocessor}->{laststatus} = "unknown";
1052
1053        printf "\nSHEPHERD: Using postprocessor: %s\n",$postprocessor;
1054
1055        my $output = "$CWD/postprocessors/$postprocessor/output.xmltv";
1056        my $comm = "$CWD/postprocessors/$postprocessor/$postprocessor " .
1057                   "--region $region " .
1058                   "--channels_file $channels_file " .
1059                   "--output $output";
1060        $comm .= " --days $days" if ($days);
1061        $comm .= " --offset $opt->{offset}" if ($opt->{offset});
1062        $comm .= " --debug" if ($debug);
1063        $comm .= " @ARGV" if (@ARGV);
1064        $comm .= " $input_postprocess_file";
1065        print "SHEPHERD: Excuting command: $comm\n";
1066
1067        chdir "$CWD/postprocessors/$postprocessor/";
1068        system($comm);
1069        chdir $CWD;
1070
1071        #
1072        # soak up the data we just collected and check it
1073        # YES - these are the SAME routines we used in the previous 'grabber' phase
1074        # but the difference here is that we clear out our 'channel_data' beforehand
1075        # so we can independently analyze the impact of this postprocessor.
1076        # if it clearly returns bad data, don't use that data (go back one step) and
1077        # flag the postprocessor as having failed.  after 3 consecutive failures, disable it
1078        #
1079
1080        # clear out channel_data
1081        foreach my $ch (keys %{$channels}) {
1082            delete $channel_data->{$ch};
1083        }
1084
1085        # process and analyze it!
1086        &soak_up_data($postprocessor, $output, "postprocessor");
1087        my $found_data_percent = &analyze_plugin_data($postprocessor_ok_threshold_percent, "POSTPROCESSOR");
1088
1089        $components->{$postprocessor}->{laststatus} = $plugin_data->{$postprocessor}->{laststatus};
1090
1091        if ($found_data_percent < $postprocessor_ok_threshold_percent) {
1092            # how bad is the data?  is it significantly different to that of what the grabber run finished with?
1093            # allow at most 5% of the data to go away
1094            if ($grabber_data_percent > ($found_data_percent + 5)) {
1095                # urgh.  this postprocessor did a bad bad thing ...
1096                printf "SHEPHERD: XML data from postprocessor %s rejected, using XML from previous stage\n",$postprocessor;
1097
1098                if (defined $components->{$postprocessor}->{conescutive_failures}) {
1099                    $components->{$postprocessor}->{conescutive_failures}++;
1100                } else {
1101                    $components->{$postprocessor}->{conescutive_failures} = 1;
1102                }
1103                printf "SHEPHERD: Postprocessor \"%s\" has now failed %d times in a row.  %d more and it will be automatically disabled.\n",
1104                    $postprocessor,
1105                    $components->{$postprocessor}->{conescutive_failures},
1106                    ($postprocessor_disable_failure_threshold - $components->{$postprocessor}->{conescutive_failures});
1107
1108                if ($components->{$postprocessor}->{conescutive_failures} >= $postprocessor_disable_failure_threshold) {
1109                    printf "SHEPHERD: Disabling Postprocessor \"%s\".\n",$postprocessor;
1110                    $components->{$postprocessor}->{disabled} = 1;
1111                }
1112            } else {
1113                # accept what this postprocessor did to our output ...
1114                printf "SHEPHERD: accepting output from postprocessor %s, feeding it into next stage\n",$postprocessor;
1115                $input_postprocess_file = $output;
1116                delete $components->{$postprocessor}->{conescutive_failures} if (defined $components->{$postprocessor}->{conescutive_failures});
1117            }
1118        } else {
1119            # accept what this postprocessor did to our output ...
1120            printf "SHEPHERD: accepting output from postprocessor %s, feeding it into next stage\n",$postprocessor;
1121            $input_postprocess_file = $output;
1122            delete $components->{$postprocessor}->{conescutive_failures} if (defined $components->{$postprocessor}->{conescutive_failures});
1123        }
1124    }
1125}
1126
1127
1128sub output_data
1129{
1130    # $input_postprocess_file contains our final output
1131    # send it to whereever --output told us to!
1132
1133    my $output_filename = "$CWD/output.xmltv";
1134    $output_filename = $opt->{output} if ($opt->{output});
1135
1136    open(OUTFILE,">$output_filename") || die "could not open output file $output_filename for writing: $!\n";
1137
1138    if (!(open(INFILE,"<$input_postprocess_file"))) {
1139        printf "WARNING: could not open input file \"%s\": %s\n", $input_postprocess_file, $!;
1140        printf "Output XMLTV data may be damanged as a result!\n";
1141    } else {
1142        while (<INFILE>) {
1143            print OUTFILE $_;
1144        }
1145        close(INFILE);
1146        close(OUTFILE);
1147    }
1148
1149    printf "Final output stored in $output_filename.\n";
1150}
1151
1152# -----------------------------------------
1153# Subs: Updates & Installations
1154# -----------------------------------------
1155
1156sub update
1157{
1158    printf "\nChecking for updates:\n\n";
1159
1160    my $data = fetch_file("status");
1161
1162    return unless ($data);
1163
1164    my %clist = %$components;
1165    while ($data =~ /(.*):(.*):(.*)/g)
1166    {
1167        my ($proggy, $latestversion, $progtype) = ($1,$2,$3);
1168        update_component($proggy, $latestversion, $progtype);
1169        delete $clist{$proggy};
1170    }
1171
1172    # work out what components disappeared (if any)
1173    foreach (keys %clist) {
1174        unless ($components->{$_}->{disabled}) {
1175            print "\nDeleted component: $_.\n";
1176            disable($_);
1177            $made_changes = 1;
1178        }
1179    }
1180
1181}
1182
1183sub update_component
1184{
1185    my ($proggy, $latestversion, $progtype) = @_;
1186
1187    # handle new installs..
1188    if ($progtype eq "shepherd") {
1189        if(! -e "$CWD/$progname") {
1190            print "Missing: $CWD/$progname\n";
1191            install($progname, $latestversion, $progtype);
1192            return;
1193        }
1194    } else {
1195        if (!defined $components->{$proggy} or ! -e ($progtype . "s/$proggy/$proggy")) {
1196            print "New $progtype: $proggy.\n";
1197            install($proggy, $latestversion, $progtype);
1198            return;
1199        }
1200        if ($components->{$proggy}->{disabled}) {
1201            print "Warning: grabber $proggy disabled by config file.\n";
1202        }
1203    }
1204
1205    # upgrade/downgrades
1206    my $ver;
1207    if ($progtype eq "shepherd") {
1208        $ver = $version;
1209    }
1210    else {
1211        $ver = $components->{$proggy}->{ver};
1212    } 
1213
1214    my $result = versioncmp($ver, $latestversion);
1215    if ($result == -1) {
1216        print "Upgrading $proggy from v$ver to v$latestversion.\n";
1217    } elsif ($result == 1) {
1218        print "Downgrading $proggy from v$ver to v$latestversion.\n";
1219    } else {
1220        print "Already have latest version of $proggy: v$ver.\n";
1221        return;
1222    }
1223    install($proggy, $latestversion, $progtype);
1224}
1225
1226sub install
1227{
1228    my ($proggy, $latestversion, $progtype) = @_;
1229
1230    print "Downloading $proggy v$latestversion.\n";
1231
1232    my $rdir = "";
1233    my $ldir = $CWD;
1234    my $ver = "unknown";
1235
1236    if ($progtype eq "shepherd") {
1237        $ver = $version;
1238    } else {
1239        $rdir = $progtype . "s";
1240        $ldir = "$CWD/$progtype" . "s/$proggy";
1241        $ver = $components->{$proggy}->{ver} if ((defined $components->{$proggy}) && $components->{$proggy}->{ver});
1242        -d ("$CWD/$progtype" . "s") or mkdir ("$CWD/$progtype" . "s") or die "Cannot create directory $CWD/$progtype" . "s: $!";
1243    }
1244    -d $ldir or mkdir $ldir or die "Cannot create directory $ldir: $!";
1245
1246    my $newfile = "$ldir/$proggy-$latestversion";
1247    my $rfile = "$rdir/$proggy";
1248
1249    return unless (fetch_file($rfile, $newfile));
1250   
1251    # Fetch grabber config file
1252    $rfile .= ".conf";
1253    my $config = fetch_file($rfile);
1254    return unless ($config);
1255
1256    eval $config;
1257
1258    # Make component executable
1259    system('chmod u+x ' . $newfile);
1260
1261    -d $ARCHIVE_DIR or mkdir $ARCHIVE_DIR or die "Cannot create directory $ARCHIVE_DIR: $!";
1262
1263    if (-e "$ldir/$proggy")
1264    {
1265        rename("$ldir/$proggy", "$ARCHIVE_DIR/$proggy-$ver");
1266    }
1267    rename($newfile, "$ldir/$proggy");
1268   
1269    print "Installed $proggy v$latestversion.\n" if ($debug);
1270
1271    # if the update was for shepherd itself, restart it
1272    if ($progtype eq "shepherd") {
1273        print "\n*** Restarting ***\n\n";
1274        exec("$ldir/$proggy");
1275        # This exits.
1276    }
1277
1278    print "Testing $proggy...\n" if ($debug);
1279    my $result = test_proggy($ldir,"$ldir/$proggy");
1280
1281    $components->{$proggy}->{type} = $progtype;
1282    $components->{$proggy}->{ver} = $latestversion;
1283    $components->{$proggy}->{ready} = $result;
1284    $components->{$proggy}->{config} = $config;
1285    $components->{$proggy}->{laststatus} = sprintf "updated to %s on %s", $latestversion, (strftime "%a%d%b%y",localtime(time));
1286
1287    $made_changes = 1;
1288}
1289
1290sub fetch_file
1291{
1292    my ($fn, $store) = @_;
1293
1294    my $sites = "";
1295    $sites = "$mirror_site," if ($mirror_site);
1296    $sites .= $HOME;
1297
1298    my $ret;
1299    foreach my $site (split(/,/,$sites)) 
1300    {
1301        printf "Fetching $site/$fn.\n";
1302        if ($store)
1303        {
1304            $ret = LWP::Simple::getstore("$site/$fn", $store);
1305            return 1 if (is_success($ret));
1306        }
1307        else
1308        {
1309            $ret = LWP::Simple::get("$site/$fn");
1310            return $ret if ($ret);
1311        }
1312        print "Failed to retrieve $site/$fn.\n";
1313    }
1314    return undef;
1315}
1316
1317sub test_proggy
1318{
1319    my ($testdir,$proggyexec) = @_;
1320
1321    chdir($testdir);
1322    system("$proggyexec --ready");
1323    chdir ($CWD);
1324
1325    my $result = $?;
1326    print "Return value: $result\n" if ($debug);
1327
1328    print "\nComponent $proggyexec did not exit cleanly!\n" .
1329         "It may require configuration.\n\n" if ($result);
1330    return !$result;
1331}
1332
1333sub enable
1334{
1335    my $proggy = shift;
1336
1337    # confirm it exists first
1338    if (!$components->{$proggy}) {
1339        printf "No such component: \"%s\".\n",$proggy;
1340        return;
1341    }
1342    print "Enabling $proggy.\n";
1343
1344    delete $components->{$proggy}->{disabled};
1345    $components->{$proggy}->{laststatus} = sprintf "enabled on %s, not run yet",(strftime "%a%d%b%y", localtime(time));
1346    $made_changes = 1;
1347}
1348
1349sub disable
1350{
1351    my $proggy = shift;
1352
1353    # confirm it exists first
1354    if (!$components->{$proggy}) {
1355        printf "No such component: \"%s\".\n",$proggy;
1356        return;
1357    }
1358    print "Disabling $proggy.\n";
1359
1360    $components->{$proggy}->{disabled} = 1;
1361    $components->{$proggy}->{laststatus} = sprintf "manually disabled on %s",(strftime "%a%d%b%y", localtime(time));
1362    $made_changes = 1;
1363}
1364
1365sub set_order
1366{
1367    my ($quiet,$order) = @_;
1368    $pref_order = $order if ($order);
1369
1370    # reset current order to zero
1371    foreach my $proggy (query_grabbers()) {
1372        $components->{$proggy}->{order} = 0;
1373    }
1374
1375    # and now set order
1376    my $order_num = 1;
1377    if ($pref_order) {
1378        foreach my $proggy (split(/,/,$pref_order)) {
1379            if (defined $components->{$proggy} and $components->{$proggy}->{type} eq 'grabber') {
1380                $components->{$proggy}->{order} = $order_num;
1381                $order_num++;
1382            }
1383        }
1384    }
1385
1386    # set order of any grabbers not specified in a random manner
1387    foreach my $proggy (sort query_grabbers()) {
1388        if ((!defined $components->{$proggy}->{order}) || ($components->{$proggy}->{order} == 0)) {
1389            $components->{$proggy}->{order} = $order_num+int(rand(1000));
1390        }
1391    }
1392
1393    # .. and finally normalize the order (& show the user the order we chose)
1394    print "Grabber order set as follows:\n" unless $quiet;
1395    $order_num = 0;
1396    foreach my $proggy (sort { $components->{$a}->{order} <=> $components->{$b}->{order} } query_grabbers()) {
1397        $order_num++;
1398        $components->{$proggy}->{order} = $order_num;
1399        printf " #%d. %s%s\n",$components->{$proggy}->{order},$proggy,($components->{$proggy}->{disabled} ? " [disabled]" : "") unless $quiet;
1400    }
1401
1402    $made_changes = 1;
1403}
1404
1405sub check
1406{
1407    my $result;
1408    foreach my $proggy (keys %$components) {
1409        my $progtype = $components->{$proggy}->{type};
1410        $result = test_proggy("$CWD/$progtype" . "s/$proggy", "$CWD/$progtype" . "s/$proggy/$proggy");
1411        printf "%s %s: %s\n",ucfirst($progtype), $proggy,($result ? "OK" : "Failed");
1412        if (!$result ne !$components->{$proggy}->{ready}) {
1413            $components->{$proggy}->{ready} = $result;
1414            $made_changes = 1;
1415        }
1416    }
1417}
1418# -----------------------------------------
1419# Subs: Utilities
1420# -----------------------------------------
1421#
1422
1423sub query_grabbers
1424{
1425    return query_component_type('grabber');
1426}
1427
1428sub query_postprocessors
1429{
1430    return query_component_type('postprocessor');
1431}
1432
1433sub query_component_type
1434{
1435    my $progtype = shift;
1436
1437    my @ret = ();
1438    foreach (keys %$components)
1439    {
1440        push (@ret, $_) if ($components->{$_}->{type} eq $progtype);
1441    }
1442    return @ret;
1443}
1444
1445# -----------------------------------------
1446# Subs: Setup
1447# -----------------------------------------
1448
1449sub read_config_file
1450{
1451    read_file($config_file, 'configuration');
1452
1453    # TEMPORARY! Convert old $grabbers/$postprocessors config file to
1454    # new $components format.
1455    if (defined $grabbers or defined $postprocessors)
1456    {
1457        foreach (keys %$grabbers) {
1458            $grabbers->{$_}->{type} = 'grabber';
1459        }
1460        foreach (keys %$postprocessors) {
1461            $postprocessors->{$_}->{type} = 'postprocessor';
1462        }
1463        $components = { %$grabbers, %$postprocessors };
1464        $grabbers = undef;
1465        $postprocessors = undef;
1466    }
1467
1468
1469    # if we are updating from a previous rev of shepherd.conf we may not
1470    # have any 'order' fields set .. check here
1471    my $found_order = 1;
1472    foreach (query_grabbers())
1473    {
1474        $found_order = 0 if (!defined $components->{$_}->{order});
1475    }
1476    if (($found_order == 0) && (!$opt->{setorder}))
1477    {
1478        # at least one 'order' was missing .. we need to put it in!
1479        printf "Legacy shepherd.conf file didn't contain any grabber order! Automatically updating using a random order, use --setorder to manually set this if you care.\n";
1480        &set_order(1);
1481    }
1482
1483    # if a mirror has been specified, add it into our config
1484    if ($opt->{mirror}) {
1485        $mirror_site = $opt->{mirror};
1486        $made_changes = 1;
1487        print "Adding mirror: $mirror_site\n";
1488    }
1489}
1490
1491sub read_channels_file
1492{
1493    read_file($channels_file, 'channels');
1494}
1495
1496sub read_file
1497{
1498    my $fn = shift;
1499    my $name = shift;
1500
1501    print "Reading $name file: $fn\n";
1502    unless (-r $fn)
1503    {
1504        unless ($opt->{configure})
1505        {
1506            print "\nNo $name file found.\n" .
1507                  ucfirst($progname) . " must be configured: " .
1508                  "configuring now.\n\n";
1509            $opt->{'configure'} = 1;
1510        }
1511        return;
1512    }
1513    local (@ARGV, $/) = ($fn);
1514    no warnings 'all';
1515    eval <>;
1516    if ($@ and !$opt->{configure})
1517    {
1518        die "\nError in $name file!\nDetails:\n$@";
1519    }
1520}
1521
1522sub write_config_file
1523{
1524    open(CONF, ">$config_file") or die "cannot write to $config_file: $!";
1525    print CONF Data::Dumper->Dump(
1526        [$region,  $pref_order,  $mirror_site,  $components, $title_translation_table  ],
1527        ["region", "pref_order", "mirror_site", "components", "title_translation_table" ]);
1528    close CONF;
1529    print "\nUpdated configuration file $config_file.\n" if ($debug);
1530}
1531
1532sub write_channels_file
1533{
1534    open(CHAN, ">$channels_file") or die "cannot write to $channels_file: $!";
1535    print CHAN Data::Dumper->Dump([$channels], ["channels"]);
1536    close CHAN;
1537    print "Updated channels file $channels_file.\n" if ($debug);
1538}
1539
1540sub get_initial_command_line_options
1541{
1542  GetOptions( 'config-file=s'   => \$opt->{configfile},
1543              'help'            => \$opt->{help},
1544              'configure'       => \$opt->{configure},
1545              'mirror=s'        => \$opt->{mirror},
1546              'dontcallgrabbers' => \$opt->{dontcallgrabbers},
1547              'debug'           => \$debug);
1548}
1549
1550sub get_remaining_command_line_options
1551{
1552    GetOptions(
1553              'version'         => \$opt->{status},
1554              'status'          => \$opt->{status},
1555              'list'            => \$opt->{list},
1556              'show-config'     => \$opt->{show_config},
1557
1558              'update'          => \$opt->{update},
1559              'noupdate'        => \$opt->{noupdate},
1560
1561              'disable=s'       => \$opt->{disable},
1562              'enable=s'        => \$opt->{enable},
1563              'setorder=s'      => \$opt->{setorder},
1564
1565              'days=i'          => \$days,
1566              'offset=i'        => \$opt->{offset},
1567              'show-channels'   => \$opt->{show_channels},
1568              'output=s'        => \$opt->{output},
1569              'check'           => \$opt->{check}
1570            );
1571}
1572
1573
1574# -----------------------------------------
1575# Subs: Configuration
1576# -----------------------------------------
1577
1578sub configure
1579{
1580    my $REGIONS = {
1581        "ACT" => 126,
1582        "NSW: Sydney" => 73,
1583        "NSW: Newcastle" => 184,
1584        "NSW: Central Coast" => 66,
1585        "NSW: Griffith" => 67,
1586        "NSW: Broken Hill" => 63,
1587        "NSW: Northern NSW" => 69,
1588        "NSW: Southern NSW" => 71,
1589        "NSW: Remote and Central" => 106,
1590        "NT: Darwin" => 74,
1591        "NT: Remote & Central" => 108,
1592        "QLD: Brisbane" => 75,
1593        "QLD: Gold Coast" => 78,
1594        "QLD: Regional" => 79,
1595        "QLD: Remote & Central" => 114,
1596        "SA: Adelaide" => 81,
1597        "SA: Renmark" => 82,
1598        "SA: Riverland" => 83,
1599        "SA: South East SA" => 85,
1600        "SA: Spencer Gulf" => 86,
1601        "SA: Remote & Central" => 107,
1602        "Tasmania" => 88,
1603        "VIC: Melbourne" => 94,
1604        "VIC: Geelong" => 93,
1605        "VIC: Eastern Victoria" => 90,
1606        "VIC: Mildura/Sunraysia" => 95,
1607        "VIC: Western Victoria" => 98,
1608        "WA: Perth" => 101,
1609        "WA: Regional" => 102
1610    };
1611
1612    print "\nConfiguring.\n\n" .
1613          "Select your region:\n";
1614    foreach (sort keys %$REGIONS)
1615    {
1616        printf(" (%3d) %s\n", $REGIONS->{$_}, $_);
1617    }
1618    $region = ask_choice("Enter region code:", "94", values %$REGIONS);
1619
1620    print "\nFetching channel information... ";
1621
1622    my @channellist = get_channels();
1623
1624    print "done.\n\n" .
1625          "For each channel you want guide data for, enter an XMLTV id\n" .
1626          "of your choice (e.g. \"seven.free.au\"). If you don't need\n" .
1627          "guide data for this channel, just press Enter.\n\n" .
1628          "Please don't subscribe to unneeded channels.\n\nChannels:\n";
1629    $channels = {};
1630    my $line;
1631    foreach (@channellist)
1632    {
1633        $line = ask(" \"$_\"? ");
1634        $channels->{$_} = $line if ($line);
1635    }
1636
1637
1638    print "\nRandomly selecting grabber order.\n\n";
1639    set_order(0);
1640
1641    show_channels();
1642    unless(ask_boolean("\nCreate configuration file?"))
1643    {
1644        print "Aborting configuration.\n";
1645        exit 0;
1646    }
1647
1648    write_config_file();
1649    write_channels_file();
1650
1651    print "Finished configuring.\n\n" .
1652          "Shepherd is installed into $CWD.\n\n";
1653   
1654    if ($invoked ne "$CWD/$progname" and $invoked =~ /$progname/)
1655    {
1656        print "Warning: you invoked this program as $invoked.\n" .
1657            "In the future, it should be run as $CWD/$progname,\n" .
1658            "to avoid constantly re-downloading the latest version.\n\n" .
1659            "MythTV users may wish to create the following symlink, by " .
1660            "doing this (as root):\n" .
1661            "\"ln -s $CWD/$progname /usr/bin/tv_grab_au\".\n\n" .
1662            "You may safely delete $invoked.\n\n";
1663    }
1664
1665    status();
1666
1667    unless (ask_boolean("\nGrab data now?"))
1668    {
1669        exit 0;
1670    }
1671}
1672
1673sub get_channels
1674{
1675    my @date = localtime;
1676    my $page = LWP::Simple::get(
1677        "http://au.tv.yahoo.com/results.html?rg=$region&dt=" .
1678        ($date[5] + 1900) . "-$date[4]-$date[3]");
1679    my @channellist;
1680    while ($page =~ /<tr class=rtb><td class=rth><a .*?>(.*?)<\/a>/g)
1681    {
1682        push @channellist, $1;
1683    }
1684    return @channellist;
1685}
1686
1687# -----------------------------------------
1688# Subs: Status & Help
1689# -----------------------------------------
1690
1691sub show_config
1692{
1693    print "\nConfiguration\n".
1694          "-------------\n" .
1695          "Config file: $config_file\n" .
1696          "Debug mode : " . is_set($debug) . "\n" .
1697          "Output file: " . ($opt->{output} ? $opt->{output} : "None") . "\n" .
1698          "Region ID  : $region\n";
1699  show_channels();
1700  print "\n";
1701  status();
1702  print "\n";
1703}
1704
1705sub show_channels
1706{
1707  print "Subscribed channels:\n";
1708  print "    $_ -> $channels->{$_}\n" for sort keys %$channels;
1709}
1710
1711sub is_set
1712{
1713    my $arg = shift;
1714    return $arg ? "Yes" : "No";
1715}
1716
1717sub status
1718{
1719    print " Grabber           Version Enabled Ready Last Run   Status\n" .
1720          " ----------------- ------- ------- ----- ---------- ---------------------------\n";
1721    foreach (sort { $components->{$a}->{order} <=> $components->{$b}->{order} } query_grabbers()) {
1722        my $h = $components->{$_};
1723        printf  " %-16s %8s %4s %6s  %11s %s\n",
1724                "$h->{order}. $_",
1725                ($h->{ver} ? $h->{ver} : "unknown"),
1726                $h->{disabled} ? '' : 'Y',
1727                $h->{ready} ? 'Y' : '',
1728                $h->{lastdata} ? (strftime "%a%d%b%y", localtime($h->{lastdata})) : 'never',
1729                $h->{laststatus} ? $h->{laststatus} : '';
1730    }
1731    printf "Grabbers shown in order of preference.\n\n";
1732
1733    print " Postprocessor     Version Enabled Ready Last Run   Status\n" .
1734          " ----------------- ------- ------- ----- ---------- ---------------------------\n";
1735    foreach (sort { $components->{$a} <=> $components->{$b} } query_postprocessors()) {
1736        my $h = $components->{$_};
1737        printf  " %-16s %8s %4s %6s  %11s %s\n",
1738                $_,
1739                ($h->{ver} ? $h->{ver} : "unknown"),
1740                $h->{disabled} ? '' : 'Y',
1741                $h->{ready} ? 'Y' : '',
1742                $h->{lastdata} ? (strftime "%a%d%b%y", localtime($h->{lastdata})) : 'never',
1743                $h->{laststatus} ? $h->{laststatus} : '';
1744    }
1745    printf "Postprocessors shown in order of execution.\n\n";
1746}
1747
1748sub help
1749{
1750    print q{
1751Command-line options:
1752    --help                Print this message
1753
1754    --status              Print a list of grabbers maintained
1755    --list                Print a detailed list of grabbers
1756    --mirror <s>          Set URL <s> as primary location to check for updates
1757
1758    --configure           Setup
1759    --show-config         Print setup details
1760
1761    --setorder <s>        Set order of grabbers to <s> (comma-seperated list of grabbers)
1762
1763    --disable <s>         Don't ever use grabber/postprocessor <s>
1764    --enable <s>          Okay, maybe use it again then
1765    --uninstall <s>       Remove a disabled grabber/postprocessor
1766
1767    --noupdate            Do not attempt to update before running
1768    --update              Update only; do not grab data
1769
1770    --check               Check status of all grabbers and postprocessors
1771};
1772    exit 0;
1773}
1774
1775# -----------------------------------------
1776# Subs: override handlers for standard perl.
1777# -----------------------------------------
1778
1779# ugly hack. please don't try this at home kids!
1780sub my_die {
1781    my ($arg,@rest) = @_;
1782    my ($pack,$file,$line,$sub) = caller(1);
1783
1784    # check if we are in an eval()
1785    if ($^S) {
1786        printf STDERR "  shepherd caught a die() within eval{} from file $file line $line\n";
1787    } else {
1788        if (!ref($arg)) {
1789            printf STDERR "DIE at line %d in file %s\n",$line,$file;
1790            CORE::die(join("",@rest));
1791        } else {
1792            CORE::die($arg,@rest);
1793        }
1794    }
1795}
Note: See TracBrowser for help on using the browser.