28f50078c99860fc10d86bd65b68636c0be4aed8
[videosite.git] / videosite / YouTubeGrabber.pm
1 # (c) 2007 by Ralf Ertzinger <ralf@camperquake.de>
2 # licensed under GNU GPL v2
3 #
4 # Grabber for youtube.com/de/...
5 #
6 # download strategy revised using
7 # http://www.kde-apps.org/content/show.php?content=41456
8
9 package videosite::YouTubeGrabber;
10
11 use videosite::GrabberBase;
12 @ISA = qw(videosite::GrabberBase);
13
14 use HTML::TokeParser;
15 use HTML::Entities qw(decode_entities);
16 use Encode;
17 use Data::Dumper;
18 use videosite::JSArrayParser;
19
20 use strict;
21
22 my %preflist = (
23     'insane' => [38, 37, 22, 35, 18, 34, 6, 5, 43],
24     'hd' => [37, 22, 35, 18, 34, 6, 5, 38, 43],
25     'h264' => [18, 34, 37, 22, 35, 6, 5, 38, 43],
26     'high' => [34, 35, 18, 37, 22, 6, 5, 38, 43],
27     'normal' => [6, 5, 34, 35, 18, 22, 37, 38, 43]);
28 my %videoformats = (
29     # Container/Video codec/Audio codec/Resolution
30     5 => 'FLV/Sorenson/MP3/240p',
31     6 => 'FLV/Sorenson/MP3/270p',
32     13 => '3GP/MPEG4-Visual/144p',  # 0.5MBit
33     17 => '3GP/MPEG4-Visual/144p',  # 2MBit
34     18 => 'MP4/H264/AAC/360p',      # isommp42, Baseline
35     22 => 'MP4/H264/AAC/720p',      # isommp42, High
36     34 => 'FLV/H264/AAC/360p',      # Main
37     35 => 'FLV/H264/AAC/480p',      # Main
38     36 => '3GP/MPEG4-Visual/240p',
39     37 => 'MP4/H264/AAC/1080p',     # High
40     38 => 'MP4/H264/AAC/3072p',     # High
41     43 => 'WebM/VP8/Vorbis/360p',   
42     44 => 'WebM/VP8/Vorbis/480p',
43     45 => 'WebM/VP8/Vorbis/720p',
44     46 => 'WebM/VP8/Vorbis/1080p/3D',  # effective 540p
45     82 => 'MP4/H264/AAC/360p/3D',      # isomavc1mp42
46     83 => 'MP4/H264/AAC/240p/3D',      # isomavc1mp42
47     84 => 'MP4/H264/AAC/720p/3D',      # isomavc1mp42
48     85 => 'MP4/H264/AAC/1080p/3D',     # isomavc1mp42, effective 540p
49     100 => 'WebM/VP8/Vorbis/360p/3D',
50     101 => 'WebM/VP8/Vorbis/480p/3D',
51     102 => 'WebM/VP8/Vorbis/720p/3D',
52     );
53
54 sub new {
55     my $class = shift;
56     my $self = $class->SUPER::new(
57         NAME => 'youtube',
58         _SELFTESTURL => 'http://www.youtube.com/watch?v=dMH0bHeiRNg',
59         _SELFTESTTITLE => 'Evolution of Dance - By Judson Laipply',
60         PATTERNS => ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?.*?v=([-a-zA-Z0-9_]+))',
61                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
62                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
63                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/embed/([-a-zA-Z0-9_]+))',
64                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
65                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
66                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
67                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
68                      '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'],
69         _PARAMS => {
70             QUALITY => ['normal', 'Quality of the video to download.', {
71                            normal => 'standard resolution flash video',
72                            high => 'higher resolution flash video',
73                            h264 => 'high resolution MPEG4 video',
74                            hd => 'HD720 resolution'}],
75             USERNAME => ['', 'Username to use for YouTube login'],
76             PASSWORD => ['', 'Password to use for YouTube login'],
77             HTTPS => [1, 'Whether to use HTTPS (if available) to connect to YouTube']
78         },
79         @_,
80     );
81
82     return bless($self, $class);
83 }
84
85 sub _parse {
86     my $self = shift;
87     my $url = shift;
88     my $pattern = shift;
89     my $id;
90     my $res;
91
92     $url =~ m|$pattern|;
93     $url = $1;
94     $id = $2;
95
96     $self->debug("Matched id %s from pattern %s", $id, $pattern);
97
98     $res = $self->_parse_by_video_info($url, $id);
99     if (defined($res) && ref($res)) {
100         return $res;
101     } else {
102         $res = $self->_parse_by_scrape($url, $id);
103     }
104
105     return $res;
106 }
107
108 sub _parse_by_video_info {
109     my $self = shift;
110     my $url = shift;
111     my $id = shift;
112     my $quality = $self->_getval('QUALITY');
113     my $metadata;
114     my $videourl;
115     my $ua = $self->ua();
116     my $preflist;
117     my $r;
118     my $content;
119     my $urls;
120
121     $metadata->{'URL'} = $url;
122     $metadata->{'ID'} = $id;
123     $metadata->{'TYPE'} = 'video';
124     $metadata->{'SOURCE'} = $self->{'NAME'};
125     $metadata->{'TITLE'} = undef;
126     $metadata->{'DLURL'} = undef;
127
128     $preflist = $preflist{$quality};
129     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
130
131     $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
132             $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
133     $self->debug("Video info URL: %s", $videourl);
134
135     $r = $ua->get($videourl);
136     unless($r->is_success()) {
137         $self->debug('Could not download %s: %s', $videourl, $r->code());
138         return undef;
139     }
140
141     $content = $r->content();
142     $self->debug('Content from get_video_info: %s', $content);
143
144     # Decode content
145     $content = $self->decode_querystring($content);
146
147     if ($content->{'status'} ne 'ok') {
148         $self->debug("Non OK status code found: %s", $content->{'status'});
149         return undef;
150     }
151
152     if (exists($content->{'fmt_url_map'})) {
153         # Decode fmt_url_map
154         $urls = $self->decode_hexurl($content->{'fmt_url_map'});
155         $urls = { split /[\|,]/, $urls };
156     } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
157         $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
158     } else {
159         $self->debug("No URL data found");
160         return undef;
161     }
162
163     unless(exists($content->{'title'})) {
164         $self->debug("No title found");
165         return undef;
166     }
167
168     $self->__pick_url($urls, $preflist, $metadata);
169
170     $metadata->{'TITLE'} = $content->{'title'};
171     $metadata->{'TITLE'} =~ s/\+/ /g;
172     $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
173     $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
174
175     $self->debug('Title found: %s', $metadata->{'TITLE'});
176
177     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
178         $self->error('Could not determine download URL');
179         return undef;
180     }
181
182     return $metadata;
183 }
184
185 sub _parse_by_scrape {
186     my $self = shift;
187     my $url = shift;
188     my $id = shift;
189     my $content;
190     my $metadata = {};
191     my $p;
192     my $e;
193     my $tag;
194     my $ua = $self->ua();
195     my $r;
196     my $videourl;
197     my $quality = $self->_getval('QUALITY');
198     my $preflist;
199     my $jsp;
200
201     $metadata->{'URL'} = $url;
202     $metadata->{'ID'} = $id;
203     $metadata->{'TYPE'} = 'video';
204     $metadata->{'SOURCE'} = $self->{'NAME'};
205     $metadata->{'TITLE'} = undef;
206     $metadata->{'DLURL'} = undef;
207
208
209     $preflist = $preflist{$quality};
210     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
211
212     $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
213
214     unless(defined($r = $ua->get($videourl))) {
215         $self->error('Could not download %s', $url);
216         return undef;
217     }
218
219     if ($r->base->as_string() =~ m,/verify_age,) {
220         $self->debug('Video requires age verification');
221         my @logindata = $self->__login($videourl, $ua);
222         $r = $logindata[0];
223         unless(defined($r)) {
224             $self->error('Could not log into YouTube');
225             return undef;
226         }
227     }
228     $content = $r->content();
229
230     $p = HTML::TokeParser->new(\$content);
231
232     SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
233         if ('meta' eq $tag->[0]) {
234             if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
235                 $metadata->{'TITLE'} = $tag->[1]->{'content'};
236                 # Convert HTML entities in the title. This is a bit convoluted.
237                 $metadata->{'TITLE'} = decode_entities(
238                                            decode("utf8", $metadata->{'TITLE'}));
239                     
240                 $self->debug('Title found: %s', $metadata->{'TITLE'});
241             }
242         } elsif ('script' eq $tag->[0]) {
243             my %urls;
244
245             $e = $p->get_text();
246             $self->debug("Found script: %s", $e);
247
248              if ($e =~ m|ytplayer\.config\s*=\s*(.+);$|) {
249                 my $args = $1;
250                 $self->debug("Found PLAYER_CONFIG: %s", $args);
251
252                 $jsp = videosite::JSArrayParser->new();
253                 $self->debug("Using %s to parse", ref($jsp));
254                 $r = $jsp->parse($args);
255
256                 unless(defined($r)) {
257                     $self->error("Found information hash, but could not parse");
258                     return undef;
259                 }
260
261                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
262                     $self->error("Video URL seems to point to a live stream, cannot save this");
263                     return undef;
264                 }
265
266                 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
267                     my $urls = $r->{'args'}->{'fmt_url_map'};
268
269                     $self->debug("Video has fmt_url_map: %s", $urls);
270
271                     %urls = split(/[\|,]/, $urls);
272                     foreach (keys(%urls)) {
273                         $urls{$_} = $self->decode_hexurl($urls{$_});
274                     }
275                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
276                 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
277                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
278
279                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
280                 } else {
281                     $self->error('fmt_url_map not found in PLAYER_CONFIG');
282                     return undef;
283                 }
284             } elsif ($e =~ m|yt\.playerConfig\s*=\s*(.+);\n|) {
285                 my $args = $1;
286                 $self->debug("Found yt.playerConfig: %s", $args);
287
288                 $jsp = videosite::JSArrayParser->new();
289                 $self->debug("Using %s to parse", ref($jsp));
290                 $r = $jsp->parse($args);
291
292                 unless(defined($r)) {
293                     $self->error("Found information hash, but could not parse");
294                     return undef;
295                 }
296
297                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
298                     $self->error("Video URL seems to point to a live stream, cannot save this");
299                     return undef;
300                 }
301
302                 if (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
303                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
304
305                     $self->debug("Pagetype: 2012 (yt.playerConfig), url_encoded_fmt_stream_map");
306                 } else {
307                     $self->error('url_map not found in yt.playerConfig');
308                     return undef;
309                 }
310             }
311
312
313             if (%urls) {
314                 $self->__pick_url(\%urls, $preflist, $metadata);
315                 last SWF_ARGS;
316             }
317         } elsif ('div' eq $tag->[0]) {
318             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
319                 # Search forward to the next <div>
320                 $tag = $p->get_tag('div');
321                 $self->error("Could not get video data for youtube %s: %s",
322                         $metadata->{'ID'}, $p->get_trimmed_text());
323                 return undef;
324             }
325         }
326     }
327
328     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
329         $self->error('Could not determine download URL');
330         return undef;
331     }
332
333     return $metadata;
334 }
335
336 sub __login {
337     my $self = shift;
338     my $videourl = shift;
339     my $ua = shift;
340     my $user = $self->_getval('USERNAME');
341     my $pass = $self->_getval('PASSWORD');
342     my $r;
343     my $p;
344     my $c;
345     my $token;
346
347     sub check_cookie {
348
349         my $jar = shift;
350         my $key = shift;
351         my $found = undef;
352
353         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
354
355         return $found;
356     }
357
358     sub get_all_cookies {
359
360         my $jar = shift;
361         my $key = shift;
362         my $val = "";
363         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
364
365         return $val;
366     }
367
368     if (($user eq '') or ($pass eq '')) {
369         $self->error('No username or password defined for YouTube');
370         return undef;
371     }
372
373     $self->debug('Logging in');
374     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
375     unless($r->is_success()) {
376         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
377         return undef;
378     }
379     $c = $r->decoded_content();
380     $p = HTML::TokeParser->new(\$c);
381     while (my $tag = $p->get_tag('input')) {
382         $self->debug("%s", Dumper($tag));
383         if ($tag->[1]{name} eq 'GALX') {
384             $token = $tag->[1]{value};
385             last;
386         }
387     }
388     $self->debug("GALX = %s", $token);
389     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
390     unless($r->is_success()) {
391         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
392         return undef;
393     }
394     $c = $r -> decoded_content();
395     $p = HTML::TokeParser->new(\$c);
396     while (my $tag = $p->get_tag('script')) {
397         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
398             $token = $1;
399             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
400             last;
401         }
402     }
403     $r = $ua->get($token);
404     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
405         $self->error('Could not log into YouTube');
406         return undef;
407     }
408
409     $self->debug("Got a cookie");
410
411     $r = $ua->get($videourl);
412     if ($r->base->as_string() =~ m,/verify_age,) {
413         $self->debug("Looking for session token...");
414         $c = $r->decoded_content();
415         $p = HTML::TokeParser->new(\$c);
416         while (my $tag = $p->get_tag('script')) {
417             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
418                 $token = $1;
419                 last;
420             }
421         }
422
423         unless(defined($token)) {
424             $self->error("Could not find session token");
425             return undef;
426         }
427
428         $self->debug('Authenticating session...');
429         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
430     }
431
432 # Apparently there is no longer a specific "is_adult" cookie
433 # or, by the looks of it, anything similar
434 #
435 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
436 #        $self->error('Could not authenticate session');
437 #        return undef;
438 #    }
439
440     my $cookie = get_all_cookies($ua->cookie_jar);
441     return ($ua->get($videourl), $cookie);
442 }
443
444 # Take an encoded url_encoded_fmt_stream_map and return a hash
445 # matching video IDs to download URLs
446 sub _decode_url_encoded_fmt_stream_map {
447     my $self = shift;
448     my $data = shift;
449     my $dataencoded = shift;
450     my @data;
451     my $h = {};
452
453     $data = $self->decode_hexurl($data) if $dataencoded;
454     # This will
455     # - Split the decoded string into segments (along ,)
456     # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
457     # - URL-decode each key and value _again_
458     #
459     # @data will be an array of hash references
460     
461     @data = map { { map { $self->decode_hexurl($_) } split /[&=]/  } } split /,/, $data;
462     $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
463
464     # From each array entry, pick the itag and the url values and return that
465     # as a hash reference
466     
467
468     foreach (@data) {
469         if (exists($_->{'sig'})) {
470             $h->{$_->{'itag'}} = sprintf('%s&signature=%s', $_->{'url'}, $_->{'sig'});
471         } else {
472             $h->{$_->{'itag'}} =  $_->{'url'};
473         }
474     }
475
476     return $h;
477 }
478
479
480
481 sub __pick_url {
482     my $self = shift;
483     my $urls = shift;
484     my $preflist = shift;
485     my $metadata = shift;
486
487     foreach (keys(%{$urls})) {
488         if (exists($videoformats{$_})) {
489             $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
490         } else {
491             $self->error('Unknown format %s: %s', $_, $urls->{$_});
492         }
493     }
494
495     foreach (@{$preflist}) {
496         if (exists($urls->{$_})) {
497             $self->debug("Selected URL with quality level %s", $_);
498             $metadata->{'DLURL'} = $urls->{$_};
499             if (exists($videoformats{$_})) {
500                 $metadata->{'FORMAT'} = $videoformats{$_};
501             } else {
502                 $metadata->{'FORMAT'} = 'unknown';
503             }
504             last;
505         }
506     }
507
508     $self->debug('URL found: %s', $metadata->{'DLURL'});
509 }
510
511 1;
512