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 'hd' => [37, 22, 35, 18, 34, 6, 5],
65 'h264' => [18, 34, 37, 22, 35, 6, 5],
66 'high' => [34, 35, 18, 37, 22, 6, 5],
67 'normal' => [6, 5, 34, 35, 18, 22, 37]);
74 $metadata->{'URL'} = $url;
75 $metadata->{'ID'} = $2;
76 $metadata->{'TYPE'} = 'video';
77 $metadata->{'SOURCE'} = $self->{'NAME'};
78 $metadata->{'TITLE'} = undef;
79 $metadata->{'DLURL'} = undef;
80 $metadata->{'COOKIE'} = undef;
82 $self->debug("Matched id %s from pattern %s", $2, $pattern);
84 $preflist = $preflist{$quality};
85 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
87 $videourl = sprintf('http://www.youtube.com/watch?v=%s', $2);
89 unless(defined($r = $ua->get($videourl))) {
90 $self->error('Could not download %s', $url);
94 if ($r->base->as_string() =~ m,/verify_age,) {
95 $self->debug('Video requires age verification');
96 $ua->cookie_jar($jar);
97 my @logindata = $self->__login($videourl, $ua);
99 $metadata->{'COOKIE'} = $logindata[1];
100 unless(defined($r)) {
101 $self->error('Could not log into YouTube');
105 $content = $r->content();
107 $p = HTML::TokeParser->new(\$content);
109 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
110 if ('meta' eq $tag->[0]) {
111 if ('title' eq $tag->[1]->{'name'}) {
112 $metadata->{'TITLE'} = $tag->[1]->{'content'};
113 # Convert HTML entities in the title. This is a bit convoluted.
114 $metadata->{'TITLE'} = encode("utf8",
116 decode("utf8", $metadata->{'TITLE'})));
118 $self->debug('Title found: %s', $metadata->{'TITLE'});
120 } elsif ('script' eq $tag->[0]) {
124 $self->debug("Found script: %s", $e);
126 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
129 $self->debug("Found SWF_ARGS: %s", $args);
130 $jsp = videosite::JSArrayParser->new();
131 $self->debug("Using %s to parse", ref($jsp));
132 $r = $jsp->parse($args);
134 unless(defined($r)) {
135 $self->error("Found information hash, but could not parse");
139 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
140 my $urls = $r->{'fmt_url_map'};
142 $self->debug("Video has fmt_url_map: %s", $urls);
144 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
145 %urls = split(/[\|,]/, $urls);
146 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
148 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
149 my $thash = $r->{'t'};
151 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
152 my $fmt = $r->{'fmt_map'};
155 $self->debug('Video has fmt_map');
156 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
157 @fmt = split(/,/, $fmt);
160 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
165 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
168 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
171 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
174 $self->error('Neither fmt_url_map nor t found in video information hash');
177 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
179 $self->debug("Video has fmt_url_map: %s", $urls);
181 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
182 %urls = split(/[\|,]/, $urls);
183 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
187 foreach (keys(%urls)) {
189 $self->debug('Found flv,h264,large: %s', $urls{$_});
191 $self->debug('Found flv,h264: %s', $urls{$_});
193 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
195 $self->debug('Found mp4,h264,1080p: %s', $urls{$_});
197 $self->debug('Found mp4,h264: %s', $urls{$_});
199 $self->debug('Found flv,flv: %s', $urls{$_});
201 $self->error('Unknown tag %s: %s', $_, $urls{$_});
205 foreach (@{$preflist}) {
206 if (exists($urls{$_})) {
207 $self->debug("Selected URL with quality level %s", $_);
208 $metadata->{'DLURL'} = $urls{$_};
213 $self->debug('URL found: %s', $metadata->{'DLURL'});
216 } elsif ('div' eq $tag->[0]) {
217 if (exists($tag->[1]->{'class'}) and ('yt-alert-content' eq $tag->[1]->{'class'})) {
218 $self->error("Could not get video data for youtube %s: %s",
219 $metadata->{'ID'}, $p->get_trimmed_text());
225 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
226 $self->error('Could not determine download URL');
235 my $videourl = shift;
237 my $user = $self->_getval('USERNAME');
238 my $pass = $self->_getval('PASSWORD');
250 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
255 sub get_all_cookies {
260 $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
265 if (($user eq '') or ($pass eq '')) {
266 $self->error('No username or password defined for YouTube');
270 $self->debug('Logging in');
271 $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
272 $c = $r->decoded_content();
273 $p = HTML::TokeParser->new(\$c);
274 while (my $tag = $p->get_tag('input')) {
275 if ($tag->[1]{name} eq 'GALX') {
276 $token = $tag->[1]{value};
280 $self->debug("GALX = .$token");
281 $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
282 $c = $r -> decoded_content();
283 $p = HTML::TokeParser->new(\$c);
284 while (my $tag = $p->get_tag('script')) {
285 if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
287 $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
291 $r = $ua->get($token);
292 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
293 $self->error('Could not log into YouTube');
297 $self->debug("Got a cookie");
299 $r = $ua->get($videourl);
300 if ($r->base->as_string() =~ m,/verify_age,) {
301 $self->debug("Looking for session token...");
302 $c = $r->decoded_content();
303 $p = HTML::TokeParser->new(\$c);
304 while (my $tag = $p->get_tag('script')) {
305 if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
311 unless(defined($token)) {
312 $self->error("Could not find session token");
316 $self->debug('Authenticating session...');
317 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
320 # Apparently there is no longer a specific "is_adult" cookie
321 # or, by the looks of it, anything similar
323 # unless(check_cookie($ua->cookie_jar, 'is_adult')) {
324 # $self->error('Could not authenticate session');
328 my $cookie = get_all_cookies($ua->cookie_jar);
329 return ($ua->get($videourl), $cookie);