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']};
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 unless(exists($content->{'fmt_url_map'}) and exists($content->{'title'})) {
138 $self->debug("No fmt_url_map or no title found");
143 $urls = $content->{'fmt_url_map'};
144 $urls =~ s/%(..)/chr(hex($1))/ge;
145 $urls = { split /[\|,]/, $urls };
147 $self->__pick_url($urls, $preflist, $metadata);
149 $metadata->{'TITLE'} = $content->{'title'};
150 $metadata->{'TITLE'} =~ s/\+/ /g;
151 $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
152 $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
154 $self->debug('Title found: %s', $metadata->{'TITLE'});
156 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
157 $self->error('Could not determine download URL');
164 sub _parse_by_scrape {
173 my $ua = $self->ua();
176 my $quality = $self->_getval('QUALITY');
180 $metadata->{'URL'} = $url;
181 $metadata->{'ID'} = $id;
182 $metadata->{'TYPE'} = 'video';
183 $metadata->{'SOURCE'} = $self->{'NAME'};
184 $metadata->{'TITLE'} = undef;
185 $metadata->{'DLURL'} = undef;
186 $metadata->{'COOKIE'} = undef;
189 $preflist = $preflist{$quality};
190 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
192 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $id);
194 unless(defined($r = $ua->get($videourl))) {
195 $self->error('Could not download %s', $url);
199 if ($r->base->as_string() =~ m,/verify_age,) {
200 $self->debug('Video requires age verification');
201 my @logindata = $self->__login($videourl, $ua);
203 $metadata->{'COOKIE'} = $logindata[1];
204 unless(defined($r)) {
205 $self->error('Could not log into YouTube');
209 $content = $r->content();
211 $p = HTML::TokeParser->new(\$content);
213 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
214 if ('meta' eq $tag->[0]) {
215 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
216 $metadata->{'TITLE'} = $tag->[1]->{'content'};
217 # Convert HTML entities in the title. This is a bit convoluted.
218 $metadata->{'TITLE'} = decode_entities(
219 decode("utf8", $metadata->{'TITLE'}));
221 $self->debug('Title found: %s', $metadata->{'TITLE'});
223 } elsif ('script' eq $tag->[0]) {
227 $self->debug("Found script: %s", $e);
229 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
232 $self->debug("Found SWF_ARGS: %s", $args);
233 $jsp = videosite::JSArrayParser->new();
234 $self->debug("Using %s to parse", ref($jsp));
235 $r = $jsp->parse($args);
237 unless(defined($r)) {
238 $self->error("Found information hash, but could not parse");
242 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
243 my $urls = $r->{'fmt_url_map'};
245 $self->debug("Video has fmt_url_map: %s", $urls);
247 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
248 %urls = split(/[\|,]/, $urls);
249 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
251 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
252 my $thash = $r->{'t'};
254 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
255 my $fmt = $r->{'fmt_map'};
258 $self->debug('Video has fmt_map');
259 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
260 @fmt = split(/,/, $fmt);
263 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
268 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
271 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
274 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
277 $self->error('Neither fmt_url_map nor t found in video information hash');
280 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
282 $self->debug("Video has fmt_url_map: %s", $urls);
284 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
285 %urls = split(/[\|,]/, $urls);
286 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
287 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
289 $self->debug("Found PLAYER_CONFIG: %s", $args);
291 $jsp = videosite::JSArrayParser->new();
292 $self->debug("Using %s to parse", ref($jsp));
293 $r = $jsp->parse($args);
295 unless(defined($r)) {
296 $self->error("Found information hash, but could not parse");
300 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
301 $self->error("Video URL seems to point to a live stream, cannot save this");
305 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
306 my $urls = $r->{'args'}->{'fmt_url_map'};
308 $self->debug("Video has fmt_url_map: %s", $urls);
310 %urls = split(/[\|,]/, $urls);
311 foreach (keys(%urls)) {
313 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
316 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
318 $self->error('fmt_url_map not found in PLAYER_CONFIG');
324 $self->__pick_url(\%urls, $preflist, $metadata);
327 } elsif ('div' eq $tag->[0]) {
328 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
329 # Search forward to the next <div>
330 $tag = $p->get_tag('div');
331 $self->error("Could not get video data for youtube %s: %s",
332 $metadata->{'ID'}, $p->get_trimmed_text());
338 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
339 $self->error('Could not determine download URL');
348 my $videourl = shift;
350 my $user = $self->_getval('USERNAME');
351 my $pass = $self->_getval('PASSWORD');
363 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
368 sub get_all_cookies {
373 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
378 if (($user eq '') or ($pass eq '')) {
379 $self->error('No username or password defined for YouTube');
383 $self->debug('Logging in');
384 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
385 unless($r->is_success()) {
386 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
389 $c = $r->decoded_content();
390 $p = HTML::TokeParser->new(\$c);
391 while (my $tag = $p->get_tag('input')) {
392 $self->debug("%s", Dumper($tag));
393 if ($tag->[1]{name} eq 'GALX') {
394 $token = $tag->[1]{value};
398 $self->debug("GALX = %s", $token);
399 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
400 unless($r->is_success()) {
401 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
404 $c = $r -> decoded_content();
405 $p = HTML::TokeParser->new(\$c);
406 while (my $tag = $p->get_tag('script')) {
407 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
409 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
413 $r = $ua->get($token);
414 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
415 $self->error('Could not log into YouTube');
419 $self->debug("Got a cookie");
421 $r = $ua->get($videourl);
422 if ($r->base->as_string() =~ m,/verify_age,) {
423 $self->debug("Looking for session token...");
424 $c = $r->decoded_content();
425 $p = HTML::TokeParser->new(\$c);
426 while (my $tag = $p->get_tag('script')) {
427 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
433 unless(defined($token)) {
434 $self->error("Could not find session token");
438 $self->debug('Authenticating session...');
439 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
442 # Apparently there is no longer a specific "is_adult" cookie
443 # or, by the looks of it, anything similar
445 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
446 # $self->error('Could not authenticate session');
450 my $cookie = get_all_cookies($ua->cookie_jar);
451 return ($ua->get($videourl), $cookie);
457 my $preflist = shift;
458 my $metadata = shift;
460 foreach (keys(%{$urls})) {
461 if (exists($videoformats{$_})) {
462 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
464 $self->error('Unknown format %s: %s', $_, $urls->{$_});
468 foreach (@{$preflist}) {
469 if (exists($urls->{$_})) {
470 $self->debug("Selected URL with quality level %s", $_);
471 $metadata->{'DLURL'} = $urls->{$_};
476 $self->debug('URL found: %s', $metadata->{'DLURL'});