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',
32 22 => 'MP4/H264/AAC/720p',
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',
44 my $self = $class->SUPER::new();
46 $self->{'NAME'} = 'youtube';
47 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
48 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
49 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
50 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
51 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
52 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
53 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
54 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
55 $self->{'_PARAMS'} = {
56 'QUALITY' => ['normal', 'Quality of the video to download.', {
57 'normal' => 'standard resolution flash video',
58 'high' => 'higher resolution flash video',
59 'h264' => 'high resolution MPEG4 video',
60 'hd' => 'HD720 resolution'}],
61 'USERNAME' => ['', 'Username to use for YouTube login'],
62 'PASSWORD' => ['', 'Password to use for YouTube login'],
63 'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
66 $self->_prepare_parameters();
82 $self->debug("Matched id %s from pattern %s", $id, $pattern);
84 $res = $self->_parse_by_video_info($url, $id);
85 if (defined($res) && ref($res)) {
88 $res = $self->_parse_by_scrape($url, $id);
94 sub _parse_by_video_info {
98 my $quality = $self->_getval('QUALITY');
101 my $ua = $self->ua();
107 $metadata->{'URL'} = $url;
108 $metadata->{'ID'} = $id;
109 $metadata->{'TYPE'} = 'video';
110 $metadata->{'SOURCE'} = $self->{'NAME'};
111 $metadata->{'TITLE'} = undef;
112 $metadata->{'DLURL'} = undef;
113 $metadata->{'COOKIE'} = undef;
115 $preflist = $preflist{$quality};
116 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
118 $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
119 $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
120 $self->debug("Video info URL: %s", $videourl);
122 $r = $ua->get($videourl);
123 unless($r->is_success()) {
124 $self->debug('Could not download %s: %s', $videourl, $r->code());
128 $content = $r->content();
129 $self->debug('Content from get_video_info: %s', $content);
132 $content = $self->decode_querystring($content);
134 if ($content->{'status'} ne 'ok') {
135 $self->debug("Non OK status code found: %s", $content->{'status'});
139 if (exists($content->{'fmt_url_map'})) {
141 $urls = $self->decode_hexurl($content->{'fmt_url_map'});
142 $urls = { split /[\|,]/, $urls };
143 } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
144 $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
146 $self->debug("No URL data found");
150 unless(exists($content->{'title'})) {
151 $self->debug("No title found");
155 $self->__pick_url($urls, $preflist, $metadata);
157 $metadata->{'TITLE'} = $content->{'title'};
158 $metadata->{'TITLE'} =~ s/\+/ /g;
159 $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
160 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
162 $self->debug('Title found: %s', $metadata->{'TITLE'});
164 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
165 $self->error('Could not determine download URL');
172 sub _parse_by_scrape {
181 my $ua = $self->ua();
184 my $quality = $self->_getval('QUALITY');
188 $metadata->{'URL'} = $url;
189 $metadata->{'ID'} = $id;
190 $metadata->{'TYPE'} = 'video';
191 $metadata->{'SOURCE'} = $self->{'NAME'};
192 $metadata->{'TITLE'} = undef;
193 $metadata->{'DLURL'} = undef;
194 $metadata->{'COOKIE'} = undef;
197 $preflist = $preflist{$quality};
198 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
200 $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
202 unless(defined($r = $ua->get($videourl))) {
203 $self->error('Could not download %s', $url);
207 if ($r->base->as_string() =~ m,/verify_age,) {
208 $self->debug('Video requires age verification');
209 my @logindata = $self->__login($videourl, $ua);
211 $metadata->{'COOKIE'} = $logindata[1];
212 unless(defined($r)) {
213 $self->error('Could not log into YouTube');
217 $content = $r->content();
219 $p = HTML::TokeParser->new(\$content);
221 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
222 if ('meta' eq $tag->[0]) {
223 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
224 $metadata->{'TITLE'} = $tag->[1]->{'content'};
225 # Convert HTML entities in the title. This is a bit convoluted.
226 $metadata->{'TITLE'} = decode_entities(
227 decode("utf8", $metadata->{'TITLE'}));
229 $self->debug('Title found: %s', $metadata->{'TITLE'});
231 } elsif ('script' eq $tag->[0]) {
235 $self->debug("Found script: %s", $e);
237 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
240 $self->debug("Found SWF_ARGS: %s", $args);
241 $jsp = videosite::JSArrayParser->new();
242 $self->debug("Using %s to parse", ref($jsp));
243 $r = $jsp->parse($args);
245 unless(defined($r)) {
246 $self->error("Found information hash, but could not parse");
250 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
251 my $urls = $r->{'fmt_url_map'};
253 $self->debug("Video has fmt_url_map: %s", $urls);
255 $urls = $self->decode_hexurl($urls);
256 %urls = split(/[\|,]/, $urls);
257 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
259 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
260 my $thash = $r->{'t'};
262 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
263 my $fmt = $r->{'fmt_map'};
266 $self->debug('Video has fmt_map');
267 $fmt = $self->decode_hexurl($fmt);
268 @fmt = split(/,/, $fmt);
271 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
276 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
279 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
282 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
285 $self->error('Neither fmt_url_map nor t found in video information hash');
288 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
290 $self->debug("Video has fmt_url_map: %s", $urls);
292 $urls = $self->decode_hexurl($urls);
293 %urls = split(/[\|,]/, $urls);
294 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
295 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
297 $self->debug("Found PLAYER_CONFIG: %s", $args);
299 $jsp = videosite::JSArrayParser->new();
300 $self->debug("Using %s to parse", ref($jsp));
301 $r = $jsp->parse($args);
303 unless(defined($r)) {
304 $self->error("Found information hash, but could not parse");
308 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
309 $self->error("Video URL seems to point to a live stream, cannot save this");
313 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
314 my $urls = $r->{'args'}->{'fmt_url_map'};
316 $self->debug("Video has fmt_url_map: %s", $urls);
318 %urls = split(/[\|,]/, $urls);
319 foreach (keys(%urls)) {
320 $urls{$_} = $self->decode_hexurl($urls{$_});
322 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
323 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
324 %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
326 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
328 $self->error('fmt_url_map not found in PLAYER_CONFIG');
334 $self->__pick_url(\%urls, $preflist, $metadata);
337 } elsif ('div' eq $tag->[0]) {
338 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
339 # Search forward to the next <div>
340 $tag = $p->get_tag('div');
341 $self->error("Could not get video data for youtube %s: %s",
342 $metadata->{'ID'}, $p->get_trimmed_text());
348 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
349 $self->error('Could not determine download URL');
358 my $videourl = shift;
360 my $user = $self->_getval('USERNAME');
361 my $pass = $self->_getval('PASSWORD');
373 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
378 sub get_all_cookies {
383 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
388 if (($user eq '') or ($pass eq '')) {
389 $self->error('No username or password defined for YouTube');
393 $self->debug('Logging in');
394 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
395 unless($r->is_success()) {
396 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
399 $c = $r->decoded_content();
400 $p = HTML::TokeParser->new(\$c);
401 while (my $tag = $p->get_tag('input')) {
402 $self->debug("%s", Dumper($tag));
403 if ($tag->[1]{name} eq 'GALX') {
404 $token = $tag->[1]{value};
408 $self->debug("GALX = %s", $token);
409 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
410 unless($r->is_success()) {
411 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
414 $c = $r -> decoded_content();
415 $p = HTML::TokeParser->new(\$c);
416 while (my $tag = $p->get_tag('script')) {
417 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
419 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
423 $r = $ua->get($token);
424 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
425 $self->error('Could not log into YouTube');
429 $self->debug("Got a cookie");
431 $r = $ua->get($videourl);
432 if ($r->base->as_string() =~ m,/verify_age,) {
433 $self->debug("Looking for session token...");
434 $c = $r->decoded_content();
435 $p = HTML::TokeParser->new(\$c);
436 while (my $tag = $p->get_tag('script')) {
437 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
443 unless(defined($token)) {
444 $self->error("Could not find session token");
448 $self->debug('Authenticating session...');
449 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
452 # Apparently there is no longer a specific "is_adult" cookie
453 # or, by the looks of it, anything similar
455 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
456 # $self->error('Could not authenticate session');
460 my $cookie = get_all_cookies($ua->cookie_jar);
461 return ($ua->get($videourl), $cookie);
464 # Take an encoded url_encoded_fmt_stream_map and return a hash
465 # matching video IDs to download URLs
466 sub _decode_url_encoded_fmt_stream_map {
469 my $dataencoded = shift;
472 $data = $self->decode_hexurl($data) if $dataencoded;
474 # - Split the decoded string into segments (along ,)
475 # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
476 # - URL-decode each key and value _again_
478 # @data will be an array of hash references
480 @data = map { { map { $self->decode_hexurl($_) } split /[&=]/ } } split /,/, $data;
481 $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
483 # From each array entry, pick the itag and the url values and return that
484 # as a hash reference
486 return { map { $_->{'itag'}, $_->{'url'} } @data };
494 my $preflist = shift;
495 my $metadata = shift;
497 foreach (keys(%{$urls})) {
498 if (exists($videoformats{$_})) {
499 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
501 $self->error('Unknown format %s: %s', $_, $urls->{$_});
505 foreach (@{$preflist}) {
506 if (exists($urls->{$_})) {
507 $self->debug("Selected URL with quality level %s", $_);
508 $metadata->{'DLURL'} = $urls->{$_};
513 $self->debug('URL found: %s', $metadata->{'DLURL'});