root/shepherd @ 12

Revision 12, 35.6 kB (checked in by lincoln, 7 years ago)

--mirror support added with fallback to whuffy if all mirrors are down

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