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');
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 $self->__pick_url($urls, $preflist, $metadata);
146 $metadata->{'TITLE'} = $content->{'title'};
147 $metadata->{'TITLE'} =~ s/\+/ /g;
148 $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
150 $self->debug('Title found: %s', $metadata->{'TITLE'});
152 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
153 $self->error('Could not determine download URL');
160 sub _parse_by_scrape {
169 my $ua = $self->ua();
172 my $quality = $self->_getval('QUALITY');
176 $metadata->{'URL'} = $url;
177 $metadata->{'ID'} = $id;
178 $metadata->{'TYPE'} = 'video';
179 $metadata->{'SOURCE'} = $self->{'NAME'};
180 $metadata->{'TITLE'} = undef;
181 $metadata->{'DLURL'} = undef;
182 $metadata->{'COOKIE'} = undef;
185 $preflist = $preflist{$quality};
186 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
188 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $id);
190 unless(defined($r = $ua->get($videourl))) {
191 $self->error('Could not download %s', $url);
195 if ($r->base->as_string() =~ m,/verify_age,) {
196 $self->debug('Video requires age verification');
197 my @logindata = $self->__login($videourl, $ua);
199 $metadata->{'COOKIE'} = $logindata[1];
200 unless(defined($r)) {
201 $self->error('Could not log into YouTube');
205 $content = $r->content();
207 $p = HTML::TokeParser->new(\$content);
209 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
210 if ('meta' eq $tag->[0]) {
211 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
212 $metadata->{'TITLE'} = $tag->[1]->{'content'};
213 # Convert HTML entities in the title. This is a bit convoluted.
214 $metadata->{'TITLE'} = encode("utf8",
216 decode("utf8", $metadata->{'TITLE'})));
218 $self->debug('Title found: %s', $metadata->{'TITLE'});
220 } elsif ('script' eq $tag->[0]) {
224 $self->debug("Found script: %s", $e);
226 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
229 $self->debug("Found SWF_ARGS: %s", $args);
230 $jsp = videosite::JSArrayParser->new();
231 $self->debug("Using %s to parse", ref($jsp));
232 $r = $jsp->parse($args);
234 unless(defined($r)) {
235 $self->error("Found information hash, but could not parse");
239 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
240 my $urls = $r->{'fmt_url_map'};
242 $self->debug("Video has fmt_url_map: %s", $urls);
244 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
245 %urls = split(/[\|,]/, $urls);
246 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
248 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
249 my $thash = $r->{'t'};
251 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
252 my $fmt = $r->{'fmt_map'};
255 $self->debug('Video has fmt_map');
256 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
257 @fmt = split(/,/, $fmt);
260 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
265 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
268 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
271 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
274 $self->error('Neither fmt_url_map nor t found in video information hash');
277 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
279 $self->debug("Video has fmt_url_map: %s", $urls);
281 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
282 %urls = split(/[\|,]/, $urls);
283 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
284 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
286 $self->debug("Found PLAYER_CONFIG: %s", $args);
288 $jsp = videosite::JSArrayParser->new();
289 $self->debug("Using %s to parse", ref($jsp));
290 $r = $jsp->parse($args);
292 unless(defined($r)) {
293 $self->error("Found information hash, but could not parse");
297 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
298 $self->error("Video URL seems to point to a live stream, cannot save this");
302 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
303 my $urls = $r->{'args'}->{'fmt_url_map'};
305 $self->debug("Video has fmt_url_map: %s", $urls);
307 %urls = split(/[\|,]/, $urls);
308 foreach (keys(%urls)) {
310 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
313 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
315 $self->error('fmt_url_map not found in PLAYER_CONFIG');
321 $self->__pick_url(\%urls, $preflist, $metadata);
324 } elsif ('div' eq $tag->[0]) {
325 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
326 # Search forward to the next <div>
327 $tag = $p->get_tag('div');
328 $self->error("Could not get video data for youtube %s: %s",
329 $metadata->{'ID'}, $p->get_trimmed_text());
335 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
336 $self->error('Could not determine download URL');
345 my $videourl = shift;
347 my $user = $self->_getval('USERNAME');
348 my $pass = $self->_getval('PASSWORD');
360 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
365 sub get_all_cookies {
370 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
375 if (($user eq '') or ($pass eq '')) {
376 $self->error('No username or password defined for YouTube');
380 $self->debug('Logging in');
381 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
382 unless($r->is_success()) {
383 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
386 $c = $r->decoded_content();
387 $p = HTML::TokeParser->new(\$c);
388 while (my $tag = $p->get_tag('input')) {
389 $self->debug("%s", Dumper($tag));
390 if ($tag->[1]{name} eq 'GALX') {
391 $token = $tag->[1]{value};
395 $self->debug("GALX = %s", $token);
396 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
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('script')) {
404 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
406 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
410 $r = $ua->get($token);
411 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
412 $self->error('Could not log into YouTube');
416 $self->debug("Got a cookie");
418 $r = $ua->get($videourl);
419 if ($r->base->as_string() =~ m,/verify_age,) {
420 $self->debug("Looking for session token...");
421 $c = $r->decoded_content();
422 $p = HTML::TokeParser->new(\$c);
423 while (my $tag = $p->get_tag('script')) {
424 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
430 unless(defined($token)) {
431 $self->error("Could not find session token");
435 $self->debug('Authenticating session...');
436 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
439 # Apparently there is no longer a specific "is_adult" cookie
440 # or, by the looks of it, anything similar
442 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
443 # $self->error('Could not authenticate session');
447 my $cookie = get_all_cookies($ua->cookie_jar);
448 return ($ua->get($videourl), $cookie);
454 my $preflist = shift;
455 my $metadata = shift;
457 foreach (keys(%{$urls})) {
458 if (exists($videoformats{$_})) {
459 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
461 $self->error('Unknown format %s: %s', $_, $urls->{$_});
465 foreach (@{$preflist}) {
466 if (exists($urls->{$_})) {
467 $self->debug("Selected URL with quality level %s", $_);
468 $metadata->{'DLURL'} = $urls->{$_};
473 $self->debug('URL found: %s', $metadata->{'DLURL'});