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
46 my $self = $class->SUPER::new();
48 $self->{'NAME'} = 'youtube';
49 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
50 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
51 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
52 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
53 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
54 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
55 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
56 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
57 $self->{'_PARAMS'} = {
58 'QUALITY' => ['normal', 'Quality of the video to download.', {
59 'normal' => 'standard resolution flash video',
60 'high' => 'higher resolution flash video',
61 'h264' => 'high resolution MPEG4 video',
62 'hd' => 'HD720 resolution'}],
63 'USERNAME' => ['', 'Username to use for YouTube login'],
64 'PASSWORD' => ['', 'Password to use for YouTube login'],
65 'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
68 $self->_prepare_parameters();
84 $self->debug("Matched id %s from pattern %s", $id, $pattern);
86 $res = $self->_parse_by_video_info($url, $id);
87 if (defined($res) && ref($res)) {
90 $res = $self->_parse_by_scrape($url, $id);
96 sub _parse_by_video_info {
100 my $quality = $self->_getval('QUALITY');
103 my $ua = $self->ua();
109 $metadata->{'URL'} = $url;
110 $metadata->{'ID'} = $id;
111 $metadata->{'TYPE'} = 'video';
112 $metadata->{'SOURCE'} = $self->{'NAME'};
113 $metadata->{'TITLE'} = undef;
114 $metadata->{'DLURL'} = undef;
115 $metadata->{'COOKIE'} = undef;
117 $preflist = $preflist{$quality};
118 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
120 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
121 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
122 $self->debug("Video info URL: %s", $videourl);
124 $r = $ua->get($videourl);
125 unless($r->is_success()) {
126 $self->debug('Could not download %s: %s', $videourl, $r->code());
130 $content = $r->content();
131 $self->debug('Content from get_video_info: %s', $content);
134 $content = $self->decode_querystring($content);
136 if ($content->{'status'} ne 'ok') {
137 $self->debug("Non OK status code found: %s", $content->{'status'});
141 if (exists($content->{'fmt_url_map'})) {
143 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
144 $urls = { split /[\|,]/, $urls };
145 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
146 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
148 $self->debug("No URL data found");
152 unless(exists($content->{'title'})) {
153 $self->debug("No title found");
157 $self->__pick_url($urls, $preflist, $metadata);
159 $metadata->{'TITLE'} = $content->{'title'};
160 $metadata->{'TITLE'} =~ s/\+/ /g;
161 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
162 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
164 $self->debug('Title found: %s', $metadata->{'TITLE'});
166 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
167 $self->error('Could not determine download URL');
174 sub _parse_by_scrape {
183 my $ua = $self->ua();
186 my $quality = $self->_getval('QUALITY');
190 $metadata->{'URL'} = $url;
191 $metadata->{'ID'} = $id;
192 $metadata->{'TYPE'} = 'video';
193 $metadata->{'SOURCE'} = $self->{'NAME'};
194 $metadata->{'TITLE'} = undef;
195 $metadata->{'DLURL'} = undef;
196 $metadata->{'COOKIE'} = undef;
199 $preflist = $preflist{$quality};
200 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
202 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
204 unless(defined($r = $ua->get($videourl))) {
205 $self->error('Could not download %s', $url);
209 if ($r->base->as_string() =~ m,/verify_age,) {
210 $self->debug('Video requires age verification');
211 my @logindata = $self->__login($videourl, $ua);
213 $metadata->{'COOKIE'} = $logindata[1];
214 unless(defined($r)) {
215 $self->error('Could not log into YouTube');
219 $content = $r->content();
221 $p = HTML::TokeParser->new(\$content);
223 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
224 if ('meta' eq $tag->[0]) {
225 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
226 $metadata->{'TITLE'} = $tag->[1]->{'content'};
227 # Convert HTML entities in the title. This is a bit convoluted.
228 $metadata->{'TITLE'} = decode_entities(
229 decode("utf8", $metadata->{'TITLE'}));
231 $self->debug('Title found: %s', $metadata->{'TITLE'});
233 } elsif ('script' eq $tag->[0]) {
237 $self->debug("Found script: %s", $e);
239 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
242 $self->debug("Found SWF_ARGS: %s", $args);
243 $jsp = videosite::JSArrayParser->new();
244 $self->debug("Using %s to parse", ref($jsp));
245 $r = $jsp->parse($args);
247 unless(defined($r)) {
248 $self->error("Found information hash, but could not parse");
252 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
253 my $urls = $r->{'fmt_url_map'};
255 $self->debug("Video has fmt_url_map: %s", $urls);
257 $urls = $self->decode_hexurl($urls);
258 %urls = split(/[\|,]/, $urls);
259 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
261 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
262 my $thash = $r->{'t'};
264 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
265 my $fmt = $r->{'fmt_map'};
268 $self->debug('Video has fmt_map');
269 $fmt = $self->decode_hexurl($fmt);
270 @fmt = split(/,/, $fmt);
273 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
278 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
281 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
284 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
287 $self->error('Neither fmt_url_map nor t found in video information hash');
290 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
292 $self->debug("Video has fmt_url_map: %s", $urls);
294 $urls = $self->decode_hexurl($urls);
295 %urls = split(/[\|,]/, $urls);
296 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
297 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
299 $self->debug("Found PLAYER_CONFIG: %s", $args);
301 $jsp = videosite::JSArrayParser->new();
302 $self->debug("Using %s to parse", ref($jsp));
303 $r = $jsp->parse($args);
305 unless(defined($r)) {
306 $self->error("Found information hash, but could not parse");
310 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
311 $self->error("Video URL seems to point to a live stream, cannot save this");
315 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
316 my $urls = $r->{'args'}->{'fmt_url_map'};
318 $self->debug("Video has fmt_url_map: %s", $urls);
320 %urls = split(/[\|,]/, $urls);
321 foreach (keys(%urls)) {
322 $urls{$_} = $self->decode_hexurl($urls{$_});
324 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
325 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
326 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
328 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
330 $self->error('fmt_url_map not found in PLAYER_CONFIG');
336 $self->__pick_url(\%urls, $preflist, $metadata);
339 } elsif ('div' eq $tag->[0]) {
340 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
341 # Search forward to the next <div>
342 $tag = $p->get_tag('div');
343 $self->error("Could not get video data for youtube %s: %s",
344 $metadata->{'ID'}, $p->get_trimmed_text());
350 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
351 $self->error('Could not determine download URL');
360 my $videourl = shift;
362 my $user = $self->_getval('USERNAME');
363 my $pass = $self->_getval('PASSWORD');
375 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
380 sub get_all_cookies {
385 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
390 if (($user eq '') or ($pass eq '')) {
391 $self->error('No username or password defined for YouTube');
395 $self->debug('Logging in');
396 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
397 unless($r->is_success()) {
398 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
401 $c = $r->decoded_content();
402 $p = HTML::TokeParser->new(\$c);
403 while (my $tag = $p->get_tag('input')) {
404 $self->debug("%s", Dumper($tag));
405 if ($tag->[1]{name} eq 'GALX') {
406 $token = $tag->[1]{value};
410 $self->debug("GALX = %s", $token);
411 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
412 unless($r->is_success()) {
413 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
416 $c = $r -> decoded_content();
417 $p = HTML::TokeParser->new(\$c);
418 while (my $tag = $p->get_tag('script')) {
419 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
421 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
425 $r = $ua->get($token);
426 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
427 $self->error('Could not log into YouTube');
431 $self->debug("Got a cookie");
433 $r = $ua->get($videourl);
434 if ($r->base->as_string() =~ m,/verify_age,) {
435 $self->debug("Looking for session token...");
436 $c = $r->decoded_content();
437 $p = HTML::TokeParser->new(\$c);
438 while (my $tag = $p->get_tag('script')) {
439 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
445 unless(defined($token)) {
446 $self->error("Could not find session token");
450 $self->debug('Authenticating session...');
451 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
454 # Apparently there is no longer a specific "is_adult" cookie
455 # or, by the looks of it, anything similar
457 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
458 # $self->error('Could not authenticate session');
462 my $cookie = get_all_cookies($ua->cookie_jar);
463 return ($ua->get($videourl), $cookie);
466 # Take an encoded url_encoded_fmt_stream_map and return a hash
467 # matching video IDs to download URLs
468 sub _decode_url_encoded_fmt_stream_map {
471 my $dataencoded = shift;
474 $data = $self->decode_hexurl($data) if $dataencoded;
476 # - Split the decoded string into segments (along ,)
477 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
478 # - URL-decode each key and value _again_
480 # @data will be an array of hash references
482 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
483 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
485 # From each array entry, pick the itag and the url values and return that
486 # as a hash reference
488 return { map { $_->{'itag'}, $_->{'url'} } @data };
496 my $preflist = shift;
497 my $metadata = shift;
499 foreach (keys(%{$urls})) {
500 if (exists($videoformats{$_})) {
501 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
503 $self->error('Unknown format %s: %s', $_, $urls->{$_});
507 foreach (@{$preflist}) {
508 if (exists($urls->{$_})) {
509 $self->debug("Selected URL with quality level %s", $_);
510 $metadata->{'DLURL'} = $urls->{$_};
515 $self->debug('URL found: %s', $metadata->{'DLURL'});