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