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\?(?:.+=.+&)*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_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
34 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
35 '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
36 $self->{'_PARAMS'} = {
37 'QUALITY' => ['normal', 'Quality of the video to download.', {
38 'normal' => 'standard resolution flash video',
39 'high' => 'higher resolution flash video',
40 'h264' => 'high resolution MPEG4 video',
41 'hd' => 'HD720 resolution'}],
42 'USERNAME' => ['', 'Username to use for YouTube login'],
43 'PASSWORD' => ['', 'Password to use for YouTube login']};
46 $self->_prepare_parameters();
60 my $jar = HTTP::Cookies->new;
61 my $ua = LWP::UserAgent->new('agent' => 'Mozilla/5.0');
64 my $quality = $self->_getval('QUALITY');
66 'insane' => [38, 37, 22, 35, 18, 34, 6, 5],
67 'hd' => [37, 22, 35, 18, 34, 6, 5, 38],
68 'h264' => [18, 34, 37, 22, 35, 6, 5, 38],
69 'high' => [34, 35, 18, 37, 22, 6, 5, 38],
70 'normal' => [6, 5, 34, 35, 18, 22, 37, 38]);
73 37 => 'mp4,h264,1080p',
74 35 => 'flv,h264,large',
76 22 => 'mp4,h264,720p',
86 $metadata->{'URL'} = $url;
87 $metadata->{'ID'} = $2;
88 $metadata->{'TYPE'} = 'video';
89 $metadata->{'SOURCE'} = $self->{'NAME'};
90 $metadata->{'TITLE'} = undef;
91 $metadata->{'DLURL'} = undef;
92 $metadata->{'COOKIE'} = undef;
94 $self->debug("Matched id %s from pattern %s", $2, $pattern);
96 $preflist = $preflist{$quality};
97 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
99 $videourl = sprintf('https://www.youtube.com/watch?v=%s', $2);
101 unless(defined($r = $ua->get($videourl))) {
102 $self->error('Could not download %s', $url);
106 if ($r->base->as_string() =~ m,/verify_age,) {
107 $self->debug('Video requires age verification');
108 $ua->cookie_jar($jar);
109 my @logindata = $self->__login($videourl, $ua);
111 $metadata->{'COOKIE'} = $logindata[1];
112 unless(defined($r)) {
113 $self->error('Could not log into YouTube');
117 $content = $r->content();
119 $p = HTML::TokeParser->new(\$content);
121 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
122 if ('meta' eq $tag->[0]) {
123 if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
124 $metadata->{'TITLE'} = $tag->[1]->{'content'};
125 # Convert HTML entities in the title. This is a bit convoluted.
126 $metadata->{'TITLE'} = encode("utf8",
128 decode("utf8", $metadata->{'TITLE'})));
130 $self->debug('Title found: %s', $metadata->{'TITLE'});
132 } elsif ('script' eq $tag->[0]) {
136 $self->debug("Found script: %s", $e);
138 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
141 $self->debug("Found SWF_ARGS: %s", $args);
142 $jsp = videosite::JSArrayParser->new();
143 $self->debug("Using %s to parse", ref($jsp));
144 $r = $jsp->parse($args);
146 unless(defined($r)) {
147 $self->error("Found information hash, but could not parse");
151 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
152 my $urls = $r->{'fmt_url_map'};
154 $self->debug("Video has fmt_url_map: %s", $urls);
156 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
157 %urls = split(/[\|,]/, $urls);
158 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
160 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
161 my $thash = $r->{'t'};
163 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
164 my $fmt = $r->{'fmt_map'};
167 $self->debug('Video has fmt_map');
168 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
169 @fmt = split(/,/, $fmt);
172 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
177 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
180 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
183 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
186 $self->error('Neither fmt_url_map nor t found in video information hash');
189 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
191 $self->debug("Video has fmt_url_map: %s", $urls);
193 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
194 %urls = split(/[\|,]/, $urls);
195 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
199 foreach (keys(%urls)) {
200 if (exists($videoformats{$_})) {
201 $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls{$_});
203 $self->error('Unknown format %s: %s', $_, $urls{$_});
207 foreach (@{$preflist}) {
208 if (exists($urls{$_})) {
209 $self->debug("Selected URL with quality level %s", $_);
210 $metadata->{'DLURL'} = $urls{$_};
215 $self->debug('URL found: %s', $metadata->{'DLURL'});
218 } elsif ('div' eq $tag->[0]) {
219 if (exists($tag->[1]->{'class'}) and ('yt-alert-content' eq $tag->[1]->{'class'})) {
220 $self->error("Could not get video data for youtube %s: %s",
221 $metadata->{'ID'}, $p->get_trimmed_text());
227 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
228 $self->error('Could not determine download URL');
237 my $videourl = shift;
239 my $user = $self->_getval('USERNAME');
240 my $pass = $self->_getval('PASSWORD');
252 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
257 sub get_all_cookies {
262 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
267 if (($user eq '') or ($pass eq '')) {
268 $self->error('No username or password defined for YouTube');
272 $self->debug('Logging in');
273 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
274 unless($r->is_success()) {
275 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
278 $c = $r->decoded_content();
279 $p = HTML::TokeParser->new(\$c);
280 while (my $tag = $p->get_tag('input')) {
281 $self->debug("%s", Dumper($tag));
282 if ($tag->[1]{name} eq 'GALX') {
283 $token = $tag->[1]{value};
287 $self->debug("GALX = %s", $token);
288 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
289 unless($r->is_success()) {
290 $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
293 $c = $r -> decoded_content();
294 $p = HTML::TokeParser->new(\$c);
295 while (my $tag = $p->get_tag('script')) {
296 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
298 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
302 $r = $ua->get($token);
303 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
304 $self->error('Could not log into YouTube');
308 $self->debug("Got a cookie");
310 $r = $ua->get($videourl);
311 if ($r->base->as_string() =~ m,/verify_age,) {
312 $self->debug("Looking for session token...");
313 $c = $r->decoded_content();
314 $p = HTML::TokeParser->new(\$c);
315 while (my $tag = $p->get_tag('script')) {
316 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
322 unless(defined($token)) {
323 $self->error("Could not find session token");
327 $self->debug('Authenticating session...');
328 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
331 # Apparently there is no longer a specific "is_adult" cookie
332 # or, by the looks of it, anything similar
334 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
335 # $self->error('Could not authenticate session');
339 my $cookie = get_all_cookies($ua->cookie_jar);
340 return ($ua->get($videourl), $cookie);