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'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
211 $self->error("Video URL seems to point to a live stream, cannot save this");
215 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
216 my $urls = $r->{'args'}->{'fmt_url_map'};
218 $self->debug("Video has fmt_url_map: %s", $urls);
220 %urls = split(/[\|,]/, $urls);
221 foreach (keys(%urls)) {
223 $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
226 $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
228 $self->error('fmt_url_map not found in PLAYER_CONFIG');
234 foreach (keys(%urls)) {
235 if (exists($videoformats{$_})) {
236 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls{$_});
238 $self->error('Unknown format %s: %s', $_, $urls{$_});
242 foreach (@{$preflist}) {
243 if (exists($urls{$_})) {
244 $self->debug("Selected URL with quality level %s", $_);
245 $metadata->{'DLURL'} = $urls{$_};
250 $self->debug('URL found: %s', $metadata->{'DLURL'});
253 } elsif ('div' eq $tag->[0]) {
254 if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
255 # Search forward to the next <div>
256 $tag = $p->get_tag('div');
257 $self->error("Could not get video data for youtube %s: %s",
258 $metadata->{'ID'}, $p->get_trimmed_text());
264 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
265 $self->error('Could not determine download URL');
274 my $videourl = shift;
276 my $user = $self->_getval('USERNAME');
277 my $pass = $self->_getval('PASSWORD');
289 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
294 sub get_all_cookies {
299 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
304 if (($user eq '') or ($pass eq '')) {
305 $self->error('No username or password defined for YouTube');
309 $self->debug('Logging in');
310 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
311 unless($r->is_success()) {
312 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
315 $c = $r->decoded_content();
316 $p = HTML::TokeParser->new(\$c);
317 while (my $tag = $p->get_tag('input')) {
318 $self->debug("%s", Dumper($tag));
319 if ($tag->[1]{name} eq 'GALX') {
320 $token = $tag->[1]{value};
324 $self->debug("GALX = %s", $token);
325 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
326 unless($r->is_success()) {
327 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
330 $c = $r -> decoded_content();
331 $p = HTML::TokeParser->new(\$c);
332 while (my $tag = $p->get_tag('script')) {
333 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
335 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
339 $r = $ua->get($token);
340 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
341 $self->error('Could not log into YouTube');
345 $self->debug("Got a cookie");
347 $r = $ua->get($videourl);
348 if ($r->base->as_string() =~ m,/verify_age,) {
349 $self->debug("Looking for session token...");
350 $c = $r->decoded_content();
351 $p = HTML::TokeParser->new(\$c);
352 while (my $tag = $p->get_tag('script')) {
353 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
359 unless(defined($token)) {
360 $self->error("Could not find session token");
364 $self->debug('Authenticating session...');
365 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
368 # Apparently there is no longer a specific "is_adult" cookie
369 # or, by the looks of it, anything similar
371 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
372 # $self->error('Could not authenticate session');
376 my $cookie = get_all_cookies($ua->cookie_jar);
377 return ($ua->get($videourl), $cookie);