1 # (c) 2007 by Ralf Ertzinger <ralf@camperquake.de>
2 # licensed under GNU GPL v2
4 # Grabber for youtube.com/de/...
6 # download strategy revised using
7 # http://www.kde-apps.org/content/show.php?content=41456
9 package videosite::YouTubeGrabber;
11 use videosite::GrabberBase;
12 @ISA = qw(videosite::GrabberBase);
17 use HTML::Entities qw(decode_entities);
20 use videosite::JSArrayParser;
26 my $self = $class->SUPER::new();
28 $self->{'NAME'} = 'youtube';
29 $self->{'PATTERNS'} = ['(http://(?:[-a-zA-Z0-9_.]+\.)*youtube.(?:com|de|co.uk)/watch\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
30 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))'];
31 $self->{'_PARAMS'} = {
32 'QUALITY' => ['normal', 'Quality of the video to download.', {
33 'normal' => 'standard resolution flash video',
34 'high' => 'higher resolution flash video',
35 'h264' => 'high resolution MPEG4 video',
36 'hd' => 'HD720 resolution'}],
37 'USERNAME' => ['', 'Username to use for YouTube login'],
38 'PASSWORD' => ['', 'Password to use for YouTube login']};
41 $self->_prepare_parameters();
55 my $jar = HTTP::Cookies->new;
56 my $ua = LWP::UserAgent->new('agent' => 'Mozilla/5.0');
59 my $quality = $self->_getval('QUALITY');
61 'hd' => [37, 22, 35, 18, 34, 6, 5],
62 'h264' => [18, 34, 37, 22, 35, 6, 5],
63 'high' => [34, 35, 18, 37, 22, 6, 5],
64 'normal' => [6, 5, 34, 35, 18, 22, 37]);
71 $metadata->{'URL'} = $url;
72 $metadata->{'ID'} = $2;
73 $metadata->{'TYPE'} = 'video';
74 $metadata->{'SOURCE'} = $self->{'NAME'};
75 $metadata->{'TITLE'} = undef;
76 $metadata->{'DLURL'} = undef;
78 $preflist = $preflist{$quality};
79 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
81 $videourl = sprintf('http://www.youtube.com/watch?v=%s', $2);
83 unless(defined($r = $ua->get($videourl))) {
84 $self->error('Could not download %s', $url);
88 if ($r->base->as_string() =~ m,/verify_age,) {
89 $self->debug('Video requires age verification');
90 $ua->cookie_jar($jar);
91 $r = $self->__login($videourl, $ua);
93 $self->error('Could not log into YouTube');
97 $content = $r->content();
99 $p = HTML::TokeParser->new(\$content);
101 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
102 if ('meta' eq $tag->[0]) {
103 if ('title' eq $tag->[1]->{'name'}) {
104 $metadata->{'TITLE'} = $tag->[1]->{'content'};
105 # Convert HTML entities in the title. This is a bit convoluted.
106 $metadata->{'TITLE'} = encode("utf8",
108 decode("utf8", $metadata->{'TITLE'})));
110 $self->debug('Title found: %s', $metadata->{'TITLE'});
112 } elsif ('script' eq $tag->[0]) {
114 $self->debug("Found script: %s", $e);
115 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
119 $self->debug("Found SWF_ARGS: %s", $args);
120 $jsp = videosite::JSArrayParser->new();
121 $self->debug("Using %s to parse", ref($jsp));
122 $r = $jsp->parse($args);
124 unless(defined($r)) {
125 $self->error("Found information hash, but could not parse");
129 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
130 my $urls = $r->{'fmt_url_map'};
132 $self->debug("Video has fmt_url_map: %s", $urls);
134 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
135 %urls = split(/[\|,]/, $urls);
136 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
137 my $thash = $r->{'t'};
139 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
140 my $fmt = $r->{'fmt_map'};
143 $self->debug('Video has fmt_map');
144 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
145 @fmt = split(/,/, $fmt);
148 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
154 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
159 $self->error('Neither fmt_url_map nor t found in video information hash');
162 $self->debug("Found quality levels [%s]", join(", ", keys(%urls)));
164 foreach (keys(%urls)) {
166 $self->debug('Found flv,h264,large: %s', $urls{$_});
168 $self->debug('Found flv,h264: %s', $urls{$_});
170 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
172 $self->debug('Found mp4,h264,1080p: %s', $urls{$_});
174 $self->debug('Found mp4,h264: %s', $urls{$_});
176 $self->debug('Found flv,flv: %s', $urls{$_});
178 $self->error('Unknown tag %s: %s', $_, $urls{$_});
182 foreach (@{$preflist}) {
183 if (exists($urls{$_})) {
184 $self->debug("Selected URL with quality level %s", $_);
185 $metadata->{'DLURL'} = $urls{$_};
190 $self->debug('URL found: %s', $metadata->{'DLURL'});
193 } elsif ('div' eq $tag->[0]) {
194 if (exists($tag->[1]->{'class'}) and ('errorBox' eq $tag->[1]->{'class'})) {
195 $self->error("Could not get video data for youtube %s: %s",
196 $metadata->{'ID'}, $p->get_trimmed_text());
202 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
203 $self->error('Could not determine download URL');
212 my $videourl = shift;
214 my $user = $self->_getval('USERNAME');
215 my $pass = $self->_getval('PASSWORD');
227 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
232 if (($user eq '') or ($pass eq '')) {
233 $self->error('No username or password defined for YouTube');
237 $self->debug('Logging in');
238 $r = $ua->post('http://www.youtube.com/signup', { 'next' => '/', 'current_form' => 'login', 'action_login' => '1', 'username' => $user, 'password' => $pass });
240 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
241 $self->error('Could not log into YouTube');
245 $r = $ua->get($videourl);
246 if ($r->base->as_string() =~ m,/verify_age,) {
247 $self->debug("Looking for session token...");
248 $c = $r->decoded_content();
249 $p = HTML::TokeParser->new(\$c);
250 while (my $tag = $p->get_tag('script')) {
251 if ($p->get_text() =~ /gXSRF_token = '(.+)'/) {
257 unless(defined($token)) {
258 $self->error("Could not find session token");
262 $self->debug('Authenticating session...');
263 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
266 unless(check_cookie($ua->cookie_jar, 'is_adult')) {
267 $self->error('Could not authenticate session');
271 return $ua->get($videourl);