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 5 => 'FLV/Sorenson/MP3/240p',
30 18 => 'MP4/H264/AAC/360p',
31 22 => 'MP4/H264/AAC/720p',
32 34 => 'FLV/H264/AAC/360p',
33 35 => 'FLV/H264/AAC/480p',
34 37 => 'MP4/H264/AAC/1080p',
35 38 => 'MP4/H264/AAC/3072p',
36 43 => 'WebM/VP8/Vorbis/360p',
37 44 => 'WebM/VP8/Vorbis/480p',
38 45 => 'WebM/VP8/Vorbis/720p',
43 my $self = $class->SUPER::new();
45 $self->{'NAME'} = 'youtube';
46 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
47 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
48 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
49 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
50 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
51 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
52 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
53 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
54 $self->{'_PARAMS'} = {
55 'QUALITY' => ['normal', 'Quality of the video to download.', {
56 'normal' => 'standard resolution flash video',
57 'high' => 'higher resolution flash video',
58 'h264' => 'high resolution MPEG4 video',
59 'hd' => 'HD720 resolution'}],
60 'USERNAME' => ['', 'Username to use for YouTube login'],
61 'PASSWORD' => ['', 'Password to use for YouTube login']};
64 $self->_prepare_parameters();
80 $self->debug("Matched id %s from pattern %s", $id, $pattern);
82 $res = $self->_parse_by_video_info($url, $id);
83 if (defined($res) && ref($res)) {
86 $res = $self->_parse_by_scrape($url, $id);
92 sub _parse_by_video_info {
96 my $quality = $self->_getval('QUALITY');
105 $metadata->{'URL'} = $url;
106 $metadata->{'ID'} = $id;
107 $metadata->{'TYPE'} = 'video';
108 $metadata->{'SOURCE'} = $self->{'NAME'};
109 $metadata->{'TITLE'} = undef;
110 $metadata->{'DLURL'} = undef;
111 $metadata->{'COOKIE'} = undef;
113 $preflist = $preflist{$quality};
114 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
116 $videourl = sprintf('https://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
117 $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
118 $self->debug("Video info URL: %s", $videourl);
120 $r = $ua->get($videourl);
121 unless($r->is_success()) {
122 $self->debug('Could not download %s: %s', $videourl, $r->code());
126 $content = $r->content();
127 $self->debug('Content from get_video_info: %s', $content);
130 $content = { split /[&=]/, $content };
132 if ($content->{'status'} ne 'ok') {
133 $self->debug("Non OK status code found: %s", $content->{'status'});
137 if (exists($content->{'fmt_url_map'})) {
139 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
140 $urls = { split /[\|,]/, $urls };
141 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
142 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
144 $self->debug("No URL data found");
148 unless(exists($content->{'title'})) {
149 $self->debug("No title found");
153 $self->__pick_url($urls, $preflist, $metadata);
155 $metadata->{'TITLE'} = $content->{'title'};
156 $metadata->{'TITLE'} =~ s/\+/ /g;
157 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
158 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
160 $self->debug('Title found: %s', $metadata->{'TITLE'});
162 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
163 $self->error('Could not determine download URL');
170 sub _parse_by_scrape {
179 my $ua = $self->ua();
182 my $quality = $self->_getval('QUALITY');
186 $metadata->{'URL'} = $url;
187 $metadata->{'ID'} = $id;
188 $metadata->{'TYPE'} = 'video';
189 $metadata->{'SOURCE'} = $self->{'NAME'};
190 $metadata->{'TITLE'} = undef;
191 $metadata->{'DLURL'} = undef;
192 $metadata->{'COOKIE'} = undef;
195 $preflist = $preflist{$quality};
196 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
198 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $id);
200 unless(defined($r = $ua->get($videourl))) {
201 $self->error('Could not download %s', $url);
205 if ($r->base->as_string() =~ m,/verify_age,) {
206 $self->debug('Video requires age verification');
207 my @logindata = $self->__login($videourl, $ua);
209 $metadata->{'COOKIE'} = $logindata[1];
210 unless(defined($r)) {
211 $self->error('Could not log into YouTube');
215 $content = $r->content();
217 $p = HTML::TokeParser->new(\$content);
219 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
220 if ('meta' eq $tag->[0]) {
221 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
222 $metadata->{'TITLE'} = $tag->[1]->{'content'};
223 # Convert HTML entities in the title. This is a bit convoluted.
224 $metadata->{'TITLE'} = decode_entities(
225 decode("utf8", $metadata->{'TITLE'}));
227 $self->debug('Title found: %s', $metadata->{'TITLE'});
229 } elsif ('script' eq $tag->[0]) {
233 $self->debug("Found script: %s", $e);
235 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
238 $self->debug("Found SWF_ARGS: %s", $args);
239 $jsp = videosite::JSArrayParser->new();
240 $self->debug("Using %s to parse", ref($jsp));
241 $r = $jsp->parse($args);
243 unless(defined($r)) {
244 $self->error("Found information hash, but could not parse");
248 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
249 my $urls = $r->{'fmt_url_map'};
251 $self->debug("Video has fmt_url_map: %s", $urls);
253 $urls = $self->decode_hexurl($urls);
254 %urls = split(/[\|,]/, $urls);
255 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
257 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
258 my $thash = $r->{'t'};
260 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
261 my $fmt = $r->{'fmt_map'};
264 $self->debug('Video has fmt_map');
265 $fmt = $self->decode_hexurl($fmt);
266 @fmt = split(/,/, $fmt);
269 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
274 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
277 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
280 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
283 $self->error('Neither fmt_url_map nor t found in video information hash');
286 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
288 $self->debug("Video has fmt_url_map: %s", $urls);
290 $urls = $self->decode_hexurl($urls);
291 %urls = split(/[\|,]/, $urls);
292 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
293 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
295 $self->debug("Found PLAYER_CONFIG: %s", $args);
297 $jsp = videosite::JSArrayParser->new();
298 $self->debug("Using %s to parse", ref($jsp));
299 $r = $jsp->parse($args);
301 unless(defined($r)) {
302 $self->error("Found information hash, but could not parse");
306 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
307 $self->error("Video URL seems to point to a live stream, cannot save this");
311 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
312 my $urls = $r->{'args'}->{'fmt_url_map'};
314 $self->debug("Video has fmt_url_map: %s", $urls);
316 %urls = split(/[\|,]/, $urls);
317 foreach (keys(%urls)) {
318 $urls{$_} = $self->decode_hexurl($urls{$_});
320 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
321 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
322 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
324 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
326 $self->error('fmt_url_map not found in PLAYER_CONFIG');
332 $self->__pick_url(\%urls, $preflist, $metadata);
335 } elsif ('div' eq $tag->[0]) {
336 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
337 # Search forward to the next <div>
338 $tag = $p->get_tag('div');
339 $self->error("Could not get video data for youtube %s: %s",
340 $metadata->{'ID'}, $p->get_trimmed_text());
346 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
347 $self->error('Could not determine download URL');
356 my $videourl = shift;
358 my $user = $self->_getval('USERNAME');
359 my $pass = $self->_getval('PASSWORD');
371 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
376 sub get_all_cookies {
381 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
386 if (($user eq '') or ($pass eq '')) {
387 $self->error('No username or password defined for YouTube');
391 $self->debug('Logging in');
392 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
393 unless($r->is_success()) {
394 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
397 $c = $r->decoded_content();
398 $p = HTML::TokeParser->new(\$c);
399 while (my $tag = $p->get_tag('input')) {
400 $self->debug("%s", Dumper($tag));
401 if ($tag->[1]{name} eq 'GALX') {
402 $token = $tag->[1]{value};
406 $self->debug("GALX = %s", $token);
407 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
408 unless($r->is_success()) {
409 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
412 $c = $r -> decoded_content();
413 $p = HTML::TokeParser->new(\$c);
414 while (my $tag = $p->get_tag('script')) {
415 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
417 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
421 $r = $ua->get($token);
422 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
423 $self->error('Could not log into YouTube');
427 $self->debug("Got a cookie");
429 $r = $ua->get($videourl);
430 if ($r->base->as_string() =~ m,/verify_age,) {
431 $self->debug("Looking for session token...");
432 $c = $r->decoded_content();
433 $p = HTML::TokeParser->new(\$c);
434 while (my $tag = $p->get_tag('script')) {
435 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
441 unless(defined($token)) {
442 $self->error("Could not find session token");
446 $self->debug('Authenticating session...');
447 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
450 # Apparently there is no longer a specific "is_adult" cookie
451 # or, by the looks of it, anything similar
453 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
454 # $self->error('Could not authenticate session');
458 my $cookie = get_all_cookies($ua->cookie_jar);
459 return ($ua->get($videourl), $cookie);
462 # Take an encoded url_encoded_fmt_stream_map and return a hash
463 # matching video IDs to download URLs
464 sub _decode_url_encoded_fmt_stream_map {
467 my $dataencoded = shift;
470 $data = $self->decode_hexurl($data) if $dataencoded;
472 # - Split the decoded string into segments (along ,)
473 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
474 # - URL-decode each key and value _again_
476 # @data will be an array of hash references
478 @data = map { { map { $self->decode_hexurl($_) } split /[=&]/ } } split /,/, $data;
479 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
481 # From each array entry, pick the itag and the url values and return that
482 # as a hash reference
484 return { map { $_->{'itag'}, $_->{'url'} } @data };
492 my $preflist = shift;
493 my $metadata = shift;
495 foreach (keys(%{$urls})) {
496 if (exists($videoformats{$_})) {
497 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
499 $self->error('Unknown format %s: %s', $_, $urls->{$_});
503 foreach (@{$preflist}) {
504 if (exists($urls->{$_})) {
505 $self->debug("Selected URL with quality level %s", $_);
506 $metadata->{'DLURL'} = $urls->{$_};
511 $self->debug('URL found: %s', $metadata->{'DLURL'});