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);
15 use HTML::Entities qw(decode_entities);
18 use videosite::JSArrayParser;
23 'insane' => [38, 37, 22, 35, 18, 34, 6, 5, 43],
24 'hd' => [37, 22, 35, 18, 34, 6, 5, 38, 43],
25 'h264' => [18, 34, 37, 22, 35, 6, 5, 38, 43],
26 'high' => [34, 35, 18, 37, 22, 6, 5, 38, 43],
27 'normal' => [6, 5, 34, 35, 18, 22, 37, 38, 43]);
31 37 => 'mp4,h264,1080p',
32 35 => 'flv,h264,large',
34 22 => 'mp4,h264,720p',
41 my $self = $class->SUPER::new();
43 $self->{'NAME'} = 'youtube';
44 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
45 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
46 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
47 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
48 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
49 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
50 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
51 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
52 $self->{'_PARAMS'} = {
53 'QUALITY' => ['normal', 'Quality of the video to download.', {
54 'normal' => 'standard resolution flash video',
55 'high' => 'higher resolution flash video',
56 'h264' => 'high resolution MPEG4 video',
57 'hd' => 'HD720 resolution'}],
58 'USERNAME' => ['', 'Username to use for YouTube login'],
59 'PASSWORD' => ['', 'Password to use for YouTube login']};
62 $self->_prepare_parameters();
74 my $url =~ m|$pattern|;
78 $self->debug("Matched id %s from pattern %s", $id, $pattern);
80 $res = $self->_parse_by_video_info($url, $id);
81 if (defined($res) && ref($res)) {
84 $res = $self->_parse_by_scrape($url, $id);
90 sub _parse_by_video_info {
94 my $quality = $self->_getval('QUALITY');
103 $metadata->{'URL'} = $url;
104 $metadata->{'ID'} = $id;
105 $metadata->{'TYPE'} = 'video';
106 $metadata->{'SOURCE'} = $self->{'NAME'};
107 $metadata->{'TITLE'} = undef;
108 $metadata->{'DLURL'} = undef;
109 $metadata->{'COOKIE'} = undef;
111 $preflist = $preflist{$quality};
112 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
114 $videourl = sprintf('https://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
115 $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
116 $self->debug("Video info URL: %s", $videourl);
118 $r = $ua->get($videourl);
119 unless($r->is_success()) {
120 $self->debug('Could not download %s: %s', $videourl, $r->code());
124 $content = $r->content();
125 $self->debug('Content from get_video_info: %s', $content);
128 $content = { split /[&=]/, $content };
130 if ($content->{'status'} ne 'ok') {
131 $self->debug("Non OK status code found: %s", $content->{'status'});
135 unless(exists($content->{'fmt_url_map'}) and exists($content->{'title'})) {
136 $self->debug("No fmt_url_map or no title found");
141 $urls = $content->{'fmt_url_map'};
142 $urls =~ s/%(..)/chr(hex($1))/ge;
143 $urls = { split /[\|,]/, $urls };
145 $self->__pick_url($urls, $preflist, $metadata);
147 $metadata->{'TITLE'} = $content->{'title'};
148 $metadata->{'TITLE'} =~ s/\+/ /g;
149 $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
150 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
152 $self->debug('Title found: %s', $metadata->{'TITLE'});
154 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
155 $self->error('Could not determine download URL');
162 sub _parse_by_scrape {
171 my $ua = $self->ua();
174 my $quality = $self->_getval('QUALITY');
178 $metadata->{'URL'} = $url;
179 $metadata->{'ID'} = $id;
180 $metadata->{'TYPE'} = 'video';
181 $metadata->{'SOURCE'} = $self->{'NAME'};
182 $metadata->{'TITLE'} = undef;
183 $metadata->{'DLURL'} = undef;
184 $metadata->{'COOKIE'} = undef;
187 $preflist = $preflist{$quality};
188 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
190 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $id);
192 unless(defined($r = $ua->get($videourl))) {
193 $self->error('Could not download %s', $url);
197 if ($r->base->as_string() =~ m,/verify_age,) {
198 $self->debug('Video requires age verification');
199 my @logindata = $self->__login($videourl, $ua);
201 $metadata->{'COOKIE'} = $logindata[1];
202 unless(defined($r)) {
203 $self->error('Could not log into YouTube');
207 $content = $r->content();
209 $p = HTML::TokeParser->new(\$content);
211 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
212 if ('meta' eq $tag->[0]) {
213 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
214 $metadata->{'TITLE'} = $tag->[1]->{'content'};
215 # Convert HTML entities in the title. This is a bit convoluted.
216 $metadata->{'TITLE'} = decode_entities(
217 decode("utf8", $metadata->{'TITLE'}));
219 $self->debug('Title found: %s', $metadata->{'TITLE'});
221 } elsif ('script' eq $tag->[0]) {
225 $self->debug("Found script: %s", $e);
227 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
230 $self->debug("Found SWF_ARGS: %s", $args);
231 $jsp = videosite::JSArrayParser->new();
232 $self->debug("Using %s to parse", ref($jsp));
233 $r = $jsp->parse($args);
235 unless(defined($r)) {
236 $self->error("Found information hash, but could not parse");
240 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
241 my $urls = $r->{'fmt_url_map'};
243 $self->debug("Video has fmt_url_map: %s", $urls);
245 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
246 %urls = split(/[\|,]/, $urls);
247 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
249 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
250 my $thash = $r->{'t'};
252 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
253 my $fmt = $r->{'fmt_map'};
256 $self->debug('Video has fmt_map');
257 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
258 @fmt = split(/,/, $fmt);
261 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
266 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
269 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
272 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
275 $self->error('Neither fmt_url_map nor t found in video information hash');
278 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
280 $self->debug("Video has fmt_url_map: %s", $urls);
282 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
283 %urls = split(/[\|,]/, $urls);
284 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
285 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
287 $self->debug("Found PLAYER_CONFIG: %s", $args);
289 $jsp = videosite::JSArrayParser->new();
290 $self->debug("Using %s to parse", ref($jsp));
291 $r = $jsp->parse($args);
293 unless(defined($r)) {
294 $self->error("Found information hash, but could not parse");
298 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
299 $self->error("Video URL seems to point to a live stream, cannot save this");
303 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
304 my $urls = $r->{'args'}->{'fmt_url_map'};
306 $self->debug("Video has fmt_url_map: %s", $urls);
308 %urls = split(/[\|,]/, $urls);
309 foreach (keys(%urls)) {
311 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
314 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
316 $self->error('fmt_url_map not found in PLAYER_CONFIG');
322 $self->__pick_url(\%urls, $preflist, $metadata);
325 } elsif ('div' eq $tag->[0]) {
326 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
327 # Search forward to the next <div>
328 $tag = $p->get_tag('div');
329 $self->error("Could not get video data for youtube %s: %s",
330 $metadata->{'ID'}, $p->get_trimmed_text());
336 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
337 $self->error('Could not determine download URL');
346 my $videourl = shift;
348 my $user = $self->_getval('USERNAME');
349 my $pass = $self->_getval('PASSWORD');
361 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
366 sub get_all_cookies {
371 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
376 if (($user eq '') or ($pass eq '')) {
377 $self->error('No username or password defined for YouTube');
381 $self->debug('Logging in');
382 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
383 unless($r->is_success()) {
384 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
387 $c = $r->decoded_content();
388 $p = HTML::TokeParser->new(\$c);
389 while (my $tag = $p->get_tag('input')) {
390 $self->debug("%s", Dumper($tag));
391 if ($tag->[1]{name} eq 'GALX') {
392 $token = $tag->[1]{value};
396 $self->debug("GALX = %s", $token);
397 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
398 unless($r->is_success()) {
399 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
402 $c = $r -> decoded_content();
403 $p = HTML::TokeParser->new(\$c);
404 while (my $tag = $p->get_tag('script')) {
405 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
407 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
411 $r = $ua->get($token);
412 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
413 $self->error('Could not log into YouTube');
417 $self->debug("Got a cookie");
419 $r = $ua->get($videourl);
420 if ($r->base->as_string() =~ m,/verify_age,) {
421 $self->debug("Looking for session token...");
422 $c = $r->decoded_content();
423 $p = HTML::TokeParser->new(\$c);
424 while (my $tag = $p->get_tag('script')) {
425 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
431 unless(defined($token)) {
432 $self->error("Could not find session token");
436 $self->debug('Authenticating session...');
437 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
440 # Apparently there is no longer a specific "is_adult" cookie
441 # or, by the looks of it, anything similar
443 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
444 # $self->error('Could not authenticate session');
448 my $cookie = get_all_cookies($ua->cookie_jar);
449 return ($ua->get($videourl), $cookie);
455 my $preflist = shift;
456 my $metadata = shift;
458 foreach (keys(%{$urls})) {
459 if (exists($videoformats{$_})) {
460 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
462 $self->error('Unknown format %s: %s', $_, $urls->{$_});
466 foreach (@{$preflist}) {
467 if (exists($urls->{$_})) {
468 $self->debug("Selected URL with quality level %s", $_);
469 $metadata->{'DLURL'} = $urls->{$_};
474 $self->debug('URL found: %s', $metadata->{'DLURL'});