root/shepherd @ 5

Revision 5, 33.5 kB (checked in by lincoln, 7 years ago)

postprocessor support

Line 
1#!/usr/bin/perl -w
2
3# "Shepherd"
4
5my $version = '0.2.6';
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#
24# ToDo:
25# * --mirror <url> option, to let you get software from somewhere other
26#   than whuffy. Store this in shepherd.conf. Whuffy is merely the first
27#   mirror.
28# * Make it check compilation after installing by calling --version or
29#   --desc or --ready
30# * --ready  option that says whether config is required?
31
32use strict;
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);
42
43# ---------------------------------------------------------------------------
44# --- Global Variables
45# ---------------------------------------------------------------------------
46
47my $progname = 'shepherd';
48
49my $HOME = 'http://www.whuffy.com';
50my $STATUS = "$HOME/status";
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 $GRABBER_DIR = "$CWD/grabbers";
61my $POSTPROCESSOR_DIR = "$CWD/postprocessors";
62my $ARCHIVE_DIR = "$CWD/archive";
63
64my $timeslot_size = (15 * 60);                  # 15 minute slots
65my $channel_ok_threshold_percent = 90;          # 90% these may need to be tweaked but look ok for now
66my $postprocessor_ok_threshold_percent = 80;    # 80% these may need to be tweaked but look ok for now
67my $postprocessor_disable_failure_threshold = 5; # number of times a postprocessor has to fail in a row before it is automatically disabled
68
69my $opt;
70my $pref_order;
71my $made_changes = 0;
72my $debug = 1;
73my $grabbers = { };
74my $postprocessors = { };
75my $preferred; # obsolete but may still exist in shepherd.conf
76my $region;
77my $channels;
78my $config_file =   "$CWD/$progname.conf";
79my $channels_file = "$CWD/channels.conf";
80my $days;
81
82# postprocessing
83my $langs = [ 'en' ];
84my $num_timeslots;
85my $plugin_data = { };
86my $channel_data = { };
87my $starttime, my $endtime;
88my $input_postprocess_files = "";
89my $insufficient_grabber_data = 0;
90
91# ---------------------------------------------------------------------------
92# --- Setup
93# ---------------------------------------------------------------------------
94
95print ucfirst($progname) . " v$version\n\n";
96#print "Cwd: $CWD.\n";
97
98# Any options Shepherd doesn't understand, we'll pass to the grabber(s)
99Getopt::Long::Configure(qw/pass_through/);
100
101get_initial_command_line_options();
102
103help() if ($opt->{help});
104
105unless ($opt->{configure})
106{
107    read_config_file();
108    read_channels_file();
109}
110
111get_remaining_command_line_options();
112
113if ($opt->{status})
114{
115    status();
116    exit;
117}
118
119if ($opt->{show_config})
120{
121    show_config();
122    exit;
123}
124
125if ($opt->{enable})
126{
127    enable($opt->{enable});
128}
129
130if ($opt->{disable})
131{
132    disable($opt->{disable});
133}
134
135&set_order(0,$opt->{setorder}) if ($opt->{setorder});
136&check() if ($opt->{check});
137
138if ($opt->{enable} or $opt->{disable} or $opt->{setorder} or $opt->{check})
139{
140    set_order(1) if $made_changes;
141    write_config_file() if $made_changes;
142    status();
143    exit;
144}
145
146# ---------------------------------------------------------------------------
147# --- Update
148# ---------------------------------------------------------------------------
149
150unless ($opt->{noupdate})
151{
152    update($progname, $version);
153    write_config_file() unless ($opt->{configure});
154}
155
156if ($opt->{configure})
157{
158    configure();
159}
160
161# ---------------------------------------------------------------------------
162# --- Go!
163# ---------------------------------------------------------------------------
164
165unless ($opt->{update})
166{
167    calc_date_range();
168    grab_data();
169    postprocess_data();
170    output_data();
171}
172
173print "Done.\n";
174
175status();
176write_config_file();
177
178# ---------------------------------------------------------------------------
179# --- Subroutines
180# ---------------------------------------------------------------------------
181
182# -----------------------------------------
183# Subs: Grabbing
184# -----------------------------------------
185
186sub grab_data
187{
188    my $used_grabbers = 0;
189    my $need_more_data = 1;
190
191    # iterate across grabbers until we have all our data we want (or need)
192    foreach my $grabber (sort { $grabbers->{$a}->{order} <=> $grabbers->{$b}->{order} } keys %$grabbers) {
193        next if ($grabbers->{$grabber}->{disabled});
194        $used_grabbers++;
195
196        $grabbers->{$grabber}->{lastdata} = time;
197        $grabbers->{$grabber}->{laststatus} = "unknown";
198
199        printf "SHEPHERD: Using grabber: (%d) %s\n",$grabbers->{$grabber}->{order},$grabber;
200
201        my $output = "$GRABBER_DIR/$grabber/output.xmltv";
202        $input_postprocess_files .= "$output ";
203
204        my $comm = "$GRABBER_DIR/$grabber/$grabber " .
205                   "--region $region " .
206                   "--channels_file $channels_file " .
207                   "--output $output";
208
209        # NOTE: ideally a grabber could be instructed to fetch partial data through --channel, --starttime & --endtime
210        # we don't have that for now so instead whenever there is missing data, ALL 7 days for all channels will be collected
211        # FIXME FUTURE: call grabbers just with what we want...
212        $comm .= " --days $days" if ($days);
213        $comm .= " --offset $opt->{offset}" if ($opt->{offset});
214        $comm .= " --debug" if ($debug);
215        $comm .= " @ARGV" if (@ARGV);
216        print "SHEPHERD: Excuting command: $comm\n";
217
218        chdir "$GRABBER_DIR/$grabber/";
219        system($comm);
220        chdir $CWD;
221
222        # soak up the data we just collected
223        &soak_up_data($grabber, $output);
224        $grabbers->{$grabber}->{laststatus} = $plugin_data->{$grabber}->{laststatus};
225
226        # check to see if we have all the data we want
227        $need_more_data = &analyze_plugin_data($channel_ok_threshold_percent);
228
229        last if (!$need_more_data);
230    }
231
232
233    if ($used_grabbers == 0)
234    {
235        print "No valid grabbers installed/enabled!\n";
236        return;
237    }
238
239    if ($need_more_data)
240    {
241        print "SHEPHERD: Ran through ALL grabbers but still missing data!!! :(\n";
242        $insufficient_grabber_data = 1;
243        return;
244    }
245}
246
247
248# interpret xmltv data from this grabber/postprocessor
249sub soak_up_data
250{
251    my ($grabber, $output) = @_;
252    eval { $plugin_data->{$grabber}->{xmltv} = XMLTV::parsefiles($output); };
253
254    if (defined $plugin_data->{$grabber}->{xmltv}) {
255        $plugin_data->{$grabber}->{valid} = 1;
256
257        my $xmltv = $plugin_data->{$grabber}->{xmltv};
258        my ($encoding, $credits, $chan, $progs) = @$xmltv;
259        $plugin_data->{$grabber}->{total_duration} = 0;
260        $plugin_data->{$grabber}->{programmes} = 0;
261
262        my $strptime = new DateTime::Format::Strptime( pattern => "%Y%m%d%H%M %z");
263        my $seen_channels_with_data = 0;
264
265        # iterate thru channels
266        foreach my $ch (sort keys %{$channels}) {
267            my $seen_progs_on_this_channel = 0;
268
269            # iterate thru programmes per channel
270            foreach my $prog (@$progs) {
271                next if ($prog->{channel} ne $channels->{$ch});
272
273                my $t1 = $strptime->parse_datetime($prog->{start});
274                my $t2 = $strptime->parse_datetime($prog->{stop});
275                next if (!$t1 || !$t2); # if we can't parse stop/start then clearly THIS data is bunk!
276
277                # store grabber-specific stats
278                $plugin_data->{$grabber}->{programmes}++;
279                $plugin_data->{$grabber}->{total_duration} += ($t2->epoch - $t1->epoch);
280                $seen_progs_on_this_channel++;
281                $plugin_data->{$grabber}->{earliest_data_seen} = $t1->epoch if (!defined $plugin_data->{$grabber}->{earliest_data_seen});
282                $plugin_data->{$grabber}->{earliest_data_seen} = $t1->epoch if ($t1->epoch < $plugin_data->{$grabber}->{earliest_data_seen});
283                $plugin_data->{$grabber}->{latest_data_seen} = $t2->epoch if (!defined $plugin_data->{$grabber}->{latest_data_seen});
284                $plugin_data->{$grabber}->{latest_data_seen} = $t2->epoch if ($t2->epoch > $plugin_data->{$grabber}->{latest_data_seen});
285
286                # store channel-specific stats
287                $channel_data->{$ch}->{programmes}++;
288                $channel_data->{$ch}->{total_duration} += ($t2->epoch - $t1->epoch);
289
290                # store timeslot info
291                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!
292                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!
293                my $start_slotnum;
294                if ($t1->epoch >= $starttime) {
295                    $start_slotnum = int(($t1->epoch - $starttime) / $timeslot_size);
296                } else {
297                    $start_slotnum = 0;
298                }
299                my $end_slotnum;
300                if ($t2->epoch < $endtime) {
301                    $end_slotnum = int(($t2->epoch - $starttime) / $timeslot_size);
302                } else {
303                    $end_slotnum = ($num_timeslots-1);
304                }
305
306                # add this programme into the global timeslots table for this channel
307                foreach my $slotnum ($start_slotnum..$end_slotnum) {
308                    $channel_data->{$ch}->{timeslots}[$slotnum]++;
309                }
310            }
311
312            $seen_channels_with_data++ if ($seen_progs_on_this_channel > 0);
313        }
314
315        # print some stats about what we saw!
316        printf "SHEPHERD: Grabber '%s' returned data for %d channels, %d programmes, %dd%02dh%02dm%02ds duration, %s%s\n",
317            $grabber, $seen_channels_with_data, $plugin_data->{$grabber}->{programmes},
318            int($plugin_data->{$grabber}->{total_duration} / 86400),            # days
319            int(($plugin_data->{$grabber}->{total_duration} % 86400) / 3600),   # hours
320            int(($plugin_data->{$grabber}->{total_duration} % 3600) / 60),      # mins
321            int($plugin_data->{$grabber}->{total_duration} % 60),               # sec
322            (defined $plugin_data->{$grabber}->{earliest_data_seen} ? (strftime "%a %e %b %H:%M - ", localtime($plugin_data->{$grabber}->{earliest_data_seen})) : 'no data'),
323            (defined $plugin_data->{$grabber}->{latest_data_seen} ? (strftime "%a %e %b %H:%M", localtime($plugin_data->{$grabber}->{latest_data_seen})) : '');
324        $plugin_data->{$grabber}->{laststatus} = sprintf "%dch/%dpr/%dhrs %s-%s",
325            $seen_channels_with_data, $plugin_data->{$grabber}->{programmes},
326            int($plugin_data->{$grabber}->{total_duration} / 3600),
327            (defined $plugin_data->{$grabber}->{earliest_data_seen} ? (strftime "%a%d%b%H:%M", localtime($plugin_data->{$grabber}->{earliest_data_seen})) : 'no'),
328            (defined $plugin_data->{$grabber}->{latest_data_seen} ? (strftime "%a%d%b%H:%M", localtime($plugin_data->{$grabber}->{latest_data_seen})) : 'data');
329
330    } else {
331        printf "WARNING: Plugin %s didn't seem to return any valid XMLTV!\n",$grabber;
332        delete $plugin_data->{$grabber}->{valid};
333    }
334}
335
336
337# analyze grabber data - do we have all the data we want?
338# returns 1 if we need more data, 0 if we have all we want
339sub analyze_plugin_data
340{
341    my $threshold = shift;
342    my $retval = 0; # until proven otherwise
343    my $total_data_percent = 0, my $total_channels = 0;
344    my $statusstring = "";
345
346    # iterate across each channel
347    foreach my $ch (sort keys %{$channels}) {
348        $total_channels++;
349        if (defined $channel_data->{$ch}) {
350            my $data_in_channel = 0;
351            for my $slotnum (0..($num_timeslots-1)) {
352                $data_in_channel++ if ((defined $channel_data->{$ch}->{timeslots}[$slotnum]) && ($channel_data->{$ch}->{timeslots}[$slotnum] > 0));
353            }
354
355            # do we have enough data for this channel?
356            my $data_in_channel_percent = $data_in_channel / ($num_timeslots-1) * 100;
357            if ($data_in_channel_percent >= $threshold) {
358                $statusstring .= sprintf "%s: %0.1f%% [complete], ",$ch,$data_in_channel_percent;
359            } else {
360                $statusstring .= sprintf "%s: %0.1f%% [hungry], ",$ch,$data_in_channel_percent;
361                $retval = 1;
362            }
363            $total_data_percent += $data_in_channel_percent;
364        } else {
365            $statusstring .= sprintf "%s: 0%% [starving], ",$ch;
366            $retval = 1;
367        }
368    }
369
370    if ($total_channels > 0) {
371        $total_data_percent = $total_data_percent / $total_channels;
372    } else {
373        $total_data_percent = 0;
374    }
375
376    # print some stats about what our analysis says!
377    printf "SHEPHERD: ANALYSIS: %sTOTAL %0.2f%% %s %0.2f%%: %s\n", $statusstring, $total_data_percent,
378        ($total_data_percent >= $channel_ok_threshold_percent ? ">" : "<"), $channel_ok_threshold_percent,
379        ($retval ? "WANT MORE DATA" : "COMPLETE");
380    return $retval;
381}
382
383
384# work out date range we are expecting data to be in
385sub calc_date_range
386{
387    # normalize starttime to beginning of hour
388    my $now = time;
389    my ($sec,$min,@rest) = localtime($now);
390
391    $starttime = $now - ((60 * $min) + $sec);
392
393    if ($days) {
394        $endtime = $starttime + ($days * 86400);
395    } else {
396        $endtime = $starttime + (7*86400);
397    }
398    $starttime += (86400 * $opt->{offset}) if ($opt->{offset});
399
400    $num_timeslots = ($endtime - $starttime) / $timeslot_size;
401}
402
403# -----------------------------------------
404# Subs: Postprocessing
405# -----------------------------------------
406
407sub postprocess_data
408{
409    # for our first postprocessor, we feed it ALL of the XMLTV files we have
410    # as each postprocessor runs, we feed in the output from the previous one
411    # Shepherd checks the "completeness" of the data that comes out of a postprocessor & automatically
412    # reverts back to the previous postprocessor if it was shown to be bad
413
414    # first time around: feed in $input_postprocess_files
415    my $need_more_data;
416
417    foreach my $postprocessor (sort { $postprocessors->{$a} <=> $postprocessors->{$b} } keys %$postprocessors) {
418        next if ($postprocessors->{$postprocessor}->{disabled});
419
420        $postprocessors->{$postprocessor}->{lastdata} = time;
421        $postprocessors->{$postprocessor}->{laststatus} = "unknown";
422
423        printf "SHEPHERD: Using postprocessor: %s\n",$postprocessor;
424
425        my $output = "$POSTPROCESSOR_DIR/$postprocessor/output.xmltv";
426        my $comm = "$POSTPROCESSOR_DIR/$postprocessor/$postprocessor " .
427                   "--region $region " .
428                   "--channels_file $channels_file " .
429                   "--output $output";
430        $comm .= " --days $days" if ($days);
431        $comm .= " --offset $opt->{offset}" if ($opt->{offset});
432        $comm .= " --debug" if ($debug);
433        $comm .= " @ARGV" if (@ARGV);
434        $comm .= " $input_postprocess_files";
435        print "SHEPHERD: Excuting command: $comm\n";
436
437        chdir "$POSTPROCESSOR_DIR/$postprocessor/";
438        system($comm);
439        chdir $CWD;
440
441        #
442        # soak up the data we just collected and check it
443        # YES - these are the SAME routines we used in the previous 'grabber' phase
444        # but the difference here is that we clear out our 'channel_data' beforehand
445        # so we can independently analyze the impact of this postprocessor.
446        # if it clearly returns bad data, don't use that data (go back one step) and
447        # flag the postprocessor as having failed.  after 3 consecutive failures, disable it
448        #
449
450        # clear out channel_data
451        foreach my $ch (keys %{$channels}) {
452            delete $channel_data->{$ch};
453        }
454
455        # process and analyze it!
456        &soak_up_data($postprocessor, $output);
457        $need_more_data = &analyze_plugin_data($postprocessor_ok_threshold_percent);
458
459        $postprocessors->{$postprocessor}->{laststatus} = $plugin_data->{$postprocessor}->{laststatus};
460
461        if (($need_more_data) && (!$insufficient_grabber_data)) {
462            # urgh.  this postprocessor did a bad bad thing ...
463            printf "SHEPHERD: XML data from postprocessor %s rejected, using XML from previous stage\n",$postprocessor;
464
465            if (defined $postprocessors->{$postprocessor}->{conescutive_failures}) {
466                $postprocessors->{$postprocessor}->{conescutive_failures}++;
467            } else {
468                $postprocessors->{$postprocessor}->{conescutive_failures} = 1;
469            }
470            printf "SHEPHERD: Postprocessor \"%s\" has now failed %d times in a row.  %d more and it will be automatically disabled.\n",
471                $postprocessor,
472                $postprocessors->{$postprocessor}->{conescutive_failures},
473                $postprocessor_disable_failure_threshold;
474
475            if ($postprocessors->{$postprocessor}->{conescutive_failures} >= $postprocessor_disable_failure_threshold) {
476                printf "SHEPHERD: Disabling Postprocessor \"%s\".\n",$postprocessor;
477                $postprocessors->{$postprocessor}->{disabled} = 1;
478            }
479        } else {
480            # accept what this postprocessor did to our output ...
481            printf "SHEPHERD: accepting output from postprocessor %s, feeding it into next stage\n",$postprocessor;
482            $input_postprocess_files = $output;
483            delete $postprocessors->{$postprocessor}->{conescutive_failures} if (defined $postprocessors->{$postprocessor}->{conescutive_failures});
484        }
485    }
486}
487
488
489sub output_data
490{
491    # $input_postprocess_files (hopefully just one file now) contains our final output
492    # send it to whereever --output told us to!
493
494    if ($opt->{output}) {
495        open(F,">$opt->{output}") || die "could not open outputfile $opt->{output} for writing: $!\n";
496    }
497
498    foreach my $infile (split(/ /,$input_postprocess_files)) {
499        if (!(open(INFILE,"<$infile"))) {
500            printf "WARNING: could not open input file \"%s\": %s\n", $infile, $!;
501            printf "Output XMLTV data may be damanged as a result!\n";
502        } else {
503            while (<INFILE>) {
504                if ($opt->{output}) {
505                    print F $_ if ($opt->{output});
506                } else {
507                    print $_;
508                }
509            }
510            close(INFILE);
511        }
512    }
513    close(F) if ($opt->{output});
514}
515
516# -----------------------------------------
517# Subs: Updates & Installations
518# -----------------------------------------
519
520sub update
521{
522    print "\nFetching status file: $STATUS.\n";
523    my $data = LWP::Simple::get($STATUS);
524    unless ($data)
525    {
526        print "Failed to retrieve status file.\n";
527        return;
528    }
529
530    my %glist = %$grabbers;
531    my %plist = %$postprocessors;
532    while ($data =~ /(.*):(.*):(.*)/g)
533    {
534        my ($proggy, $latestversion, $progtype) = ($1,$2,$3);
535        update_component($proggy, $latestversion, $progtype);
536        delete $glist{$proggy} if ($progtype eq "grabber");
537        delete $plist{$proggy} if ($progtype eq "postprocessor");
538    }
539
540    # work out what grabbers disappeared (if any)
541    foreach (keys %glist) {
542        unless ($grabbers->{$_}->{disabled}) {
543            print "\nDeleted grabber: $_.\n";
544            disable($_,"grabber");
545            $made_changes = 1;
546        }
547    }
548
549    # work out what postprocessors disappeared (if any)
550    foreach (keys %plist) {
551        unless ($postprocessors->{$_}->{disabled}) {
552            print "\nDeleted Postprocessor: $_.\n";
553            disable($_,"postprocessor");
554            $made_changes = 1;
555        }
556    }
557}
558
559sub update_component
560{
561    my ($proggy, $latestversion, $progtype) = @_;
562
563    print "\n";
564
565    # handle new installs..
566    if (($$proggy eq $progname) && ($progtype eq "shepherd")) {
567        # shepherd itself..
568        if(! -e "$CWD/$progname") {
569            print "Missing: $CWD/$progname\n";
570            install($progname, $latestversion, $progtype);
571            return;
572        }
573    } elsif ($progtype eq "grabber") {
574        if (!$grabbers->{$proggy} or ! -e "$GRABBER_DIR/$proggy/$proggy") {
575            print "New grabber: $proggy.\n";
576            install($proggy, $latestversion, $progtype);
577            return;
578        }
579        print "Warning: grabber $proggy disabled by config file.\n" if ($grabbers->{$proggy}->{disabled});
580    } elsif ($progtype eq "postprocessor") {
581        if (!$postprocessors->{$proggy} or ! -e "$POSTPROCESSOR_DIR/$proggy/$proggy") {
582            print "New postprocessor: $proggy.\n";
583            install($proggy, $latestversion, $progtype);
584            return;
585        }
586        print "Warning: postprocessor $proggy disabled by config file.\n" if ($postprocessors->{$proggy}->{disabled});
587    }
588
589    # upgrade/downgrades
590    my $ver;
591    if ($progtype eq "grabber") {
592        $ver = ($proggy eq $progname ? $version : $grabbers->{$proggy}->{ver});
593    } elsif ($progtype eq "postprocessor") {
594        $ver = ($proggy eq $progname ? $version : $postprocessors->{$proggy}->{ver});
595    } elsif (($$proggy eq $progname) && ($progtype eq "shepherd")) {
596        $ver = $version;
597    } else {
598        print "Warning: unknown type of programme: prog '$proggy' progtype '$progtype' not installed.\n";
599        return;
600    }
601
602    my $result = versioncmp($ver, $latestversion);
603    if ($result == -1) {
604        print "Upgrading $proggy from v$ver to v$latestversion.\n";
605    } elsif ($result == 1) {
606        print "Downgrading $proggy from v$ver to v$latestversion.\n";
607    } else {
608        print "Already have latest version of $proggy: v$ver.\n";
609        return;
610    }
611    install($proggy, $latestversion, $progtype);
612}
613
614sub install
615{
616    my ($proggy, $latestversion, $progtype) = @_;
617
618    print "Downloading $proggy v$latestversion.\n";
619
620    my $rdir = $HOME;
621    my $ldir = $CWD;
622    my $ver = $version;
623
624    if (($$proggy eq $progname) && ($progtype eq "shepherd")) {
625        $rdir = $HOME;
626        $ldir = $CWD;
627        $ver = $version;
628    } elsif ($progtype eq "grabber") {
629        $rdir = $HOME . "/grabbers";
630        $ldir = "$GRABBER_DIR/$proggy";
631        $ver = $grabbers->{$proggy}->{ver};
632        -d $GRABBER_DIR or mkdir $GRABBER_DIR or die "Cannot create directory $GRABBER_DIR: $!";
633    } elsif ($progtype eq "postprocessor") {
634        $rdir = $HOME . "/postprocessors";
635        $ldir = "$POSTPROCESSOR_DIR/$proggy";
636        $ver = $postprocessors->{$proggy}->{ver};
637        -d $POSTPROCESSOR_DIR or mkdir $POSTPROCESSOR_DIR or die "Cannot create directory $POSTPROCESSOR_DIR: $!";
638    } else {
639        print "Warning: unknown type of programme: prog '$proggy' progtype '$progtype' not installed.\n";
640        return;
641    }
642    -d $ldir or mkdir $ldir or die "Cannot create directory $ldir: $!";
643
644    my $newfile = "$ldir/$proggy-$latestversion";
645    my $rc = LWP::Simple::getstore("$rdir/$proggy-$latestversion", $newfile);
646
647    unless (is_success($rc))
648    {
649        print "Failed to retrieve $rdir/$proggy-$latestversion.\n";
650        return;
651    }
652
653    # Make it executable
654    system('chmod u+x ' . $newfile);
655
656    -d $ARCHIVE_DIR or mkdir $ARCHIVE_DIR or die "Cannot create directory $ARCHIVE_DIR: $!";
657
658    if (-e "$ldir/$proggy")
659    {
660        rename("$ldir/$proggy", "$ARCHIVE_DIR/$proggy-$ver");
661    }
662    rename($newfile, "$ldir/$proggy");
663   
664    print "Installed $proggy v$latestversion.\n" if ($debug);
665
666    # if the update was for shepherd itself, restart it
667    if (($$proggy eq $progname) && ($progtype eq "shepherd")) {
668        print "\n*** Restarting ***\n\n";
669        exec("$ldir/$proggy");
670        # This exits.
671    }
672
673    print "Testing $proggy...\n" if ($debug);
674    my $result = test_proggy($ldir,"$ldir/$proggy");
675
676    if ($progtype eq "grabber") {
677        $grabbers->{$proggy}->{ver} = $latestversion;
678        $grabbers->{$proggy}->{ready} = $result;
679        $grabbers->{$proggy}->{laststatus} = sprintf "updated to %s on %s", $latestversion, (strftime "%a%d%b%y",localtime(time));
680    } elsif ($progtype eq "postprocessor") {
681        $postprocessors->{$proggy}->{ver} = $latestversion;
682        $postprocessors->{$proggy}->{ready} = $result;
683        $postprocessors->{$proggy}->{laststatus} = sprintf "updated to %s on %s", $latestversion, (strftime "%a%d%b%y",localtime(time));
684    }
685
686    $made_changes = 1;
687}
688
689sub test_proggy
690{
691    my ($testdir,$proggyexec) = @_;
692
693    chdir($testdir);
694    system("$proggyexec --ready");
695    chdir ($CWD);
696
697    my $result = $?;
698    print "Return value: $result\n" if ($debug);
699
700    print "\nprogramme $proggyexec did not exit cleanly!\n" .
701         "It may require configuration.\n\n" if ($result);
702    return !$result;
703}
704
705sub enable
706{
707    my $proggy = shift;
708
709    # confirm it exists first
710    if ((!$grabbers->{$proggy}) && (!$postprocessors->{$proggy})) {
711        printf "No such grabber/postprocessor: \"%s\".\n",$proggy;
712        return;
713    }
714    print "Enabling $proggy.\n";
715
716    delete $grabbers->{$proggy}->{disabled} if ($grabbers->{$proggy});
717    delete $postprocessors->{$proggy}->{disabled} if ($postprocessors->{$proggy});
718    $made_changes = 1;
719}
720
721sub disable
722{
723    my $proggy = shift;
724
725    # confirm it exists first
726    if ((!$grabbers->{$proggy}) && (!$postprocessors->{$proggy})) {
727        printf "No such grabber/postprocessor: \"%s\".\n",$proggy;
728        return;
729    }
730    print "Disabling $proggy.\n";
731
732    $grabbers->{$proggy}->{disabled} = 1 if ($grabbers->{$proggy});
733    $postprocessors->{$proggy}->{disabled} = 1 if ($postprocessors->{$proggy});
734    $made_changes = 1;
735}
736
737sub set_order
738{
739    my ($quiet,$order) = @_;
740    $pref_order = $order if ($order);
741
742    # reset current order to zero
743    foreach my $proggy (keys %$grabbers) {
744        $grabbers->{$proggy}->{order} = 0;
745    }
746
747    # and now set order
748    my $order_num = 1;
749    if ($pref_order) {
750        foreach my $proggy (split(/,/,$pref_order)) {
751            if (defined $grabbers->{$proggy}) {
752                $grabbers->{$proggy}->{order} = $order_num;
753                $order_num++;
754            }
755        }
756    }
757
758    # set order of any grabbers not specified in a random manner
759    foreach my $proggy (sort keys %$grabbers) {
760        if ((!defined $grabbers->{$proggy}->{order}) || ($grabbers->{$proggy}->{order} == 0)) {
761            $grabbers->{$proggy}->{order} = $order_num+int(rand(1000));
762        }
763    }
764
765    # .. and finally normalize the order (& show the user the order we chose)
766    print "Grabber order set as follows:\n" unless $quiet;
767    $order_num = 0;
768    foreach my $proggy (sort { $grabbers->{$a}->{order} <=> $grabbers->{$b}->{order} } keys %$grabbers) {
769        $order_num++;
770        $grabbers->{$proggy}->{order} = $order_num;
771        printf " #%d. %s%s\n",$grabbers->{$proggy}->{order},$proggy,($grabbers->{$proggy}->{disabled} ? " [disabled]" : "") unless $quiet;
772    }
773
774    $made_changes = 1;
775}
776
777sub check
778{
779    my $result;
780    foreach my $proggy (keys %$grabbers) {
781        $result = test_proggy("$GRABBER_DIR/$proggy","$GRABBER_DIR/$proggy/$proggy");
782        printf "Grabber %s: %s\n",$proggy,($result ? "OK" : "Failed");
783        if (!$result ne !$grabbers->{$proggy}->{ready}) {
784            $grabbers->{$proggy}->{ready} = $result;
785            $made_changes = 1;
786        }
787    }
788
789    foreach my $proggy (keys %$postprocessors) {
790        $result = test_proggy("$POSTPROCESSOR_DIR/$proggy","$POSTPROCESSOR_DIR/$proggy/$proggy");
791        printf "Postprocessor %s: %s\n",$proggy,($result ? "OK" : "Failed");
792        if (!$result ne !$postprocessors->{$proggy}->{ready}) {
793            $postprocessors->{$proggy}->{ready} = $result;
794            $made_changes = 1;
795        }
796    }
797}
798
799# -----------------------------------------
800# Subs: Setup
801# -----------------------------------------
802
803sub read_config_file
804{
805    read_file($config_file, 'configuration');
806
807    # if we are updating from a previous rev of shepherd.conf we may not
808    # have any 'order' fields set .. check here
809    my $found_order = 1;
810    foreach (keys %$grabbers)
811    {
812        $found_order = 0 if (!defined $grabbers->{$_}->{order});
813    }
814    if (($found_order == 0) && (!$opt->{setorder}))
815    {
816        # at least one 'order' was missing .. we need to put it in!
817        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";
818        &set_order(1);
819    }
820}
821
822sub read_channels_file
823{
824    read_file($channels_file, 'channels');
825}
826
827sub read_file
828{
829    my $fn = shift;
830    my $name = shift;
831
832    print "Reading $name file: $fn\n";
833    unless (-r $fn)
834    {
835        unless ($opt->{configure})
836        {
837            print "\nNo $name file found.\n" .
838                  ucfirst($progname) . " must be configured: " .
839                  "configuring now.\n\n";
840            $opt->{'configure'} = 1;
841        }
842        return;
843    }
844    local (@ARGV, $/) = ($fn);
845    no warnings 'all';
846    eval <>;
847    if ($@ and !$opt->{configure})
848    {
849        die "\nError in $name file!\nDetails:\n$@";
850    }
851}
852
853sub write_config_file
854{
855    open(CONF, ">$config_file") or die "cannot write to $config_file: $!";
856    print CONF Data::Dumper->Dump(
857        [$region,  $pref_order,   $grabbers, $postprocessors  ],
858        ["region", "pref_order", "grabbers", "postprocessors" ]);
859    close CONF;
860    print "\nUpdated configuration file $config_file.\n" if ($debug);
861}
862
863sub write_channels_file
864{
865    open(CHAN, ">$channels_file") or die "cannot write to $channels_file: $!";
866    print CHAN Data::Dumper->Dump([$channels], ["channels"]);
867    close CHAN;
868    print "Updated channels file $channels_file.\n" if ($debug);
869}
870
871sub get_initial_command_line_options
872{
873  GetOptions( 'config-file=s'   => \$opt->{configfile},
874              'help'            => \$opt->{help},
875              'configure'       => \$opt->{configure},
876              'output'          => \$opt->{output},
877              'debug'           => \$debug);
878}
879
880sub get_remaining_command_line_options
881{
882    GetOptions(
883              'version'         => \$opt->{status},
884              'status'          => \$opt->{status},
885              'list'            => \$opt->{list},
886              'show-config'     => \$opt->{show_config},
887
888              'update'          => \$opt->{update},
889              'noupdate'        => \$opt->{noupdate},
890
891              'disable=s'       => \$opt->{disable},
892              'enable=s'        => \$opt->{enable},
893              'setorder=s'      => \$opt->{setorder},
894
895              'days=i'          => \$days,
896              'offset=i'        => \$opt->{offset},
897              'show-channels'   => \$opt->{show_channels},
898              'output=s'        => \$opt->{output},
899              'check'           => \$opt->{check}
900            );
901}
902
903
904# -----------------------------------------
905# Subs: Configuration
906# -----------------------------------------
907
908sub configure
909{
910    my $REGIONS = {
911        "ACT" => 126,
912        "NSW: Sydney" => 73,
913        "NSW: Newcastle" => 184,
914        "NSW: Central Coast" => 66,
915        "NSW: Griffith" => 67,
916        "NSW: Broken Hill" => 63,
917        "NSW: Northern NSW" => 69,
918        "NSW: Southern NSW" => 71,
919        "NSW: Remote and Central" => 106,
920        "NT: Darwin" => 74,
921        "NT: Remote & Central" => 108,
922        "QLD: Brisbane" => 75,
923        "QLD: Gold Coast" => 78,
924        "QLD: Regional" => 79,
925        "QLD: Remote & Central" => 114,
926        "SA: Adelaide" => 81,
927        "SA: Renmark" => 82,
928        "SA: Riverland" => 83,
929        "SA: South East SA" => 85,
930        "SA: Spencer Gulf" => 86,
931        "SA: Remote & Central" => 107,
932        "Tasmania" => 88,
933        "VIC: Melbourne" => 94,
934        "VIC: Geelong" => 93,
935        "VIC: Eastern Victoria" => 90,
936        "VIC: Mildura/Sunraysia" => 95,
937        "VIC: Western Victoria" => 98,
938        "WA: Perth" => 101,
939        "WA: Regional" => 102
940    };
941
942    print "\nConfiguring.\n\n" .
943          "Select your region:\n";
944    foreach (sort keys %$REGIONS)
945    {
946        printf(" (%3d) %s\n", $REGIONS->{$_}, $_);
947    }
948    $region = ask_choice("Enter region code:", "94", values %$REGIONS);
949
950    print "\nFetching channel information... ";
951
952    my @channellist = get_channels();
953
954    print "done.\n\n" .
955          "For each channel you want guide data for, enter an XMLTV id\n" .
956          "of your choice (e.g. \"seven.free.au\"). If you don't need\n" .
957          "guide data for this channel, just press Enter.\n\n" .
958          "Please don't subscribe to unneeded channels.\n\nChannels:\n";
959    $channels = {};
960    my $line;
961    foreach (@channellist)
962    {
963        $line = ask(" \"$_\"? ");
964        $channels->{$_} = $line if ($line);
965    }
966
967
968    print "\nRandomly selecting grabber order.\n\n";
969    set_order(0);
970
971    show_channels();
972    unless(ask_boolean("\nCreate configuration file?"))
973    {
974        print "Aborting configuration.\n";
975        exit 0;
976    }
977
978    write_config_file();
979    write_channels_file();
980
981    print "Finished configuring.\n\n" .
982          "Shepherd is installed into $CWD.\n\n";
983   
984    if ($invoked ne "$CWD/$progname" and $invoked =~ /$progname/)
985    {
986        print "Warning: you invoked this program as $invoked.\n" .
987            "In the future, it should be run as $CWD/$progname,\n" .
988            "to avoid constantly re-downloading the latest version.\n\n" .
989            "MythTV users may wish to create the following symlink, by " .
990            "doing this (as root):\n" .
991            "\"ln -s $CWD/$progname /usr/bin/tv_grab_au\".\n\n" .
992            "You may safely delete $invoked.\n\n";
993    }
994
995    status();
996
997    unless (ask_boolean("\nGrab data now?"))
998    {
999        exit 0;
1000    }
1001}
1002
1003sub get_channels
1004{
1005    my @date = localtime;
1006    my $page = LWP::Simple::get(
1007        "http://au.tv.yahoo.com/results.html?rg=$region&dt=" .
1008        ($date[5] + 1900) . "-$date[4]-$date[3]");
1009    my @channellist;
1010    while ($page =~ /<tr class=rtb><td class=rth><a .*?>(.*?)<\/a>/g)
1011    {
1012        push @channellist, $1;
1013    }
1014    return @channellist;
1015}
1016
1017# -----------------------------------------
1018# Subs: Status & Help
1019# -----------------------------------------
1020
1021sub show_config
1022{
1023    print "\nConfiguration\n".
1024          "-------------\n" .
1025          "Config file: $config_file\n" .
1026          "Debug mode : " . is_set($debug) . "\n" .
1027          "Output file: " . ($opt->{output} ? $opt->{output} : "None") . "\n" .
1028          "Region ID  : $region\n";
1029  show_channels();
1030  print "\n";
1031  status();
1032  print "\n";
1033}
1034
1035sub show_channels
1036{
1037  print "Subscribed channels:\n";
1038  print "    $_ -> $channels->{$_}\n" for sort keys %$channels;
1039}
1040
1041sub is_set
1042{
1043    my $arg = shift;
1044    return $arg ? "Yes" : "No";
1045}
1046
1047sub status
1048{
1049    print " Grabber           Version Enabled Ready Last Run   Status\n" .
1050          " ----------------- ------- ------- ----- ---------- ---------------------------\n";
1051    foreach (sort { $grabbers->{$a}->{order} <=> $grabbers->{$b}->{order} } keys %$grabbers) {
1052        my $h = $grabbers->{$_};
1053        printf  " %-16s %8s %4s %6s  %11s %s\n",
1054                "$h->{order}. $_",
1055                $h->{ver},
1056                $h->{disabled} ? '' : 'Y',
1057                $h->{ready} ? 'Y' : '',
1058                $h->{lastdata} ? (strftime "%a%d%b%y", localtime($h->{lastdata})) : '',
1059                $h->{laststatus} ? $h->{laststatus} : '';
1060    }
1061    printf "Grabbers shown in order of preference.\n\n";
1062
1063    print " Postprocessor     Version Enabled Ready Last Run   Status\n" .
1064          " ----------------- ------- ------- ----- ---------- ---------------------------\n";
1065    foreach (sort { $postprocessors->{$a} <=> $postprocessors->{$b} } keys %$postprocessors) {
1066        my $h = $postprocessors->{$_};
1067        printf  " %-16s %8s %4s %6s  %11s %s\n",
1068                $_,
1069                $h->{ver},
1070                $h->{disabled} ? '' : 'Y',
1071                $h->{ready} ? 'Y' : '',
1072                $h->{lastdata} ? (strftime "%a%d%b%y", localtime($h->{lastdata})) : '',
1073                $h->{laststatus} ? $h->{laststatus} : '';
1074    }
1075    printf "Postprocessors shown in order of execution.\n\n";
1076}
1077
1078sub help
1079{
1080    print q{
1081Command-line options:
1082    --help                Print this message
1083
1084    --status              Print a list of grabbers maintained
1085    --list                Print a detailed list of grabbers
1086
1087    --configure           Setup
1088    --show-config         Print setup details
1089
1090    --setorder <s>        Set order of grabbers to <s> (comma-seperated list of grabbers)
1091
1092    --disable <s>         Don't ever use grabber/postprocessor <s>
1093    --enable <s>          Okay, maybe use it again then
1094    --uninstall <s>       Remove a disabled grabber/postprocessor
1095
1096    --noupdate            Do not attempt to update before running
1097    --update              Update only; do not grab data
1098
1099    --check               Check status of all grabbers and postprocessors
1100};
1101    exit 0;
1102}
Note: See TracBrowser for help on using the browser.