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);
17 use HTML::Entities qw(decode_entities);
20 use videosite::JSArrayParser;
26 my $self = $class->SUPER::new();
28 $self->{'NAME'} = 'youtube';
29 $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
30 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
31 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
32 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
33 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+#p/\w/\d+/([-a-zA-Z0-9_]+))',
34 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
35 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
36 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
37 $self->{'_PARAMS'} = {
38 'QUALITY' => ['normal', 'Quality of the video to download.', {
39 'normal' => 'standard resolution flash video',
40 'high' => 'higher resolution flash video',
41 'h264' => 'high resolution MPEG4 video',
42 'hd' => 'HD720 resolution'}],
43 'USERNAME' => ['', 'Username to use for YouTube login'],
44 'PASSWORD' => ['', 'Password to use for YouTube login']};
47 $self->_prepare_parameters();
61 my $jar = HTTP::Cookies->new;
62 my $ua = LWP::UserAgent->new('agent' => 'Mozilla/5.0');
65 my $quality = $self->_getval('QUALITY');
67 'insane' => [38, 37, 22, 35, 18, 34, 6, 5],
68 'hd' => [37, 22, 35, 18, 34, 6, 5, 38],
69 'h264' => [18, 34, 37, 22, 35, 6, 5, 38],
70 'high' => [34, 35, 18, 37, 22, 6, 5, 38],
71 'normal' => [6, 5, 34, 35, 18, 22, 37, 38]);
74 37 => 'mp4,h264,1080p',
75 35 => 'flv,h264,large',
77 22 => 'mp4,h264,720p',
87 $metadata->{'URL'} = $url;
88 $metadata->{'ID'} = $2;
89 $metadata->{'TYPE'} = 'video';
90 $metadata->{'SOURCE'} = $self->{'NAME'};
91 $metadata->{'TITLE'} = undef;
92 $metadata->{'DLURL'} = undef;
93 $metadata->{'COOKIE'} = undef;
95 $self->debug("Matched id %s from pattern %s", $2, $pattern);
97 $preflist = $preflist{$quality};
98 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
100 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $2);
102 unless(defined($r = $ua->get($videourl))) {
103 $self->error('Could not download %s', $url);
107 if ($r->base->as_string() =~ m,/verify_age,) {
108 $self->debug('Video requires age verification');
109 $ua->cookie_jar($jar);
110 my @logindata = $self->__login($videourl, $ua);
112 $metadata->{'COOKIE'} = $logindata[1];
113 unless(defined($r)) {
114 $self->error('Could not log into YouTube');
118 $content = $r->content();
120 $p = HTML::TokeParser->new(\$content);
122 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
123 if ('meta' eq $tag->[0]) {
124 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
125 $metadata->{'TITLE'} = $tag->[1]->{'content'};
126 # Convert HTML entities in the title. This is a bit convoluted.
127 $metadata->{'TITLE'} = encode("utf8",
129 decode("utf8", $metadata->{'TITLE'})));
131 $self->debug('Title found: %s', $metadata->{'TITLE'});
133 } elsif ('script' eq $tag->[0]) {
137 $self->debug("Found script: %s", $e);
139 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
142 $self->debug("Found SWF_ARGS: %s", $args);
143 $jsp = videosite::JSArrayParser->new();
144 $self->debug("Using %s to parse", ref($jsp));
145 $r = $jsp->parse($args);
147 unless(defined($r)) {
148 $self->error("Found information hash, but could not parse");
152 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
153 my $urls = $r->{'fmt_url_map'};
155 $self->debug("Video has fmt_url_map: %s", $urls);
157 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
158 %urls = split(/[\|,]/, $urls);
159 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
161 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
162 my $thash = $r->{'t'};
164 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
165 my $fmt = $r->{'fmt_map'};
168 $self->debug('Video has fmt_map');
169 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
170 @fmt = split(/,/, $fmt);
173 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
178 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
181 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
184 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
187 $self->error('Neither fmt_url_map nor t found in video information hash');
190 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
192 $self->debug("Video has fmt_url_map: %s", $urls);
194 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
195 %urls = split(/[\|,]/, $urls);
196 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
197 } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
199 $self->debug("Found PLAYER_CONFIG: %s", $args);
201 $jsp = videosite::JSArrayParser->new();
202 $self->debug("Using %s to parse", ref($jsp));
203 $r = $jsp->parse($args);
205 unless(defined($r)) {
206 $self->error("Found information hash, but could not parse");
210 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
211 my $urls = $r->{'args'}->{'fmt_url_map'};
213 $self->debug("Video has fmt_url_map: %s", $urls);
215 %urls = split(/[\|,]/, $urls);
216 foreach (keys(%urls)) {
218 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
221 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
223 $self->error('fmt_url_map not found in PLAYER_CONFIG');
228 foreach (keys(%urls)) {
229 if (exists($videoformats{$_})) {
230 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls{$_});
232 $self->error('Unknown format %s: %s', $_, $urls{$_});
236 foreach (@{$preflist}) {
237 if (exists($urls{$_})) {
238 $self->debug("Selected URL with quality level %s", $_);
239 $metadata->{'DLURL'} = $urls{$_};
244 $self->debug('URL found: %s', $metadata->{'DLURL'});
247 } elsif ('div' eq $tag->[0]) {
248 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
249 # Search forward to the next <div>
250 $tag = $p->get_tag('div');
251 $self->error("Could not get video data for youtube %s: %s",
252 $metadata->{'ID'}, $p->get_trimmed_text());
258 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
259 $self->error('Could not determine download URL');
268 my $videourl = shift;
270 my $user = $self->_getval('USERNAME');
271 my $pass = $self->_getval('PASSWORD');
283 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
288 sub get_all_cookies {
293 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
298 if (($user eq '') or ($pass eq '')) {
299 $self->error('No username or password defined for YouTube');
303 $self->debug('Logging in');
304 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
305 unless($r->is_success()) {
306 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
309 $c = $r->decoded_content();
310 $p = HTML::TokeParser->new(\$c);
311 while (my $tag = $p->get_tag('input')) {
312 $self->debug("%s", Dumper($tag));
313 if ($tag->[1]{name} eq 'GALX') {
314 $token = $tag->[1]{value};
318 $self->debug("GALX = %s", $token);
319 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
320 unless($r->is_success()) {
321 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
324 $c = $r -> decoded_content();
325 $p = HTML::TokeParser->new(\$c);
326 while (my $tag = $p->get_tag('script')) {
327 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
329 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
333 $r = $ua->get($token);
334 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
335 $self->error('Could not log into YouTube');
339 $self->debug("Got a cookie");
341 $r = $ua->get($videourl);
342 if ($r->base->as_string() =~ m,/verify_age,) {
343 $self->debug("Looking for session token...");
344 $c = $r->decoded_content();
345 $p = HTML::TokeParser->new(\$c);
346 while (my $tag = $p->get_tag('script')) {
347 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
353 unless(defined($token)) {
354 $self->error("Could not find session token");
358 $self->debug('Authenticating session...');
359 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
362 # Apparently there is no longer a specific "is_adult" cookie
363 # or, by the looks of it, anything similar
365 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
366 # $self->error('Could not authenticate session');
370 my $cookie = get_all_cookies($ua->cookie_jar);
371 return ($ua->get($videourl), $cookie);