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;
81 $self->debug("Matched id %s from pattern %s", $2, $pattern);
83 $preflist = $preflist{$quality};
84 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
86 $videourl = sprintf('http://www.youtube.com/watch?v=%s', $2);
88 unless(defined($r = $ua->get($videourl))) {
89 $self->error('Could not download %s', $url);
93 if ($r->base->as_string() =~ m,/verify_age,) {
94 $self->debug('Video requires age verification');
95 $ua->cookie_jar($jar);
96 $r = $self->__login($videourl, $ua);
98 $self->error('Could not log into YouTube');
102 $content = $r->content();
104 $p = HTML::TokeParser->new(\$content);
106 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
107 if ('meta' eq $tag->[0]) {
108 if ('title' eq $tag->[1]->{'name'}) {
109 $metadata->{'TITLE'} = $tag->[1]->{'content'};
110 # Convert HTML entities in the title. This is a bit convoluted.
111 $metadata->{'TITLE'} = encode("utf8",
113 decode("utf8", $metadata->{'TITLE'})));
115 $self->debug('Title found: %s', $metadata->{'TITLE'});
117 } elsif ('script' eq $tag->[0]) {
119 $self->debug("Found script: %s", $e);
120 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
124 $self->debug("Found SWF_ARGS: %s", $args);
125 $jsp = videosite::JSArrayParser->new();
126 $self->debug("Using %s to parse", ref($jsp));
127 $r = $jsp->parse($args);
129 unless(defined($r)) {
130 $self->error("Found information hash, but could not parse");
134 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
135 my $urls = $r->{'fmt_url_map'};
137 $self->debug("Video has fmt_url_map: %s", $urls);
139 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
140 %urls = split(/[\|,]/, $urls);
141 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
142 my $thash = $r->{'t'};
144 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
145 my $fmt = $r->{'fmt_map'};
148 $self->debug('Video has fmt_map');
149 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
150 @fmt = split(/,/, $fmt);
153 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
159 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
164 $self->error('Neither fmt_url_map nor t found in video information hash');
167 $self->debug("Found quality levels [%s]", join(", ", keys(%urls)));
169 foreach (keys(%urls)) {
171 $self->debug('Found flv,h264,large: %s', $urls{$_});
173 $self->debug('Found flv,h264: %s', $urls{$_});
175 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
177 $self->debug('Found mp4,h264,1080p: %s', $urls{$_});
179 $self->debug('Found mp4,h264: %s', $urls{$_});
181 $self->debug('Found flv,flv: %s', $urls{$_});
183 $self->error('Unknown tag %s: %s', $_, $urls{$_});
187 foreach (@{$preflist}) {
188 if (exists($urls{$_})) {
189 $self->debug("Selected URL with quality level %s", $_);
190 $metadata->{'DLURL'} = $urls{$_};
195 $self->debug('URL found: %s', $metadata->{'DLURL'});
198 } elsif ('div' eq $tag->[0]) {
199 if (exists($tag->[1]->{'class'}) and ('yt-alert-content' eq $tag->[1]->{'class'})) {
200 $self->error("Could not get video data for youtube %s: %s",
201 $metadata->{'ID'}, $p->get_trimmed_text());
207 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
208 $self->error('Could not determine download URL');
217 my $videourl = shift;
219 my $user = $self->_getval('USERNAME');
220 my $pass = $self->_getval('PASSWORD');
232 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
237 if (($user eq '') or ($pass eq '')) {
238 $self->error('No username or password defined for YouTube');
242 $self->debug('Logging in');
243 $r = $ua->post('http://www.youtube.com/signup', { 'next' => '/', 'current_form' => 'login', 'action_login' => '1', 'username' => $user, 'password' => $pass });
245 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
246 $self->error('Could not log into YouTube');
250 $self->debug("Got a cookie");
252 $r = $ua->get($videourl);
253 if ($r->base->as_string() =~ m,/verify_age,) {
254 $self->debug("Looking for session token...");
255 $c = $r->decoded_content();
256 $p = HTML::TokeParser->new(\$c);
257 while (my $tag = $p->get_tag('script')) {
258 if ($p->get_text() =~ /gXSRF_token = '(.+)'/) {
264 unless(defined($token)) {
265 $self->error("Could not find session token");
269 $self->debug('Authenticating session...');
270 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
273 unless(check_cookie($ua->cookie_jar, 'is_adult')) {
274 $self->error('Could not authenticate session');
278 return $ua->get($videourl);