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'} = ['(http://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
30 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
31 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
32 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
33 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
34 $self->{'_PARAMS'} = {
35 'QUALITY' => ['normal', 'Quality of the video to download.', {
36 'normal' => 'standard resolution flash video',
37 'high' => 'higher resolution flash video',
38 'h264' => 'high resolution MPEG4 video',
39 'hd' => 'HD720 resolution'}],
40 'USERNAME' => ['', 'Username to use for YouTube login'],
41 'PASSWORD' => ['', 'Password to use for YouTube login']};
44 $self->_prepare_parameters();
58 my $jar = HTTP::Cookies->new;
59 my $ua = LWP::UserAgent->new('agent' => 'Mozilla/5.0');
62 my $quality = $self->_getval('QUALITY');
64 'insane' => [38, 37, 22, 35, 18, 34, 6, 5],
65 'hd' => [37, 22, 35, 18, 34, 6, 5, 38],
66 'h264' => [18, 34, 37, 22, 35, 6, 5, 38],
67 'high' => [34, 35, 18, 37, 22, 6, 5, 38],
68 'normal' => [6, 5, 34, 35, 18, 22, 37, 38]);
75 $metadata->{'URL'} = $url;
76 $metadata->{'ID'} = $2;
77 $metadata->{'TYPE'} = 'video';
78 $metadata->{'SOURCE'} = $self->{'NAME'};
79 $metadata->{'TITLE'} = undef;
80 $metadata->{'DLURL'} = undef;
81 $metadata->{'COOKIE'} = undef;
83 $self->debug("Matched id %s from pattern %s", $2, $pattern);
85 $preflist = $preflist{$quality};
86 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
88 $videourl = sprintf('http://www.youtube.com/watch?v=%s', $2);
90 unless(defined($r = $ua->get($videourl))) {
91 $self->error('Could not download %s', $url);
95 if ($r->base->as_string() =~ m,/verify_age,) {
96 $self->debug('Video requires age verification');
97 $ua->cookie_jar($jar);
98 my @logindata = $self->__login($videourl, $ua);
100 $metadata->{'COOKIE'} = $logindata[1];
101 unless(defined($r)) {
102 $self->error('Could not log into YouTube');
106 $content = $r->content();
108 $p = HTML::TokeParser->new(\$content);
110 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
111 if ('meta' eq $tag->[0]) {
112 if ('title' eq $tag->[1]->{'name'}) {
113 $metadata->{'TITLE'} = $tag->[1]->{'content'};
114 # Convert HTML entities in the title. This is a bit convoluted.
115 $metadata->{'TITLE'} = encode("utf8",
117 decode("utf8", $metadata->{'TITLE'})));
119 $self->debug('Title found: %s', $metadata->{'TITLE'});
121 } elsif ('script' eq $tag->[0]) {
125 $self->debug("Found script: %s", $e);
127 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
130 $self->debug("Found SWF_ARGS: %s", $args);
131 $jsp = videosite::JSArrayParser->new();
132 $self->debug("Using %s to parse", ref($jsp));
133 $r = $jsp->parse($args);
135 unless(defined($r)) {
136 $self->error("Found information hash, but could not parse");
140 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
141 my $urls = $r->{'fmt_url_map'};
143 $self->debug("Video has fmt_url_map: %s", $urls);
145 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
146 %urls = split(/[\|,]/, $urls);
147 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
149 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
150 my $thash = $r->{'t'};
152 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
153 my $fmt = $r->{'fmt_map'};
156 $self->debug('Video has fmt_map');
157 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
158 @fmt = split(/,/, $fmt);
161 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
166 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
169 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
172 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
175 $self->error('Neither fmt_url_map nor t found in video information hash');
178 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
180 $self->debug("Video has fmt_url_map: %s", $urls);
182 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
183 %urls = split(/[\|,]/, $urls);
184 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
188 foreach (keys(%urls)) {
190 $self->debug('Found flv,h264,large: %s', $urls{$_});
192 $self->debug('Found flv,h264: %s', $urls{$_});
194 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
196 $self->debug('Found mp4,h264,4k: %s', $urls{$_});
198 $self->debug('Found mp4,h264,1080p: %s', $urls{$_});
200 $self->debug('Found mp4,h264: %s', $urls{$_});
202 $self->debug('Found flv,flv: %s', $urls{$_});
204 $self->error('Unknown tag %s: %s', $_, $urls{$_});
208 foreach (@{$preflist}) {
209 if (exists($urls{$_})) {
210 $self->debug("Selected URL with quality level %s", $_);
211 $metadata->{'DLURL'} = $urls{$_};
216 $self->debug('URL found: %s', $metadata->{'DLURL'});
219 } elsif ('div' eq $tag->[0]) {
220 if (exists($tag->[1]->{'class'}) and ('yt-alert-content' eq $tag->[1]->{'class'})) {
221 $self->error("Could not get video data for youtube %s: %s",
222 $metadata->{'ID'}, $p->get_trimmed_text());
228 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
229 $self->error('Could not determine download URL');
238 my $videourl = shift;
240 my $user = $self->_getval('USERNAME');
241 my $pass = $self->_getval('PASSWORD');
253 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
258 sub get_all_cookies {
263 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
268 if (($user eq '') or ($pass eq '')) {
269 $self->error('No username or password defined for YouTube');
273 $self->debug('Logging in');
274 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
275 $c = $r->decoded_content();
276 $p = HTML::TokeParser->new(\$c);
277 while (my $tag = $p->get_tag('input')) {
278 if ($tag->[1]{name} eq 'GALX') {
279 $token = $tag->[1]{value};
283 $self->debug("GALX = .$token");
284 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
285 $c = $r -> decoded_content();
286 $p = HTML::TokeParser->new(\$c);
287 while (my $tag = $p->get_tag('script')) {
288 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
290 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
294 $r = $ua->get($token);
295 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
296 $self->error('Could not log into YouTube');
300 $self->debug("Got a cookie");
302 $r = $ua->get($videourl);
303 if ($r->base->as_string() =~ m,/verify_age,) {
304 $self->debug("Looking for session token...");
305 $c = $r->decoded_content();
306 $p = HTML::TokeParser->new(\$c);
307 while (my $tag = $p->get_tag('script')) {
308 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
314 unless(defined($token)) {
315 $self->error("Could not find session token");
319 $self->debug('Authenticating session...');
320 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
323 # Apparently there is no longer a specific "is_adult" cookie
324 # or, by the looks of it, anything similar
326 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
327 # $self->error('Could not authenticate session');
331 my $cookie = get_all_cookies($ua->cookie_jar);
332 return ($ua->get($videourl), $cookie);