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]);
33 37 => 'mp4,h264,1080p',
34 35 => 'flv,h264,large',
36 22 => 'mp4,h264,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'],
62 'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
65 $self->_prepare_parameters();
81 $self->debug("Matched id %s from pattern %s", $id, $pattern);
83 $res = $self->_parse_by_video_info($url, $id);
84 if (defined($res) && ref($res)) {
87 $res = $self->_parse_by_scrape($url, $id);
93 sub _parse_by_video_info {
97 my $quality = $self->_getval('QUALITY');
100 my $ua = $self->ua();
106 $metadata->{'URL'} = $url;
107 $metadata->{'ID'} = $id;
108 $metadata->{'TYPE'} = 'video';
109 $metadata->{'SOURCE'} = $self->{'NAME'};
110 $metadata->{'TITLE'} = undef;
111 $metadata->{'DLURL'} = undef;
112 $metadata->{'COOKIE'} = undef;
114 $preflist = $preflist{$quality};
115 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
117 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
118 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
119 $self->debug("Video info URL: %s", $videourl);
121 $r = $ua->get($videourl);
122 unless($r->is_success()) {
123 $self->debug('Could not download %s: %s', $videourl, $r->code());
127 $content = $r->content();
128 $self->debug('Content from get_video_info: %s', $content);
131 $content = $self->decode_querystring($content);
133 if ($content->{'status'} ne 'ok') {
134 $self->debug("Non OK status code found: %s", $content->{'status'});
138 if (exists($content->{'fmt_url_map'})) {
140 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
141 $urls = { split /[\|,]/, $urls };
142 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
143 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
145 $self->debug("No URL data found");
149 unless(exists($content->{'title'})) {
150 $self->debug("No title found");
154 $self->__pick_url($urls, $preflist, $metadata);
156 $metadata->{'TITLE'} = $content->{'title'};
157 $metadata->{'TITLE'} =~ s/\+/ /g;
158 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
159 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
161 $self->debug('Title found: %s', $metadata->{'TITLE'});
163 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
164 $self->error('Could not determine download URL');
171 sub _parse_by_scrape {
180 my $ua = $self->ua();
183 my $quality = $self->_getval('QUALITY');
187 $metadata->{'URL'} = $url;
188 $metadata->{'ID'} = $id;
189 $metadata->{'TYPE'} = 'video';
190 $metadata->{'SOURCE'} = $self->{'NAME'};
191 $metadata->{'TITLE'} = undef;
192 $metadata->{'DLURL'} = undef;
193 $metadata->{'COOKIE'} = undef;
196 $preflist = $preflist{$quality};
197 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
199 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
201 unless(defined($r = $ua->get($videourl))) {
202 $self->error('Could not download %s', $url);
206 if ($r->base->as_string() =~ m,/verify_age,) {
207 $self->debug('Video requires age verification');
208 my @logindata = $self->__login($videourl, $ua);
210 $metadata->{'COOKIE'} = $logindata[1];
211 unless(defined($r)) {
212 $self->error('Could not log into YouTube');
216 $content = $r->content();
218 $p = HTML::TokeParser->new(\$content);
220 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
221 if ('meta' eq $tag->[0]) {
222 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
223 $metadata->{'TITLE'} = $tag->[1]->{'content'};
224 # Convert HTML entities in the title. This is a bit convoluted.
225 $metadata->{'TITLE'} = decode_entities(
226 decode("utf8", $metadata->{'TITLE'}));
228 $self->debug('Title found: %s', $metadata->{'TITLE'});
230 } elsif ('script' eq $tag->[0]) {
234 $self->debug("Found script: %s", $e);
236 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
239 $self->debug("Found SWF_ARGS: %s", $args);
240 $jsp = videosite::JSArrayParser->new();
241 $self->debug("Using %s to parse", ref($jsp));
242 $r = $jsp->parse($args);
244 unless(defined($r)) {
245 $self->error("Found information hash, but could not parse");
249 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
250 my $urls = $r->{'fmt_url_map'};
252 $self->debug("Video has fmt_url_map: %s", $urls);
254 $urls = $self->decode_hexurl($urls);
255 %urls = split(/[\|,]/, $urls);
256 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
258 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
259 my $thash = $r->{'t'};
261 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
262 my $fmt = $r->{'fmt_map'};
265 $self->debug('Video has fmt_map');
266 $fmt = $self->decode_hexurl($fmt);
267 @fmt = split(/,/, $fmt);
270 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
275 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
278 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
281 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
284 $self->error('Neither fmt_url_map nor t found in video information hash');
287 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
289 $self->debug("Video has fmt_url_map: %s", $urls);
291 $urls = $self->decode_hexurl($urls);
292 %urls = split(/[\|,]/, $urls);
293 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
294 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
296 $self->debug("Found PLAYER_CONFIG: %s", $args);
298 $jsp = videosite::JSArrayParser->new();
299 $self->debug("Using %s to parse", ref($jsp));
300 $r = $jsp->parse($args);
302 unless(defined($r)) {
303 $self->error("Found information hash, but could not parse");
307 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
308 $self->error("Video URL seems to point to a live stream, cannot save this");
312 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
313 my $urls = $r->{'args'}->{'fmt_url_map'};
315 $self->debug("Video has fmt_url_map: %s", $urls);
317 %urls = split(/[\|,]/, $urls);
318 foreach (keys(%urls)) {
319 $urls{$_} = $self->decode_hexurl($urls{$_});
321 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
322 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
323 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
325 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
327 $self->error('fmt_url_map not found in PLAYER_CONFIG');
333 $self->__pick_url(\%urls, $preflist, $metadata);
336 } elsif ('div' eq $tag->[0]) {
337 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
338 # Search forward to the next <div>
339 $tag = $p->get_tag('div');
340 $self->error("Could not get video data for youtube %s: %s",
341 $metadata->{'ID'}, $p->get_trimmed_text());
347 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
348 $self->error('Could not determine download URL');
357 my $videourl = shift;
359 my $user = $self->_getval('USERNAME');
360 my $pass = $self->_getval('PASSWORD');
372 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
377 sub get_all_cookies {
382 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
387 if (($user eq '') or ($pass eq '')) {
388 $self->error('No username or password defined for YouTube');
392 $self->debug('Logging in');
393 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
394 unless($r->is_success()) {
395 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
398 $c = $r->decoded_content();
399 $p = HTML::TokeParser->new(\$c);
400 while (my $tag = $p->get_tag('input')) {
401 $self->debug("%s", Dumper($tag));
402 if ($tag->[1]{name} eq 'GALX') {
403 $token = $tag->[1]{value};
407 $self->debug("GALX = %s", $token);
408 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
409 unless($r->is_success()) {
410 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
413 $c = $r -> decoded_content();
414 $p = HTML::TokeParser->new(\$c);
415 while (my $tag = $p->get_tag('script')) {
416 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
418 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
422 $r = $ua->get($token);
423 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
424 $self->error('Could not log into YouTube');
428 $self->debug("Got a cookie");
430 $r = $ua->get($videourl);
431 if ($r->base->as_string() =~ m,/verify_age,) {
432 $self->debug("Looking for session token...");
433 $c = $r->decoded_content();
434 $p = HTML::TokeParser->new(\$c);
435 while (my $tag = $p->get_tag('script')) {
436 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
442 unless(defined($token)) {
443 $self->error("Could not find session token");
447 $self->debug('Authenticating session...');
448 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
451 # Apparently there is no longer a specific "is_adult" cookie
452 # or, by the looks of it, anything similar
454 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
455 # $self->error('Could not authenticate session');
459 my $cookie = get_all_cookies($ua->cookie_jar);
460 return ($ua->get($videourl), $cookie);
463 # Take an encoded url_encoded_fmt_stream_map and return a hash
464 # matching video IDs to download URLs
465 sub _decode_url_encoded_fmt_stream_map {
468 my $dataencoded = shift;
471 $data = $self->decode_hexurl($data) if $dataencoded;
473 # - Split the decoded string into segments (along ,)
474 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
475 # - URL-decode each key and value _again_
477 # @data will be an array of hash references
479 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
480 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
482 # From each array entry, pick the itag and the url values and return that
483 # as a hash reference
485 return { map { $_->{'itag'}, $_->{'url'} } @data };
493 my $preflist = shift;
494 my $metadata = shift;
496 foreach (keys(%{$urls})) {
497 if (exists($videoformats{$_})) {
498 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
500 $self->error('Unknown format %s: %s', $_, $urls->{$_});
504 foreach (@{$preflist}) {
505 if (exists($urls->{$_})) {
506 $self->debug("Selected URL with quality level %s", $_);
507 $metadata->{'DLURL'} = $urls->{$_};
512 $self->debug('URL found: %s', $metadata->{'DLURL'});