videosite-dl: Add -i command line option to print information instead of downloading
[videosite.git] / videosite-dl.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Getopt::Long;
5 use File::Spec;
6 use File::Basename;
7 use Cwd qw(realpath);
8
9 sub ploader {
10
11     my $dir = shift;
12     my $pattern = shift;
13     my $type = shift;
14     my @list;
15     my $p;
16     my $g;
17     my @g = ();
18
19     unshift(@INC, $dir);
20
21     opendir(D, $dir) || return ();
22     @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
23     closedir(D);
24
25     foreach $p (@list) {
26         $p =~ s/\.pm$//;
27         eval qq{ require videosite::$p; };
28         if ($@) {
29             print("Failed to load plugin: $@");
30             next;
31         }
32
33         $g = eval qq{ videosite::$p->new();};
34         if ($@) {
35             print("Failed to instanciate: $@");
36             delete($INC{$p});
37             next;
38         }
39
40         if ($type eq $g->{'TYPE'}) {
41             push(@g, $g);
42         } else {
43             printf('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
44             delete($INC{$p});
45         }
46     }
47
48     return @g;
49 }
50
51 my $hq = 0;
52 my $ext = '.flv';
53 my $y;
54 my $f;
55 my $m;
56 my @g;
57 my $bp;
58 my $info = 0;
59
60 GetOptions("i" => \$info);
61
62 # This is some dark magic to find out our real base directory,
63 # where we hope to find our plugins.
64 $bp = File::Spec->catdir(dirname(realpath($0)), 'videosite');
65 unshift(@INC, dirname(realpath($0)));
66
67 @g = ploader($bp, '.*Grabber\.pm$', 'grabber');
68 ($f) = ploader($bp, '^FileGetter\.pm$', 'getter');
69
70 unless(@g and defined($f)) {
71     print("No plugins could be loaded\n");
72     exit 1;
73 }
74
75 $f->setval('FILEPATTERN', './%3$s' . $ext);
76
77 foreach (@ARGV) {
78     foreach $y (@g) {
79         ($m, undef) = $y->get($_);
80         if (defined($m)) {
81             if ($info) {
82                 foreach (keys(%{$m})) {
83                     printf("%s: %s\n", $_, defined($m->{$_})?$m->{$_}:'(undef)');
84                 }
85             } else {
86                 print("Downloading $m->{'TITLE'}\n");
87                 $f->get($m);
88             }
89         }
90     }
91 }