- Initial checkin
[videosite.git] / videosite / YouTubeGrabber.pm
1 package YouTubeGrabber;
2
3 use GrabberBase;
4 @ISA = qw(GrabberBase);
5
6 use LWP::Simple qw(!get);
7 use HTML::Parser;
8 use Data::Dumper;
9
10 use strict;
11
12 sub new {
13     my $class = shift;
14     my $self = $class->SUPER::new();
15
16     $self->{'NAME'} = 'youtube';
17     $self->{'PATTERNS'} = ['(http://(?:[-a-zA-Z0-9_.]+\.)*youtube.(?:com|de|co.uk)/watch\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
18                            '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))'];
19
20     bless($self, $class);
21     $self->_prepare_parameters();
22
23     return $self;
24 }
25
26 sub _parse {
27     my $self = shift;
28     my $url = shift;
29     my $pattern = shift;
30     my $content;
31     my $metadata = {};
32     my $p = HTML::Parser->new(api_version => 3);
33     my @accum;
34     my @text;
35     my $e;
36
37     $url =~ m|$pattern|;
38     $url = $1;
39
40     $metadata->{'URL'} = $url;
41     $metadata->{'ID'} = $2;
42     $metadata->{'TYPE'} = 'youtube';
43     $metadata->{'TITLE'} = undef;
44     $metadata->{'DLURL'} = undef;
45
46     unless(defined($content = LWP::Simple::get(sprintf('http://youtube.com/watch?v=%s', $2)))) {
47         $self->error('Could not download %s', $url);
48         return undef;
49     }
50
51     $p->handler(start => \@accum, "tagname, attr");
52     $p->handler(text => \@text, "text");
53     $p->report_tags(qw(meta script));
54     $p->utf8_mode(1);
55     $p->parse($content);
56
57     # Look for the title in the meta tags
58     foreach $e (@accum) {
59         if ('meta' eq $e->[0]) {
60             if ('title' eq $e->[1]->{'name'}) {
61                 $metadata->{'TITLE'} = $e->[1]->{'content'};
62             }
63         }
64     }
65
66     # Look for the download URL
67     foreach $e (@text) {
68         if ($e->[0] =~ m|/watch_fullscreen\?(.*)\&fs|) {
69             $metadata->{'DLURL'} = 'http://www.youtube.com/get_video.php?' . $1;
70         }
71     }
72
73     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
74         $self->error('Could not determine download URL');
75         return undef;
76     }
77
78     return $metadata;
79 }
80
81 1;