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 18 => 'MP4/H264/AAC/360p', # isommp42
32 22 => 'MP4/H264/AAC/720p', # isommp42
33 34 => 'FLV/H264/AAC/360p',
34 35 => 'FLV/H264/AAC/480p',
35 37 => 'MP4/H264/AAC/1080p',
36 38 => 'MP4/H264/AAC/3072p',
37 43 => 'WebM/VP8/Vorbis/360p',
38 44 => 'WebM/VP8/Vorbis/480p',
39 45 => 'WebM/VP8/Vorbis/720p',
40 46 => 'WebM/VP8/Vorbis/1080p',
41 82 => 'MP4/H264/AAC/360p', # isomavc1mp42
42 84 => 'MP4/H264/AAC/720p', # isomavc1mp42
43 100 => 'WebM/VP8/Vorbis/360p/3D',
44 102 => 'WebM/VP8/Vorbis/720p/3D',
49 my $self = $class->SUPER::new();
51 $self->{'NAME'} = 'youtube';
52 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
53 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
54 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
55 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
56 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
57 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
58 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
59 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
60 $self->{'_PARAMS'} = {
61 'QUALITY' => ['normal', 'Quality of the video to download.', {
62 'normal' => 'standard resolution flash video',
63 'high' => 'higher resolution flash video',
64 'h264' => 'high resolution MPEG4 video',
65 'hd' => 'HD720 resolution'}],
66 'USERNAME' => ['', 'Username to use for YouTube login'],
67 'PASSWORD' => ['', 'Password to use for YouTube login'],
68 'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
71 $self->_prepare_parameters();
87 $self->debug("Matched id %s from pattern %s", $id, $pattern);
89 $res = $self->_parse_by_video_info($url, $id);
90 if (defined($res) && ref($res)) {
93 $res = $self->_parse_by_scrape($url, $id);
99 sub _parse_by_video_info {
103 my $quality = $self->_getval('QUALITY');
106 my $ua = $self->ua();
112 $metadata->{'URL'} = $url;
113 $metadata->{'ID'} = $id;
114 $metadata->{'TYPE'} = 'video';
115 $metadata->{'SOURCE'} = $self->{'NAME'};
116 $metadata->{'TITLE'} = undef;
117 $metadata->{'DLURL'} = undef;
118 $metadata->{'COOKIE'} = undef;
120 $preflist = $preflist{$quality};
121 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
123 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
124 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
125 $self->debug("Video info URL: %s", $videourl);
127 $r = $ua->get($videourl);
128 unless($r->is_success()) {
129 $self->debug('Could not download %s: %s', $videourl, $r->code());
133 $content = $r->content();
134 $self->debug('Content from get_video_info: %s', $content);
137 $content = $self->decode_querystring($content);
139 if ($content->{'status'} ne 'ok') {
140 $self->debug("Non OK status code found: %s", $content->{'status'});
144 if (exists($content->{'fmt_url_map'})) {
146 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
147 $urls = { split /[\|,]/, $urls };
148 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
149 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
151 $self->debug("No URL data found");
155 unless(exists($content->{'title'})) {
156 $self->debug("No title found");
160 $self->__pick_url($urls, $preflist, $metadata);
162 $metadata->{'TITLE'} = $content->{'title'};
163 $metadata->{'TITLE'} =~ s/\+/ /g;
164 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
165 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
167 $self->debug('Title found: %s', $metadata->{'TITLE'});
169 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
170 $self->error('Could not determine download URL');
177 sub _parse_by_scrape {
186 my $ua = $self->ua();
189 my $quality = $self->_getval('QUALITY');
193 $metadata->{'URL'} = $url;
194 $metadata->{'ID'} = $id;
195 $metadata->{'TYPE'} = 'video';
196 $metadata->{'SOURCE'} = $self->{'NAME'};
197 $metadata->{'TITLE'} = undef;
198 $metadata->{'DLURL'} = undef;
199 $metadata->{'COOKIE'} = undef;
202 $preflist = $preflist{$quality};
203 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
205 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
207 unless(defined($r = $ua->get($videourl))) {
208 $self->error('Could not download %s', $url);
212 if ($r->base->as_string() =~ m,/verify_age,) {
213 $self->debug('Video requires age verification');
214 my @logindata = $self->__login($videourl, $ua);
216 $metadata->{'COOKIE'} = $logindata[1];
217 unless(defined($r)) {
218 $self->error('Could not log into YouTube');
222 $content = $r->content();
224 $p = HTML::TokeParser->new(\$content);
226 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
227 if ('meta' eq $tag->[0]) {
228 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
229 $metadata->{'TITLE'} = $tag->[1]->{'content'};
230 # Convert HTML entities in the title. This is a bit convoluted.
231 $metadata->{'TITLE'} = decode_entities(
232 decode("utf8", $metadata->{'TITLE'}));
234 $self->debug('Title found: %s', $metadata->{'TITLE'});
236 } elsif ('script' eq $tag->[0]) {
240 $self->debug("Found script: %s", $e);
242 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
245 $self->debug("Found SWF_ARGS: %s", $args);
246 $jsp = videosite::JSArrayParser->new();
247 $self->debug("Using %s to parse", ref($jsp));
248 $r = $jsp->parse($args);
250 unless(defined($r)) {
251 $self->error("Found information hash, but could not parse");
255 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
256 my $urls = $r->{'fmt_url_map'};
258 $self->debug("Video has fmt_url_map: %s", $urls);
260 $urls = $self->decode_hexurl($urls);
261 %urls = split(/[\|,]/, $urls);
262 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
264 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
265 my $thash = $r->{'t'};
267 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
268 my $fmt = $r->{'fmt_map'};
271 $self->debug('Video has fmt_map');
272 $fmt = $self->decode_hexurl($fmt);
273 @fmt = split(/,/, $fmt);
276 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
281 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
284 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
287 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
290 $self->error('Neither fmt_url_map nor t found in video information hash');
293 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
295 $self->debug("Video has fmt_url_map: %s", $urls);
297 $urls = $self->decode_hexurl($urls);
298 %urls = split(/[\|,]/, $urls);
299 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
300 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
302 $self->debug("Found PLAYER_CONFIG: %s", $args);
304 $jsp = videosite::JSArrayParser->new();
305 $self->debug("Using %s to parse", ref($jsp));
306 $r = $jsp->parse($args);
308 unless(defined($r)) {
309 $self->error("Found information hash, but could not parse");
313 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
314 $self->error("Video URL seems to point to a live stream, cannot save this");
318 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
319 my $urls = $r->{'args'}->{'fmt_url_map'};
321 $self->debug("Video has fmt_url_map: %s", $urls);
323 %urls = split(/[\|,]/, $urls);
324 foreach (keys(%urls)) {
325 $urls{$_} = $self->decode_hexurl($urls{$_});
327 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
328 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
329 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
331 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
333 $self->error('fmt_url_map not found in PLAYER_CONFIG');
339 $self->__pick_url(\%urls, $preflist, $metadata);
342 } elsif ('div' eq $tag->[0]) {
343 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
344 # Search forward to the next <div>
345 $tag = $p->get_tag('div');
346 $self->error("Could not get video data for youtube %s: %s",
347 $metadata->{'ID'}, $p->get_trimmed_text());
353 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
354 $self->error('Could not determine download URL');
363 my $videourl = shift;
365 my $user = $self->_getval('USERNAME');
366 my $pass = $self->_getval('PASSWORD');
378 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
383 sub get_all_cookies {
388 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
393 if (($user eq '') or ($pass eq '')) {
394 $self->error('No username or password defined for YouTube');
398 $self->debug('Logging in');
399 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
400 unless($r->is_success()) {
401 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
404 $c = $r->decoded_content();
405 $p = HTML::TokeParser->new(\$c);
406 while (my $tag = $p->get_tag('input')) {
407 $self->debug("%s", Dumper($tag));
408 if ($tag->[1]{name} eq 'GALX') {
409 $token = $tag->[1]{value};
413 $self->debug("GALX = %s", $token);
414 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
415 unless($r->is_success()) {
416 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
419 $c = $r -> decoded_content();
420 $p = HTML::TokeParser->new(\$c);
421 while (my $tag = $p->get_tag('script')) {
422 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
424 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
428 $r = $ua->get($token);
429 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
430 $self->error('Could not log into YouTube');
434 $self->debug("Got a cookie");
436 $r = $ua->get($videourl);
437 if ($r->base->as_string() =~ m,/verify_age,) {
438 $self->debug("Looking for session token...");
439 $c = $r->decoded_content();
440 $p = HTML::TokeParser->new(\$c);
441 while (my $tag = $p->get_tag('script')) {
442 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
448 unless(defined($token)) {
449 $self->error("Could not find session token");
453 $self->debug('Authenticating session...');
454 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
457 # Apparently there is no longer a specific "is_adult" cookie
458 # or, by the looks of it, anything similar
460 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
461 # $self->error('Could not authenticate session');
465 my $cookie = get_all_cookies($ua->cookie_jar);
466 return ($ua->get($videourl), $cookie);
469 # Take an encoded url_encoded_fmt_stream_map and return a hash
470 # matching video IDs to download URLs
471 sub _decode_url_encoded_fmt_stream_map {
474 my $dataencoded = shift;
477 $data = $self->decode_hexurl($data) if $dataencoded;
479 # - Split the decoded string into segments (along ,)
480 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
481 # - URL-decode each key and value _again_
483 # @data will be an array of hash references
485 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
486 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
488 # From each array entry, pick the itag and the url values and return that
489 # as a hash reference
491 return { map { $_->{'itag'}, $_->{'url'} } @data };
499 my $preflist = shift;
500 my $metadata = shift;
502 foreach (keys(%{$urls})) {
503 if (exists($videoformats{$_})) {
504 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
506 $self->error('Unknown format %s: %s', $_, $urls->{$_});
510 foreach (@{$preflist}) {
511 if (exists($urls->{$_})) {
512 $self->debug("Selected URL with quality level %s", $_);
513 $metadata->{'DLURL'} = $urls->{$_};
518 $self->debug('URL found: %s', $metadata->{'DLURL'});