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]);
29 # Container/Video codec/Audio codec/Resolution
30 5 => 'FLV/Sorenson/MP3/240p',
31 6 => 'FLV/Sorenson/MP3/270p',
32 13 => '3GP/MPEG4-Visual/144p', # 0.5MBit
33 17 => '3GP/MPEG4-Visual/144p', # 2MBit
34 18 => 'MP4/H264/AAC/360p', # isommp42, Baseline
35 22 => 'MP4/H264/AAC/720p', # isommp42, High
36 34 => 'FLV/H264/AAC/360p', # Main
37 35 => 'FLV/H264/AAC/480p', # Main
38 36 => '3GP/MPEG4-Visual/240p',
39 37 => 'MP4/H264/AAC/1080p', # High
40 38 => 'MP4/H264/AAC/3072p', # High
41 43 => 'WebM/VP8/Vorbis/360p',
42 44 => 'WebM/VP8/Vorbis/480p',
43 45 => 'WebM/VP8/Vorbis/720p',
44 46 => 'WebM/VP8/Vorbis/1080p/3D', # effective 540p
45 82 => 'MP4/H264/AAC/360p/3D', # isomavc1mp42
46 83 => 'MP4/H264/AAC/240p/3D', # isomavc1mp42
47 84 => 'MP4/H264/AAC/720p/3D', # isomavc1mp42
48 85 => 'MP4/H264/AAC/1080p/3D', # isomavc1mp42, effective 540p
49 100 => 'WebM/VP8/Vorbis/360p/3D',
50 101 => 'WebM/VP8/Vorbis/480p/3D',
51 102 => 'WebM/VP8/Vorbis/720p/3D',
56 my $self = $class->SUPER::new(
58 _SELFTESTURL => 'http://www.youtube.com/watch?v=dMH0bHeiRNg',
59 _SELFTESTTITLE => 'Evolution of Dance - By Judson Laipply',
60 PATTERNS => ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?.*?v=([-a-zA-Z0-9_]+))',
61 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
62 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
63 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/embed/([-a-zA-Z0-9_]+))',
64 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
65 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
66 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
67 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
68 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'],
70 QUALITY => ['normal', 'Quality of the video to download.', {
71 normal => 'standard resolution flash video',
72 high => 'higher resolution flash video',
73 h264 => 'high resolution MPEG4 video',
74 hd => 'HD720 resolution'}],
75 USERNAME => ['', 'Username to use for YouTube login'],
76 PASSWORD => ['', 'Password to use for YouTube login'],
77 HTTPS => [1, 'Whether to use HTTPS (if available) to connect to YouTube']
81 return bless($self, $class);
95 $self->debug("Matched id %s from pattern %s", $id, $pattern);
97 $res = $self->_parse_by_video_info($url, $id);
98 if (defined($res) && ref($res)) {
101 $res = $self->_parse_by_scrape($url, $id);
107 sub _parse_by_video_info {
111 my $quality = $self->_getval('QUALITY');
114 my $ua = $self->ua();
120 $metadata->{'URL'} = $url;
121 $metadata->{'ID'} = $id;
122 $metadata->{'TYPE'} = 'video';
123 $metadata->{'SOURCE'} = $self->{'NAME'};
124 $metadata->{'TITLE'} = undef;
125 $metadata->{'DLURL'} = undef;
127 $preflist = $preflist{$quality};
128 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
130 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
131 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
132 $self->debug("Video info URL: %s", $videourl);
134 $r = $ua->get($videourl);
135 unless($r->is_success()) {
136 $self->debug('Could not download %s: %s', $videourl, $r->code());
140 $content = $r->content();
141 $self->debug('Content from get_video_info: %s', $content);
144 $content = $self->decode_querystring($content);
146 if ($content->{'status'} ne 'ok') {
147 $self->debug("Non OK status code found: %s", $content->{'status'});
151 if (exists($content->{'fmt_url_map'})) {
153 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
154 $urls = { split /[\|,]/, $urls };
155 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
156 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
158 $self->debug("No URL data found");
162 unless(exists($content->{'title'})) {
163 $self->debug("No title found");
167 $self->__pick_url($urls, $preflist, $metadata);
169 $metadata->{'TITLE'} = $content->{'title'};
170 $metadata->{'TITLE'} =~ s/\+/ /g;
171 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
172 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
174 $self->debug('Title found: %s', $metadata->{'TITLE'});
176 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
177 $self->error('Could not determine download URL');
184 sub _parse_by_scrape {
193 my $ua = $self->ua();
196 my $quality = $self->_getval('QUALITY');
200 $metadata->{'URL'} = $url;
201 $metadata->{'ID'} = $id;
202 $metadata->{'TYPE'} = 'video';
203 $metadata->{'SOURCE'} = $self->{'NAME'};
204 $metadata->{'TITLE'} = undef;
205 $metadata->{'DLURL'} = undef;
208 $preflist = $preflist{$quality};
209 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
211 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
213 unless(defined($r = $ua->get($videourl))) {
214 $self->error('Could not download %s', $url);
218 if ($r->base->as_string() =~ m,/verify_age,) {
219 $self->debug('Video requires age verification');
220 my @logindata = $self->__login($videourl, $ua);
222 unless(defined($r)) {
223 $self->error('Could not log into YouTube');
227 $content = $r->content();
229 $p = HTML::TokeParser->new(\$content);
231 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
232 if ('meta' eq $tag->[0]) {
233 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
234 $metadata->{'TITLE'} = $tag->[1]->{'content'};
235 # Convert HTML entities in the title. This is a bit convoluted.
236 $metadata->{'TITLE'} = decode_entities(
237 decode("utf8", $metadata->{'TITLE'}));
239 $self->debug('Title found: %s', $metadata->{'TITLE'});
241 } elsif ('script' eq $tag->[0]) {
245 $self->debug("Found script: %s", $e);
247 if ($e =~ m|ytplayer\.config\s*=\s*(.+);$|) {
249 $self->debug("Found PLAYER_CONFIG: %s", $args);
251 $jsp = videosite::JSArrayParser->new();
252 $self->debug("Using %s to parse", ref($jsp));
253 $r = $jsp->parse($args);
255 unless(defined($r)) {
256 $self->error("Found information hash, but could not parse");
260 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
261 $self->error("Video URL seems to point to a live stream, cannot save this");
265 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
266 my $urls = $r->{'args'}->{'fmt_url_map'};
268 $self->debug("Video has fmt_url_map: %s", $urls);
270 %urls = split(/[\|,]/, $urls);
271 foreach (keys(%urls)) {
272 $urls{$_} = $self->decode_hexurl($urls{$_});
274 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
275 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
276 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
278 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
280 $self->error('fmt_url_map not found in PLAYER_CONFIG');
283 } elsif ($e =~ m|yt\.playerConfig\s*=\s*(.+);\n|) {
285 $self->debug("Found yt.playerConfig: %s", $args);
287 $jsp = videosite::JSArrayParser->new();
288 $self->debug("Using %s to parse", ref($jsp));
289 $r = $jsp->parse($args);
291 unless(defined($r)) {
292 $self->error("Found information hash, but could not parse");
296 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
297 $self->error("Video URL seems to point to a live stream, cannot save this");
301 if (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
302 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
304 $self->debug("Pagetype: 2012 (yt.playerConfig), url_encoded_fmt_stream_map");
306 $self->error('url_map not found in yt.playerConfig');
313 $self->__pick_url(\%urls, $preflist, $metadata);
316 } elsif ('div' eq $tag->[0]) {
317 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
318 # Search forward to the next <div>
319 $tag = $p->get_tag('div');
320 $self->error("Could not get video data for youtube %s: %s",
321 $metadata->{'ID'}, $p->get_trimmed_text());
327 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
328 $self->error('Could not determine download URL');
337 my $videourl = shift;
339 my $user = $self->_getval('USERNAME');
340 my $pass = $self->_getval('PASSWORD');
352 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
357 sub get_all_cookies {
362 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
367 if (($user eq '') or ($pass eq '')) {
368 $self->error('No username or password defined for YouTube');
372 $self->debug('Logging in');
373 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
374 unless($r->is_success()) {
375 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
378 $c = $r->decoded_content();
379 $p = HTML::TokeParser->new(\$c);
380 while (my $tag = $p->get_tag('input')) {
381 $self->debug("%s", Dumper($tag));
382 if ($tag->[1]{name} eq 'GALX') {
383 $token = $tag->[1]{value};
387 $self->debug("GALX = %s", $token);
388 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
389 unless($r->is_success()) {
390 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
393 $c = $r -> decoded_content();
394 $p = HTML::TokeParser->new(\$c);
395 while (my $tag = $p->get_tag('script')) {
396 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
398 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
402 $r = $ua->get($token);
403 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
404 $self->error('Could not log into YouTube');
408 $self->debug("Got a cookie");
410 $r = $ua->get($videourl);
411 if ($r->base->as_string() =~ m,/verify_age,) {
412 $self->debug("Looking for session token...");
413 $c = $r->decoded_content();
414 $p = HTML::TokeParser->new(\$c);
415 while (my $tag = $p->get_tag('script')) {
416 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
422 unless(defined($token)) {
423 $self->error("Could not find session token");
427 $self->debug('Authenticating session...');
428 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
431 # Apparently there is no longer a specific "is_adult" cookie
432 # or, by the looks of it, anything similar
434 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
435 # $self->error('Could not authenticate session');
439 my $cookie = get_all_cookies($ua->cookie_jar);
440 return ($ua->get($videourl), $cookie);
443 # Take an encoded url_encoded_fmt_stream_map and return a hash
444 # matching video IDs to download URLs
445 sub _decode_url_encoded_fmt_stream_map {
448 my $dataencoded = shift;
452 $data = $self->decode_hexurl($data) if $dataencoded;
454 # - Split the decoded string into segments (along ,)
455 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
456 # - URL-decode each key and value _again_
458 # @data will be an array of hash references
460 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
461 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
463 # From each array entry, pick the itag and the url values and return that
464 # as a hash reference
468 if (exists($_->{'sig'})) {
469 $h->{$_->{'itag'}} = sprintf('%s&signature=%s', $_->{'url'}, $_->{'sig'});
471 $h->{$_->{'itag'}} = $_->{'url'};
483 my $preflist = shift;
484 my $metadata = shift;
486 foreach (keys(%{$urls})) {
487 if (exists($videoformats{$_})) {
488 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
490 $self->error('Unknown format %s: %s', $_, $urls->{$_});
494 foreach (@{$preflist}) {
495 if (exists($urls->{$_})) {
496 $self->debug("Selected URL with quality level %s", $_);
497 $metadata->{'DLURL'} = $urls->{$_};
498 if (exists($videoformats{$_})) {
499 $metadata->{'FORMAT'} = $videoformats{$_};
501 $metadata->{'FORMAT'} = 'unknown';
507 $self->debug('URL found: %s', $metadata->{'DLURL'});