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 82 => 'MP4/H264/AAC/360p', # isomavc1mp42
41 84 => 'MP4/H264/AAC/720p', # isomavc1mp42
42 100 => 'WebM/VP8/Vorbis/360p/3D',
43 102 => 'WebM/VP8/Vorbis/720p/3D',
48 my $self = $class->SUPER::new();
50 $self->{'NAME'} = 'youtube';
51 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
52 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
53 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
54 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
55 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
56 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
57 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
58 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
59 $self->{'_PARAMS'} = {
60 'QUALITY' => ['normal', 'Quality of the video to download.', {
61 'normal' => 'standard resolution flash video',
62 'high' => 'higher resolution flash video',
63 'h264' => 'high resolution MPEG4 video',
64 'hd' => 'HD720 resolution'}],
65 'USERNAME' => ['', 'Username to use for YouTube login'],
66 'PASSWORD' => ['', 'Password to use for YouTube login'],
67 'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
70 $self->_prepare_parameters();
86 $self->debug("Matched id %s from pattern %s", $id, $pattern);
88 $res = $self->_parse_by_video_info($url, $id);
89 if (defined($res) && ref($res)) {
92 $res = $self->_parse_by_scrape($url, $id);
98 sub _parse_by_video_info {
102 my $quality = $self->_getval('QUALITY');
105 my $ua = $self->ua();
111 $metadata->{'URL'} = $url;
112 $metadata->{'ID'} = $id;
113 $metadata->{'TYPE'} = 'video';
114 $metadata->{'SOURCE'} = $self->{'NAME'};
115 $metadata->{'TITLE'} = undef;
116 $metadata->{'DLURL'} = undef;
117 $metadata->{'COOKIE'} = undef;
119 $preflist = $preflist{$quality};
120 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
122 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
123 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
124 $self->debug("Video info URL: %s", $videourl);
126 $r = $ua->get($videourl);
127 unless($r->is_success()) {
128 $self->debug('Could not download %s: %s', $videourl, $r->code());
132 $content = $r->content();
133 $self->debug('Content from get_video_info: %s', $content);
136 $content = $self->decode_querystring($content);
138 if ($content->{'status'} ne 'ok') {
139 $self->debug("Non OK status code found: %s", $content->{'status'});
143 if (exists($content->{'fmt_url_map'})) {
145 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
146 $urls = { split /[\|,]/, $urls };
147 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
148 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
150 $self->debug("No URL data found");
154 unless(exists($content->{'title'})) {
155 $self->debug("No title found");
159 $self->__pick_url($urls, $preflist, $metadata);
161 $metadata->{'TITLE'} = $content->{'title'};
162 $metadata->{'TITLE'} =~ s/\+/ /g;
163 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
164 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
166 $self->debug('Title found: %s', $metadata->{'TITLE'});
168 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
169 $self->error('Could not determine download URL');
176 sub _parse_by_scrape {
185 my $ua = $self->ua();
188 my $quality = $self->_getval('QUALITY');
192 $metadata->{'URL'} = $url;
193 $metadata->{'ID'} = $id;
194 $metadata->{'TYPE'} = 'video';
195 $metadata->{'SOURCE'} = $self->{'NAME'};
196 $metadata->{'TITLE'} = undef;
197 $metadata->{'DLURL'} = undef;
198 $metadata->{'COOKIE'} = undef;
201 $preflist = $preflist{$quality};
202 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
204 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
206 unless(defined($r = $ua->get($videourl))) {
207 $self->error('Could not download %s', $url);
211 if ($r->base->as_string() =~ m,/verify_age,) {
212 $self->debug('Video requires age verification');
213 my @logindata = $self->__login($videourl, $ua);
215 $metadata->{'COOKIE'} = $logindata[1];
216 unless(defined($r)) {
217 $self->error('Could not log into YouTube');
221 $content = $r->content();
223 $p = HTML::TokeParser->new(\$content);
225 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
226 if ('meta' eq $tag->[0]) {
227 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
228 $metadata->{'TITLE'} = $tag->[1]->{'content'};
229 # Convert HTML entities in the title. This is a bit convoluted.
230 $metadata->{'TITLE'} = decode_entities(
231 decode("utf8", $metadata->{'TITLE'}));
233 $self->debug('Title found: %s', $metadata->{'TITLE'});
235 } elsif ('script' eq $tag->[0]) {
239 $self->debug("Found script: %s", $e);
241 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
244 $self->debug("Found SWF_ARGS: %s", $args);
245 $jsp = videosite::JSArrayParser->new();
246 $self->debug("Using %s to parse", ref($jsp));
247 $r = $jsp->parse($args);
249 unless(defined($r)) {
250 $self->error("Found information hash, but could not parse");
254 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
255 my $urls = $r->{'fmt_url_map'};
257 $self->debug("Video has fmt_url_map: %s", $urls);
259 $urls = $self->decode_hexurl($urls);
260 %urls = split(/[\|,]/, $urls);
261 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
263 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
264 my $thash = $r->{'t'};
266 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
267 my $fmt = $r->{'fmt_map'};
270 $self->debug('Video has fmt_map');
271 $fmt = $self->decode_hexurl($fmt);
272 @fmt = split(/,/, $fmt);
275 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
280 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
283 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
286 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
289 $self->error('Neither fmt_url_map nor t found in video information hash');
292 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
294 $self->debug("Video has fmt_url_map: %s", $urls);
296 $urls = $self->decode_hexurl($urls);
297 %urls = split(/[\|,]/, $urls);
298 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
299 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
301 $self->debug("Found PLAYER_CONFIG: %s", $args);
303 $jsp = videosite::JSArrayParser->new();
304 $self->debug("Using %s to parse", ref($jsp));
305 $r = $jsp->parse($args);
307 unless(defined($r)) {
308 $self->error("Found information hash, but could not parse");
312 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
313 $self->error("Video URL seems to point to a live stream, cannot save this");
317 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
318 my $urls = $r->{'args'}->{'fmt_url_map'};
320 $self->debug("Video has fmt_url_map: %s", $urls);
322 %urls = split(/[\|,]/, $urls);
323 foreach (keys(%urls)) {
324 $urls{$_} = $self->decode_hexurl($urls{$_});
326 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
327 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
328 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
330 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
332 $self->error('fmt_url_map not found in PLAYER_CONFIG');
338 $self->__pick_url(\%urls, $preflist, $metadata);
341 } elsif ('div' eq $tag->[0]) {
342 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
343 # Search forward to the next <div>
344 $tag = $p->get_tag('div');
345 $self->error("Could not get video data for youtube %s: %s",
346 $metadata->{'ID'}, $p->get_trimmed_text());
352 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
353 $self->error('Could not determine download URL');
362 my $videourl = shift;
364 my $user = $self->_getval('USERNAME');
365 my $pass = $self->_getval('PASSWORD');
377 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
382 sub get_all_cookies {
387 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
392 if (($user eq '') or ($pass eq '')) {
393 $self->error('No username or password defined for YouTube');
397 $self->debug('Logging in');
398 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
399 unless($r->is_success()) {
400 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
403 $c = $r->decoded_content();
404 $p = HTML::TokeParser->new(\$c);
405 while (my $tag = $p->get_tag('input')) {
406 $self->debug("%s", Dumper($tag));
407 if ($tag->[1]{name} eq 'GALX') {
408 $token = $tag->[1]{value};
412 $self->debug("GALX = %s", $token);
413 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
414 unless($r->is_success()) {
415 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
418 $c = $r -> decoded_content();
419 $p = HTML::TokeParser->new(\$c);
420 while (my $tag = $p->get_tag('script')) {
421 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
423 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
427 $r = $ua->get($token);
428 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
429 $self->error('Could not log into YouTube');
433 $self->debug("Got a cookie");
435 $r = $ua->get($videourl);
436 if ($r->base->as_string() =~ m,/verify_age,) {
437 $self->debug("Looking for session token...");
438 $c = $r->decoded_content();
439 $p = HTML::TokeParser->new(\$c);
440 while (my $tag = $p->get_tag('script')) {
441 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
447 unless(defined($token)) {
448 $self->error("Could not find session token");
452 $self->debug('Authenticating session...');
453 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
456 # Apparently there is no longer a specific "is_adult" cookie
457 # or, by the looks of it, anything similar
459 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
460 # $self->error('Could not authenticate session');
464 my $cookie = get_all_cookies($ua->cookie_jar);
465 return ($ua->get($videourl), $cookie);
468 # Take an encoded url_encoded_fmt_stream_map and return a hash
469 # matching video IDs to download URLs
470 sub _decode_url_encoded_fmt_stream_map {
473 my $dataencoded = shift;
476 $data = $self->decode_hexurl($data) if $dataencoded;
478 # - Split the decoded string into segments (along ,)
479 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
480 # - URL-decode each key and value _again_
482 # @data will be an array of hash references
484 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
485 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
487 # From each array entry, pick the itag and the url values and return that
488 # as a hash reference
490 return { map { $_->{'itag'}, $_->{'url'} } @data };
498 my $preflist = shift;
499 my $metadata = shift;
501 foreach (keys(%{$urls})) {
502 if (exists($videoformats{$_})) {
503 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
505 $self->error('Unknown format %s: %s', $_, $urls->{$_});
509 foreach (@{$preflist}) {
510 if (exists($urls->{$_})) {
511 $self->debug("Selected URL with quality level %s", $_);
512 $metadata->{'DLURL'} = $urls->{$_};
517 $self->debug('URL found: %s', $metadata->{'DLURL'});