- Adapt plugins to documentation
[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'} = 'video';
47     $metadata->{'SOURCE'} = 'youtube';
48     $metadata->{'TITLE'} = undef;
49     $metadata->{'DLURL'} = undef;
50
51     unless(defined($content = LWP::Simple::get(sprintf('http://youtube.com/watch?v=%s', $2)))) {
52         $self->error('Could not download %s', $url);
53         return undef;
54     }
55
56     $p->handler(start => \@accum, "tagname, attr");
57     $p->handler(text => \@text, "text");
58     $p->report_tags(qw(meta script));
59     $p->utf8_mode(1);
60     $p->parse($content);
61
62     # Look for the title in the meta tags
63     foreach $e (@accum) {
64         if ('meta' eq $e->[0]) {
65             if ('title' eq $e->[1]->{'name'}) {
66                 $metadata->{'TITLE'} = $e->[1]->{'content'};
67             }
68         }
69     }
70
71     # Look for the download URL
72     foreach $e (@text) {
73         if ($e->[0] =~ m|/watch_fullscreen\?(.*)\&fs|) {
74             $metadata->{'DLURL'} = 'http://www.youtube.com/get_video.php?' . $1;
75         }
76     }
77
78     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
79         $self->error('Could not determine download URL');
80         return undef;
81     }
82
83     return $metadata;
84 }
85
86 1;