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)/v/([-a-zA-Z0-9_]+))',
31 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
32 '(http://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
33 $self->{'_PARAMS'} = {
34 'QUALITY' => ['normal', 'Quality of the video to download.', {
35 'normal' => 'standard resolution flash video',
36 'high' => 'higher resolution flash video',
37 'h264' => 'high resolution MPEG4 video',
38 'hd' => 'HD720 resolution'}],
39 'USERNAME' => ['', 'Username to use for YouTube login'],
40 'PASSWORD' => ['', 'Password to use for YouTube login']};
43 $self->_prepare_parameters();
57 my $jar = HTTP::Cookies->new;
58 my $ua = LWP::UserAgent->new('agent' => 'Mozilla/5.0');
61 my $quality = $self->_getval('QUALITY');
63 'hd' => [37, 22, 35, 18, 34, 6, 5],
64 'h264' => [18, 34, 37, 22, 35, 6, 5],
65 'high' => [34, 35, 18, 37, 22, 6, 5],
66 'normal' => [6, 5, 34, 35, 18, 22, 37]);
73 $metadata->{'URL'} = $url;
74 $metadata->{'ID'} = $2;
75 $metadata->{'TYPE'} = 'video';
76 $metadata->{'SOURCE'} = $self->{'NAME'};
77 $metadata->{'TITLE'} = undef;
78 $metadata->{'DLURL'} = undef;
80 $self->debug("Matched id %s from pattern %s", $2, $pattern);
82 $preflist = $preflist{$quality};
83 $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
85 $videourl = sprintf('http://www.youtube.com/watch?v=%s', $2);
87 unless(defined($r = $ua->get($videourl))) {
88 $self->error('Could not download %s', $url);
92 if ($r->base->as_string() =~ m,/verify_age,) {
93 $self->debug('Video requires age verification');
94 $ua->cookie_jar($jar);
95 $r = $self->__login($videourl, $ua);
97 $self->error('Could not log into YouTube');
101 $content = $r->content();
103 $p = HTML::TokeParser->new(\$content);
105 SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
106 if ('meta' eq $tag->[0]) {
107 if ('title' eq $tag->[1]->{'name'}) {
108 $metadata->{'TITLE'} = $tag->[1]->{'content'};
109 # Convert HTML entities in the title. This is a bit convoluted.
110 $metadata->{'TITLE'} = encode("utf8",
112 decode("utf8", $metadata->{'TITLE'})));
114 $self->debug('Title found: %s', $metadata->{'TITLE'});
116 } elsif ('script' eq $tag->[0]) {
118 $self->debug("Found script: %s", $e);
119 if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
123 $self->debug("Found SWF_ARGS: %s", $args);
124 $jsp = videosite::JSArrayParser->new();
125 $self->debug("Using %s to parse", ref($jsp));
126 $r = $jsp->parse($args);
128 unless(defined($r)) {
129 $self->error("Found information hash, but could not parse");
133 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
134 my $urls = $r->{'fmt_url_map'};
136 $self->debug("Video has fmt_url_map: %s", $urls);
138 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
139 %urls = split(/[\|,]/, $urls);
140 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
141 my $thash = $r->{'t'};
143 if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
144 my $fmt = $r->{'fmt_map'};
147 $self->debug('Video has fmt_map');
148 $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
149 @fmt = split(/,/, $fmt);
152 $urls{$_[0]} = sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s',
158 $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
163 $self->error('Neither fmt_url_map nor t found in video information hash');
166 $self->debug("Found quality levels [%s]", join(", ", keys(%urls)));
168 foreach (keys(%urls)) {
170 $self->debug('Found flv,h264,large: %s', $urls{$_});
172 $self->debug('Found flv,h264: %s', $urls{$_});
174 $self->debug('Found mp4,h264,720p: %s', $urls{$_});
176 $self->debug('Found mp4,h264,1080p: %s', $urls{$_});
178 $self->debug('Found mp4,h264: %s', $urls{$_});
180 $self->debug('Found flv,flv: %s', $urls{$_});
182 $self->error('Unknown tag %s: %s', $_, $urls{$_});
186 foreach (@{$preflist}) {
187 if (exists($urls{$_})) {
188 $self->debug("Selected URL with quality level %s", $_);
189 $metadata->{'DLURL'} = $urls{$_};
194 $self->debug('URL found: %s', $metadata->{'DLURL'});
197 } elsif ('div' eq $tag->[0]) {
198 if (exists($tag->[1]->{'class'}) and ('yt-alert-content' eq $tag->[1]->{'class'})) {
199 $self->error("Could not get video data for youtube %s: %s",
200 $metadata->{'ID'}, $p->get_trimmed_text());
206 unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
207 $self->error('Could not determine download URL');
216 my $videourl = shift;
218 my $user = $self->_getval('USERNAME');
219 my $pass = $self->_getval('PASSWORD');
231 $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
236 if (($user eq '') or ($pass eq '')) {
237 $self->error('No username or password defined for YouTube');
241 $self->debug('Logging in');
242 $r = $ua->post('http://www.youtube.com/signup', { 'next' => '/', 'current_form' => 'login', 'action_login' => '1', 'username' => $user, 'password' => $pass });
244 unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
245 $self->error('Could not log into YouTube');
249 $self->debug("Got a cookie");
251 $r = $ua->get($videourl);
252 if ($r->base->as_string() =~ m,/verify_age,) {
253 $self->debug("Looking for session token...");
254 $c = $r->decoded_content();
255 $p = HTML::TokeParser->new(\$c);
256 while (my $tag = $p->get_tag('script')) {
257 if ($p->get_text() =~ /gXSRF_token = '(.+)'/) {
263 unless(defined($token)) {
264 $self->error("Could not find session token");
268 $self->debug('Authenticating session...');
269 $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
272 unless(check_cookie($ua->cookie_jar, 'is_adult')) {
273 $self->error('Could not authenticate session');
277 return $ua->get($videourl);