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;
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 $r = $self->__login($videourl, $ua);
99 $self->error('Could not log into YouTube');
103 $content = $r->content();
105 $p = HTML::TokeParser->new(\$content);
107 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
108 if ('meta' eq $tag->[0]) {
109 if ('title' eq $tag->[1]->{'name'}) {
110 $metadata->{'TITLE'} = $tag->[1]->{'content'};
111 # Convert HTML entities in the title. This is a bit convoluted.
112 $metadata->{'TITLE'} = encode("utf8",
114 decode("utf8", $metadata->{'TITLE'})));
116 $self->debug('Title found: %s', $metadata->{'TITLE'});
118 } elsif ('script' eq $tag->[0]) {
122 $self->debug("Found script: %s", $e);
124 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
127 $self->debug("Found SWF_ARGS: %s", $args);
128 $jsp = videosite::JSArrayParser->new();
129 $self->debug("Using %s to parse", ref($jsp));
130 $r = $jsp->parse($args);
132 unless(defined($r)) {
133 $self->error("Found information hash, but could not parse");
137 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
138 my $urls = $r->{'fmt_url_map'};
140 $self->debug("Video has fmt_url_map: %s", $urls);
142 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
143 %urls = split(/[\|,]/, $urls);
144 $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
146 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
147 my $thash = $r->{'t'};
149 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
150 my $fmt = $r->{'fmt_map'};
153 $self->debug('Video has fmt_map');
154 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
155 @fmt = split(/,/, $fmt);
158 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
163 $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
166 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
169 $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
172 $self->error('Neither fmt_url_map nor t found in video information hash');
175 } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
177 $self->debug("Video has fmt_url_map: %s", $urls);
179 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
180 %urls = split(/[\|,]/, $urls);
181 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
185 foreach (keys(%urls)) {
187 $self->debug('Found flv,h264,large: %s', $urls{$_});
189 $self->debug('Found flv,h264: %s', $urls{$_});
191 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
193 $self->debug('Found mp4,h264,4k: %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 if (($user eq '') or ($pass eq '')) {
256 $self->error('No username or password defined for YouTube');
260 $self->debug('Logging in');
261 $r = $ua->post('http://www.youtube.com/signup', { 'next' => '/', 'current_form' => 'login', 'action_login' => '1', 'username' => $user, 'password' => $pass });
263 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
264 $self->error('Could not log into YouTube');
268 $self->debug("Got a cookie");
270 $r = $ua->get($videourl);
271 if ($r->base->as_string() =~ m,/verify_age,) {
272 $self->debug("Looking for session token...");
273 $c = $r->decoded_content();
274 $p = HTML::TokeParser->new(\$c);
275 while (my $tag = $p->get_tag('script')) {
276 if ($p->get_text() =~ /gXSRF_token = '(.+)'/) {
282 unless(defined($token)) {
283 $self->error("Could not find session token");
287 $self->debug('Authenticating session...');
288 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
291 unless(check_cookie($ua->cookie_jar, 'is_adult')) {
292 $self->error('Could not authenticate session');
296 return $ua->get($videourl);