root/shepherd @ 34

Revision 34, 58.6 kB (checked in by lincoln, 7 years ago)

a few fixes/enhancements:
(1) new command line option --dontcallgrabbers - useful for when debugging/testing,

means you can test using previously-collected xmltv output from each grabber chosen

(2) data-scrubber automatically fixes oztivo's bogus (blank) 'director' lines

to stop XMLTV whining

(3) data-scrubber removes start_epoch/stop_epoch before write_programme to stop XMLTV whining

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