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, 137, 22, 136, 35, 135, 18, 134, 34, 6, 5, 43],
24 'hd' => [37, 137, 22, 136, 35, 135, 18, 134, 34, 6, 5, 38, 43],
25 'h264' => [18, 134, 34, 37, 137, 22, 136, 35, 135, 6, 5, 38, 43],
26 'high' => [34, 35, 135, 18, 134, 37, 137, 22, 136, 6, 5, 38, 43],
27 'normal' => [6, 5, 34, 35, 135, 18, 134, 22, 136, 37, 137, 38, 43]);
29 'insane' => [172,141,171,140,139],
30 'hd' => [172,141,171,140,139],
31 'h264' => [172,141,171,140,139],
32 'high' => [171,140,172,141,139],
33 'normal' => [171,140,172,141,139]);
35 # Container/Video codec/Audio codec/Resolution
36 5 => 'FLV/Sorenson/MP3/240p',
37 6 => 'FLV/Sorenson/MP3/270p',
38 13 => '3GP/MPEG4-Visual/144p', # 0.5MBit
39 17 => '3GP/MPEG4-Visual/144p', # 2MBit
40 18 => 'MP4/H264/AAC/360p', # isommp42, Baseline
41 22 => 'MP4/H264/AAC/720p', # isommp42, High
42 34 => 'FLV/H264/AAC/360p', # Main
43 35 => 'FLV/H264/AAC/480p', # Main
44 36 => '3GP/MPEG4-Visual/240p',
45 37 => 'MP4/H264/AAC/1080p', # High
46 38 => 'MP4/H264/AAC/3072p', # High
47 43 => 'WebM/VP8/Vorbis/360p',
48 44 => 'WebM/VP8/Vorbis/480p',
49 45 => 'WebM/VP8/Vorbis/720p',
50 46 => 'WebM/VP8/Vorbis/1080p/3D', # effective 540p
51 82 => 'MP4/H264/AAC/360p/3D', # isomavc1mp42
52 83 => 'MP4/H264/AAC/240p/3D', # isomavc1mp42
53 84 => 'MP4/H264/AAC/720p/3D', # isomavc1mp42
54 85 => 'MP4/H264/AAC/1080p/3D', # isomavc1mp42, effective 540p
55 100 => 'WebM/VP8/Vorbis/360p/3D',
56 101 => 'WebM/VP8/Vorbis/480p/3D',
57 102 => 'WebM/VP8/Vorbis/720p/3D',
58 133 => 'MP4/H264/240p/AdaptiveVideo',
59 134 => 'MP4/H264/360p/AdaptiveVideo',
60 135 => 'MP4/H264/480p/AdaptiveVideo',
61 136 => 'MP4/H264/720p/AdaptiveVideo',
62 137 => 'MP4/H264/1080p/AdaptiveVideo',
63 139 => 'MP4/AAC/48kbit/AdaptiveAudio',
64 140 => 'MP4/AAC/128kbit/AdaptiveAudio',
65 141 => 'MP4/AAC/256kbit/AdaptiveAudio',
66 160 => 'MP4/H264/144p/AdaptiveVideo',
67 171 => 'WebM/Vorbis/128kbit/AdaptiveAudio',
68 172 => 'WebM/Vorbis/160kbit/AdaptiveAudio',
73 my $self = $class->SUPER::new(
75 _SELFTESTURL => 'http://www.youtube.com/watch?v=dMH0bHeiRNg',
76 _SELFTESTTITLE => 'Evolution of Dance - By Judson Laipply',
77 PATTERNS => ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?.*?v=([-a-zA-Z0-9_]+))',
78 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
79 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
80 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/embed/([-a-zA-Z0-9_]+))',
81 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
82 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
83 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
84 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
85 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'],
87 QUALITY => ['normal', 'Quality of the video to download.', {
88 normal => 'standard resolution flash video',
89 high => 'higher resolution flash video',
90 h264 => 'high resolution MPEG4 video',
91 hd => 'HD720 resolution'}],
92 USERNAME => ['', 'Username to use for YouTube login'],
93 PASSWORD => ['', 'Password to use for YouTube login'],
94 HTTPS => [1, 'Whether to use HTTPS (if available) to connect to YouTube'],
95 ADAPTIVE => [0, 'Whether to use adaptive rate URLs (if available)'],
100 return bless($self, $class);
114 $self->debug("Matched id %s from pattern %s", $id, $pattern);
116 $res = $self->_parse_by_video_info($url, $id);
121 $self->debug("_parse_by_video_info failed with status noretry");
125 $self->debug("_parse_by_video_info failed with status retry");
126 $res = $self->_parse_by_scrape($url, $id);
133 # Try to get video information by using the API call.
135 # Returns hashref on success
136 # Returns undef on retryable error (try to scrape the website)
137 # Returns 0 on non-retryable error
139 sub _parse_by_video_info {
143 my $quality = $self->_getval('QUALITY');
146 my $ua = $self->ua();
153 $metadata->{'URL'} = $url;
154 $metadata->{'ID'} = $id;
155 $metadata->{'TYPE'} = 'video';
156 $metadata->{'SOURCE'} = $self->{'NAME'};
157 $metadata->{'TITLE'} = undef;
158 $metadata->{'DLURL'} = undef;
160 $preflist = $preflist{$quality};
161 $audiopreflist = $audiopreflist{$quality};
162 $self->debug("Quality: %s, preflist: [%s], audiopreflist: [%s]",
164 join(", ", @{$preflist}),
165 join(", ", @{$audiopreflist}));
167 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
168 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
169 $self->debug("Video info URL: %s", $videourl);
171 $r = $ua->get($videourl);
172 unless($r->is_success()) {
173 $self->debug('Could not download %s: %s', $videourl, $r->code());
177 $content = $r->content();
178 $self->debug('Content from get_video_info: %s', $content);
181 $content = $self->decode_querystring($content);
183 $self->debug("Decoded get_video_info: %s", Dumper($content));
185 if ($content->{'status'} ne 'ok') {
186 $self->debug("Non OK status code found: %s", $content->{'status'});
190 # Check if this is live content
191 if (exists($content->{ps}) and ($content->{ps} eq 'live')) {
192 $self->error("Video URL seems to point to a live stream, cannot save this");
196 if (exists($content->{'fmt_url_map'})) {
198 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
199 $urls = { split /[\|,]/, $urls };
200 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
201 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
203 $self->debug("No URL data found");
207 if (exists($content->{'adaptive_fmts'})) {
208 $self->debug('Video has adaptive_fmts');
209 if ($self->_getval('ADAPTIVE')) {
210 my %af = %{$self->_decode_url_encoded_fmt_stream_map($content->{'adaptive_fmts'}, 1)};
211 while (my ($k, $v) = each %af) {
215 $self->debug('Use of adaptive URLs not enabled');
219 unless(exists($content->{'title'})) {
220 $self->debug("No title found");
224 $self->__pick_url($urls, $preflist, $audiopreflist, $metadata);
226 $metadata->{'TITLE'} = $content->{'title'};
227 $metadata->{'TITLE'} =~ s/\+/ /g;
228 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
229 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
231 $self->debug('Title found: %s', $metadata->{'TITLE'});
233 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
234 $self->error('Could not determine download URL');
241 sub _parse_by_scrape {
250 my $ua = $self->ua();
253 my $quality = $self->_getval('QUALITY');
257 $metadata->{'URL'} = $url;
258 $metadata->{'ID'} = $id;
259 $metadata->{'TYPE'} = 'video';
260 $metadata->{'SOURCE'} = $self->{'NAME'};
261 $metadata->{'TITLE'} = undef;
262 $metadata->{'DLURL'} = undef;
265 $preflist = $preflist{$quality};
266 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
268 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
270 unless(defined($r = $ua->get($videourl))) {
271 $self->error('Could not download %s', $url);
275 if ($r->base->as_string() =~ m,/verify_age,) {
276 $self->debug('Video requires age verification');
277 my @logindata = $self->__login($videourl, $ua);
279 unless(defined($r)) {
280 $self->error('Could not log into YouTube');
284 $content = $r->content();
286 $p = HTML::TokeParser->new(\$content);
288 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
289 if ('meta' eq $tag->[0]) {
290 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
291 $metadata->{'TITLE'} = $tag->[1]->{'content'};
292 # Convert HTML entities in the title. This is a bit convoluted.
293 $metadata->{'TITLE'} = decode_entities(
294 decode("utf8", $metadata->{'TITLE'}));
296 $self->debug('Title found: %s', $metadata->{'TITLE'});
298 } elsif ('script' eq $tag->[0]) {
302 $self->debug("Found script: %s", $e);
304 if ($e =~ m|ytplayer\.config\s*=\s*(.+);$|) {
306 $self->debug("Found PLAYER_CONFIG: %s", $args);
308 $jsp = videosite::JSArrayParser->new();
309 $self->debug("Using %s to parse", ref($jsp));
310 $r = $jsp->parse($args);
312 unless(defined($r)) {
313 $self->error("Found information hash, but could not parse");
317 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
318 $self->error("Video URL seems to point to a live stream, cannot save this");
322 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
323 my $urls = $r->{'args'}->{'fmt_url_map'};
325 $self->debug("Video has fmt_url_map: %s", $urls);
327 %urls = split(/[\|,]/, $urls);
328 foreach (keys(%urls)) {
329 $urls{$_} = $self->decode_hexurl($urls{$_});
331 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
332 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
333 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
335 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
337 $self->error('fmt_url_map not found in PLAYER_CONFIG');
340 } elsif ($e =~ m|yt\.playerConfig\s*=\s*(.+);\n|) {
342 $self->debug("Found yt.playerConfig: %s", $args);
344 $jsp = videosite::JSArrayParser->new();
345 $self->debug("Using %s to parse", ref($jsp));
346 $r = $jsp->parse($args);
348 unless(defined($r)) {
349 $self->error("Found information hash, but could not parse");
353 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
354 $self->error("Video URL seems to point to a live stream, cannot save this");
358 if (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
359 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
361 $self->debug("Pagetype: 2012 (yt.playerConfig), url_encoded_fmt_stream_map");
363 $self->error('url_map not found in yt.playerConfig');
370 $self->__pick_url(\%urls, $preflist, undef, $metadata);
373 } elsif ('div' eq $tag->[0]) {
374 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
375 # Search forward to the next <div>
376 $tag = $p->get_tag('div');
377 $self->error("Could not get video data for youtube %s: %s",
378 $metadata->{'ID'}, $p->get_trimmed_text());
384 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
385 $self->error('Could not determine download URL');
394 my $videourl = shift;
396 my $user = $self->_getval('USERNAME');
397 my $pass = $self->_getval('PASSWORD');
409 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
414 sub get_all_cookies {
419 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
424 if (($user eq '') or ($pass eq '')) {
425 $self->error('No username or password defined for YouTube');
429 $self->debug('Logging in');
430 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
431 unless($r->is_success()) {
432 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
435 $c = $r->decoded_content();
436 $p = HTML::TokeParser->new(\$c);
437 while (my $tag = $p->get_tag('input')) {
438 $self->debug("%s", Dumper($tag));
439 if ($tag->[1]{name} eq 'GALX') {
440 $token = $tag->[1]{value};
444 $self->debug("GALX = %s", $token);
445 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
446 unless($r->is_success()) {
447 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
450 $c = $r -> decoded_content();
451 $p = HTML::TokeParser->new(\$c);
452 while (my $tag = $p->get_tag('script')) {
453 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
455 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
459 $r = $ua->get($token);
460 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
461 $self->error('Could not log into YouTube');
465 $self->debug("Got a cookie");
467 $r = $ua->get($videourl);
468 if ($r->base->as_string() =~ m,/verify_age,) {
469 $self->debug("Looking for session token...");
470 $c = $r->decoded_content();
471 $p = HTML::TokeParser->new(\$c);
472 while (my $tag = $p->get_tag('script')) {
473 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
479 unless(defined($token)) {
480 $self->error("Could not find session token");
484 $self->debug('Authenticating session...');
485 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
488 # Apparently there is no longer a specific "is_adult" cookie
489 # or, by the looks of it, anything similar
491 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
492 # $self->error('Could not authenticate session');
496 my $cookie = get_all_cookies($ua->cookie_jar);
497 return ($ua->get($videourl), $cookie);
500 # Take an encoded url_encoded_fmt_stream_map and return a hash
501 # matching video IDs to download URLs
502 sub _decode_url_encoded_fmt_stream_map {
505 my $dataencoded = shift;
509 $data = $self->decode_hexurl($data) if $dataencoded;
511 # - Split the decoded string into segments (along ,)
512 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
513 # - URL-decode each key and value _again_
515 # @data will be an array of hash references
517 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
518 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
520 # From each array entry, pick the itag and the url values and return that
521 # as a hash reference
525 if (exists($_->{'sig'})) {
526 $h->{$_->{'itag'}} = sprintf('%s&signature=%s', $_->{'url'}, $_->{'sig'});
528 $h->{$_->{'itag'}} = $_->{'url'};
540 my $preflist = shift;
541 my $audiopreflist = shift;
542 my $metadata = shift;
545 foreach (keys(%{$urls})) {
546 if (exists($videoformats{$_})) {
547 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
549 $self->error('Unknown format %s: %s', $_, $urls->{$_});
553 foreach (@{$preflist}) {
554 if (exists($urls->{$_})) {
555 $self->debug("Selected URL with quality level %s", $_);
556 $metadata->{'DLURL'} = $urls->{$_};
558 if (exists($videoformats{$_})) {
559 $metadata->{'FORMAT'} = $videoformats{$_};
561 $metadata->{'FORMAT'} = 'unknown';
567 if (defined($picked_format)) {
568 if ($metadata->{'FORMAT'} =~ m/Adaptive/) {
569 if (defined($audiopreflist)) {
570 # Pick an audio format as well
571 foreach (@{$audiopreflist}) {
572 if (exists($urls->{$_})) {
573 $self->debug("Selected audio URL with quality level %s", $_);
574 $metadata->{'DLURL_AUDIO'} = $urls->{$_};
575 if (exists($videoformats{$_})) {
576 $metadata->{'FORMAT_AUDIO'} = $videoformats{$_};
578 $metadata->{'FORMAT_AUDIO'} = 'unknown';
584 $self->error('Need an audio preflist, but none provided');
589 $self->debug('URL found: %s', $metadata->{'DLURL'});