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],
24 'hd' => [37, 22, 35, 18, 34, 6, 5, 38],
25 'h264' => [18, 34, 37, 22, 35, 6, 5, 38],
26 'high' => [34, 35, 18, 37, 22, 6, 5, 38],
27 'normal' => [6, 5, 34, 35, 18, 22, 37, 38]);
30 37 => 'mp4,h264,1080p',
31 35 => 'flv,h264,large',
33 22 => 'mp4,h264,720p',
40 my $self = $class->SUPER::new();
42 $self->{'NAME'} = 'youtube';
43 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
44 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
45 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
46 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
47 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
48 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
49 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
50 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
51 $self->{'_PARAMS'} = {
52 'QUALITY' => ['normal', 'Quality of the video to download.', {
53 'normal' => 'standard resolution flash video',
54 'high' => 'higher resolution flash video',
55 'h264' => 'high resolution MPEG4 video',
56 'hd' => 'HD720 resolution'}],
57 'USERNAME' => ['', 'Username to use for YouTube login'],
58 'PASSWORD' => ['', 'Password to use for YouTube login']};
61 $self->_prepare_parameters();
73 my $url =~ m|$pattern|;
77 $self->debug("Matched id %s from pattern %s", $id, $pattern);
79 $res = $self->_parse_by_video_info($url, $id);
80 if (defined($res) && ref($res)) {
83 $res = $self->_parse_by_scrape($url, $id);
89 sub _parse_by_video_info {
93 my $quality = $self->_getval('QUALITY');
96 my $ua = $self->{_ua};
102 $metadata->{'URL'} = $url;
103 $metadata->{'ID'} = $id;
104 $metadata->{'TYPE'} = 'video';
105 $metadata->{'SOURCE'} = $self->{'NAME'};
106 $metadata->{'TITLE'} = undef;
107 $metadata->{'DLURL'} = undef;
108 $metadata->{'COOKIE'} = undef;
110 $preflist = $preflist{$quality};
111 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
113 $videourl = sprintf('https://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
114 $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
115 $self->debug("Video info URL: %s", $videourl);
117 $r = $ua->get($videourl);
118 unless($r->is_success()) {
119 $self->debug('Could not download %s: %s', $videourl, $r->code());
123 $content = $r->content();
124 $self->debug('Content from get_video_info: %s', $content);
127 $content = { split /[&=]/, $content };
129 if ($content->{'status'} ne 'ok') {
130 $self->debug("Non OK status code found: %s", $content->{'status'});
134 unless(exists($content->{'fmt_url_map'}) and exists($content->{'title'})) {
135 $self->debug("No fmt_url_map or no title found");
140 $urls = $content->{'fmt_url_map'};
141 $urls =~ s/%(..)/chr(hex($1))/ge;
142 $urls = { split /[\|,]/, $urls };
144 foreach (keys(%{$urls})) {
145 if (exists($videoformats{$_})) {
146 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
148 $self->error('Unknown format %s: %s', $_, $urls->{$_});
152 foreach (@{$preflist}) {
153 if (exists($urls->{$_})) {
154 $self->debug("Selected URL with quality level %s", $_);
155 $metadata->{'DLURL'} = $urls->{$_};
160 $self->debug('URL found: %s', $metadata->{'DLURL'});
162 $metadata->{'TITLE'} = $content->{'title'};
163 $metadata->{'TITLE'} =~ s/\+/ /g;
164 $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
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('https://www.youtube.com/watch?v=%s', $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'} = encode("utf8",
232 decode("utf8", $metadata->{'TITLE'})));
234 $self->debug('Title found: %s', $metadata->{'TITLE'});
236 } elsif ('script' eq $tag->[0]) {
240 $self->debug("Found script: %s", $e);
242 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
245 $self->debug("Found SWF_ARGS: %s", $args);
246 $jsp = videosite::JSArrayParser->new();
247 $self->debug("Using %s to parse", ref($jsp));
248 $r = $jsp->parse($args);
250 unless(defined($r)) {
251 $self->error("Found information hash, but could not parse");
255 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
256 my $urls = $r->{'fmt_url_map'};
258 $self->debug("Video has fmt_url_map: %s", $urls);
260 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
261 %urls = split(/[\|,]/, $urls);
262 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
264 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
265 my $thash = $r->{'t'};
267 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
268 my $fmt = $r->{'fmt_map'};
271 $self->debug('Video has fmt_map');
272 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
273 @fmt = split(/,/, $fmt);
276 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
281 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
284 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
287 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
290 $self->error('Neither fmt_url_map nor t found in video information hash');
293 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
295 $self->debug("Video has fmt_url_map: %s", $urls);
297 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
298 %urls = split(/[\|,]/, $urls);
299 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
300 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
302 $self->debug("Found PLAYER_CONFIG: %s", $args);
304 $jsp = videosite::JSArrayParser->new();
305 $self->debug("Using %s to parse", ref($jsp));
306 $r = $jsp->parse($args);
308 unless(defined($r)) {
309 $self->error("Found information hash, but could not parse");
313 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
314 $self->error("Video URL seems to point to a live stream, cannot save this");
318 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
319 my $urls = $r->{'args'}->{'fmt_url_map'};
321 $self->debug("Video has fmt_url_map: %s", $urls);
323 %urls = split(/[\|,]/, $urls);
324 foreach (keys(%urls)) {
326 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
329 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
331 $self->error('fmt_url_map not found in PLAYER_CONFIG');
337 foreach (keys(%urls)) {
338 if (exists($videoformats{$_})) {
339 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls{$_});
341 $self->error('Unknown format %s: %s', $_, $urls{$_});
345 foreach (@{$preflist}) {
346 if (exists($urls{$_})) {
347 $self->debug("Selected URL with quality level %s", $_);
348 $metadata->{'DLURL'} = $urls{$_};
353 $self->debug('URL found: %s', $metadata->{'DLURL'});
356 } elsif ('div' eq $tag->[0]) {
357 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
358 # Search forward to the next <div>
359 $tag = $p->get_tag('div');
360 $self->error("Could not get video data for youtube %s: %s",
361 $metadata->{'ID'}, $p->get_trimmed_text());
367 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
368 $self->error('Could not determine download URL');
377 my $videourl = shift;
379 my $user = $self->_getval('USERNAME');
380 my $pass = $self->_getval('PASSWORD');
392 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
397 sub get_all_cookies {
402 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
407 if (($user eq '') or ($pass eq '')) {
408 $self->error('No username or password defined for YouTube');
412 $self->debug('Logging in');
413 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
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('input')) {
421 $self->debug("%s", Dumper($tag));
422 if ($tag->[1]{name} eq 'GALX') {
423 $token = $tag->[1]{value};
427 $self->debug("GALX = %s", $token);
428 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
429 unless($r->is_success()) {
430 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
433 $c = $r -> decoded_content();
434 $p = HTML::TokeParser->new(\$c);
435 while (my $tag = $p->get_tag('script')) {
436 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
438 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
442 $r = $ua->get($token);
443 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
444 $self->error('Could not log into YouTube');
448 $self->debug("Got a cookie");
450 $r = $ua->get($videourl);
451 if ($r->base->as_string() =~ m,/verify_age,) {
452 $self->debug("Looking for session token...");
453 $c = $r->decoded_content();
454 $p = HTML::TokeParser->new(\$c);
455 while (my $tag = $p->get_tag('script')) {
456 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
462 unless(defined($token)) {
463 $self->error("Could not find session token");
467 $self->debug('Authenticating session...');
468 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
471 # Apparently there is no longer a specific "is_adult" cookie
472 # or, by the looks of it, anything similar
474 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
475 # $self->error('Could not authenticate session');
479 my $cookie = get_all_cookies($ua->cookie_jar);
480 return ($ua->get($videourl), $cookie);