Youtube: Allow short circuiting _parse_by_scrape if the video is non-saveable anyway
[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)) {
100          if (ref($res)) {
101             return $res;
102          } else {
103              $self->debug("_parse_by_video_info failed with status noretry");
104              return undef;
105          }
106     } else {
107         $self->debug("_parse_by_video_info failed with status retry");
108         $res = $self->_parse_by_scrape($url, $id);
109     }
110
111     return $res;
112 }
113
114 #
115 # Try to get video information by using the API call.
116 #
117 # Returns hashref on success
118 # Returns undef on retryable error (try to scrape the website)
119 # Returns 0 on non-retryable error 
120 #
121 sub _parse_by_video_info {
122     my $self = shift;
123     my $url = shift;
124     my $id = shift;
125     my $quality = $self->_getval('QUALITY');
126     my $metadata;
127     my $videourl;
128     my $ua = $self->ua();
129     my $preflist;
130     my $r;
131     my $content;
132     my $urls;
133
134     $metadata->{'URL'} = $url;
135     $metadata->{'ID'} = $id;
136     $metadata->{'TYPE'} = 'video';
137     $metadata->{'SOURCE'} = $self->{'NAME'};
138     $metadata->{'TITLE'} = undef;
139     $metadata->{'DLURL'} = undef;
140
141     $preflist = $preflist{$quality};
142     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
143
144     $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
145             $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
146     $self->debug("Video info URL: %s", $videourl);
147
148     $r = $ua->get($videourl);
149     unless($r->is_success()) {
150         $self->debug('Could not download %s: %s', $videourl, $r->code());
151         return undef;
152     }
153
154     $content = $r->content();
155     $self->debug('Content from get_video_info: %s', $content);
156
157     # Decode content
158     $content = $self->decode_querystring($content);
159
160     $self->debug("Decoded get_video_info: %s", Dumper($content));
161
162     if ($content->{'status'} ne 'ok') {
163         $self->debug("Non OK status code found: %s", $content->{'status'});
164         return undef;
165     }
166
167     # Check if this is live content
168     if (exists($content->{ps}) and ($content->{ps} eq 'live')) {
169         $self->error("Video URL seems to point to a live stream, cannot save this");
170         return 0;
171     }
172
173     if (exists($content->{'fmt_url_map'})) {
174         # Decode fmt_url_map
175         $urls = $self->decode_hexurl($content->{'fmt_url_map'});
176         $urls = { split /[\|,]/, $urls };
177     } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
178         $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
179     } else {
180         $self->debug("No URL data found");
181         return undef;
182     }
183
184     unless(exists($content->{'title'})) {
185         $self->debug("No title found");
186         return undef;
187     }
188
189     $self->__pick_url($urls, $preflist, $metadata);
190
191     $metadata->{'TITLE'} = $content->{'title'};
192     $metadata->{'TITLE'} =~ s/\+/ /g;
193     $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
194     $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
195
196     $self->debug('Title found: %s', $metadata->{'TITLE'});
197
198     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
199         $self->error('Could not determine download URL');
200         return undef;
201     }
202
203     return $metadata;
204 }
205
206 sub _parse_by_scrape {
207     my $self = shift;
208     my $url = shift;
209     my $id = shift;
210     my $content;
211     my $metadata = {};
212     my $p;
213     my $e;
214     my $tag;
215     my $ua = $self->ua();
216     my $r;
217     my $videourl;
218     my $quality = $self->_getval('QUALITY');
219     my $preflist;
220     my $jsp;
221
222     $metadata->{'URL'} = $url;
223     $metadata->{'ID'} = $id;
224     $metadata->{'TYPE'} = 'video';
225     $metadata->{'SOURCE'} = $self->{'NAME'};
226     $metadata->{'TITLE'} = undef;
227     $metadata->{'DLURL'} = undef;
228
229
230     $preflist = $preflist{$quality};
231     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
232
233     $videourl = sprintf('%s://www.youtube.com/watch?v=%s', $self->_getval('HTTPS')?'https':'http', $id);
234
235     unless(defined($r = $ua->get($videourl))) {
236         $self->error('Could not download %s', $url);
237         return undef;
238     }
239
240     if ($r->base->as_string() =~ m,/verify_age,) {
241         $self->debug('Video requires age verification');
242         my @logindata = $self->__login($videourl, $ua);
243         $r = $logindata[0];
244         unless(defined($r)) {
245             $self->error('Could not log into YouTube');
246             return undef;
247         }
248     }
249     $content = $r->content();
250
251     $p = HTML::TokeParser->new(\$content);
252
253     SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
254         if ('meta' eq $tag->[0]) {
255             if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
256                 $metadata->{'TITLE'} = $tag->[1]->{'content'};
257                 # Convert HTML entities in the title. This is a bit convoluted.
258                 $metadata->{'TITLE'} = decode_entities(
259                                            decode("utf8", $metadata->{'TITLE'}));
260                     
261                 $self->debug('Title found: %s', $metadata->{'TITLE'});
262             }
263         } elsif ('script' eq $tag->[0]) {
264             my %urls;
265
266             $e = $p->get_text();
267             $self->debug("Found script: %s", $e);
268
269              if ($e =~ m|ytplayer\.config\s*=\s*(.+);$|) {
270                 my $args = $1;
271                 $self->debug("Found PLAYER_CONFIG: %s", $args);
272
273                 $jsp = videosite::JSArrayParser->new();
274                 $self->debug("Using %s to parse", ref($jsp));
275                 $r = $jsp->parse($args);
276
277                 unless(defined($r)) {
278                     $self->error("Found information hash, but could not parse");
279                     return undef;
280                 }
281
282                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
283                     $self->error("Video URL seems to point to a live stream, cannot save this");
284                     return undef;
285                 }
286
287                 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
288                     my $urls = $r->{'args'}->{'fmt_url_map'};
289
290                     $self->debug("Video has fmt_url_map: %s", $urls);
291
292                     %urls = split(/[\|,]/, $urls);
293                     foreach (keys(%urls)) {
294                         $urls{$_} = $self->decode_hexurl($urls{$_});
295                     }
296                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
297                 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
298                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
299
300                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
301                 } else {
302                     $self->error('fmt_url_map not found in PLAYER_CONFIG');
303                     return undef;
304                 }
305             } elsif ($e =~ m|yt\.playerConfig\s*=\s*(.+);\n|) {
306                 my $args = $1;
307                 $self->debug("Found yt.playerConfig: %s", $args);
308
309                 $jsp = videosite::JSArrayParser->new();
310                 $self->debug("Using %s to parse", ref($jsp));
311                 $r = $jsp->parse($args);
312
313                 unless(defined($r)) {
314                     $self->error("Found information hash, but could not parse");
315                     return undef;
316                 }
317
318                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
319                     $self->error("Video URL seems to point to a live stream, cannot save this");
320                     return undef;
321                 }
322
323                 if (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
324                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
325
326                     $self->debug("Pagetype: 2012 (yt.playerConfig), url_encoded_fmt_stream_map");
327                 } else {
328                     $self->error('url_map not found in yt.playerConfig');
329                     return undef;
330                 }
331             }
332
333
334             if (%urls) {
335                 $self->__pick_url(\%urls, $preflist, $metadata);
336                 last SWF_ARGS;
337             }
338         } elsif ('div' eq $tag->[0]) {
339             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
340                 # Search forward to the next <div>
341                 $tag = $p->get_tag('div');
342                 $self->error("Could not get video data for youtube %s: %s",
343                         $metadata->{'ID'}, $p->get_trimmed_text());
344                 return undef;
345             }
346         }
347     }
348
349     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
350         $self->error('Could not determine download URL');
351         return undef;
352     }
353
354     return $metadata;
355 }
356
357 sub __login {
358     my $self = shift;
359     my $videourl = shift;
360     my $ua = shift;
361     my $user = $self->_getval('USERNAME');
362     my $pass = $self->_getval('PASSWORD');
363     my $r;
364     my $p;
365     my $c;
366     my $token;
367
368     sub check_cookie {
369
370         my $jar = shift;
371         my $key = shift;
372         my $found = undef;
373
374         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
375
376         return $found;
377     }
378
379     sub get_all_cookies {
380
381         my $jar = shift;
382         my $key = shift;
383         my $val = "";
384         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
385
386         return $val;
387     }
388
389     if (($user eq '') or ($pass eq '')) {
390         $self->error('No username or password defined for YouTube');
391         return undef;
392     }
393
394     $self->debug('Logging in');
395     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
396     unless($r->is_success()) {
397         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
398         return undef;
399     }
400     $c = $r->decoded_content();
401     $p = HTML::TokeParser->new(\$c);
402     while (my $tag = $p->get_tag('input')) {
403         $self->debug("%s", Dumper($tag));
404         if ($tag->[1]{name} eq 'GALX') {
405             $token = $tag->[1]{value};
406             last;
407         }
408     }
409     $self->debug("GALX = %s", $token);
410     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
411     unless($r->is_success()) {
412         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
413         return undef;
414     }
415     $c = $r -> decoded_content();
416     $p = HTML::TokeParser->new(\$c);
417     while (my $tag = $p->get_tag('script')) {
418         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
419             $token = $1;
420             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
421             last;
422         }
423     }
424     $r = $ua->get($token);
425     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
426         $self->error('Could not log into YouTube');
427         return undef;
428     }
429
430     $self->debug("Got a cookie");
431
432     $r = $ua->get($videourl);
433     if ($r->base->as_string() =~ m,/verify_age,) {
434         $self->debug("Looking for session token...");
435         $c = $r->decoded_content();
436         $p = HTML::TokeParser->new(\$c);
437         while (my $tag = $p->get_tag('script')) {
438             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
439                 $token = $1;
440                 last;
441             }
442         }
443
444         unless(defined($token)) {
445             $self->error("Could not find session token");
446             return undef;
447         }
448
449         $self->debug('Authenticating session...');
450         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
451     }
452
453 # Apparently there is no longer a specific "is_adult" cookie
454 # or, by the looks of it, anything similar
455 #
456 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
457 #        $self->error('Could not authenticate session');
458 #        return undef;
459 #    }
460
461     my $cookie = get_all_cookies($ua->cookie_jar);
462     return ($ua->get($videourl), $cookie);
463 }
464
465 # Take an encoded url_encoded_fmt_stream_map and return a hash
466 # matching video IDs to download URLs
467 sub _decode_url_encoded_fmt_stream_map {
468     my $self = shift;
469     my $data = shift;
470     my $dataencoded = shift;
471     my @data;
472     my $h = {};
473
474     $data = $self->decode_hexurl($data) if $dataencoded;
475     # This will
476     # - Split the decoded string into segments (along ,)
477     # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
478     # - URL-decode each key and value _again_
479     #
480     # @data will be an array of hash references
481     
482     @data = map { { map { $self->decode_hexurl($_) } split /[&=]/  } } split /,/, $data;
483     $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
484
485     # From each array entry, pick the itag and the url values and return that
486     # as a hash reference
487     
488
489     foreach (@data) {
490         if (exists($_->{'sig'})) {
491             $h->{$_->{'itag'}} = sprintf('%s&signature=%s', $_->{'url'}, $_->{'sig'});
492         } else {
493             $h->{$_->{'itag'}} =  $_->{'url'};
494         }
495     }
496
497     return $h;
498 }
499
500
501
502 sub __pick_url {
503     my $self = shift;
504     my $urls = shift;
505     my $preflist = shift;
506     my $metadata = shift;
507
508     foreach (keys(%{$urls})) {
509         if (exists($videoformats{$_})) {
510             $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
511         } else {
512             $self->error('Unknown format %s: %s', $_, $urls->{$_});
513         }
514     }
515
516     foreach (@{$preflist}) {
517         if (exists($urls->{$_})) {
518             $self->debug("Selected URL with quality level %s", $_);
519             $metadata->{'DLURL'} = $urls->{$_};
520             if (exists($videoformats{$_})) {
521                 $metadata->{'FORMAT'} = $videoformats{$_};
522             } else {
523                 $metadata->{'FORMAT'} = 'unknown';
524             }
525             last;
526         }
527     }
528
529     $self->debug('URL found: %s', $metadata->{'DLURL'});
530 }
531
532 1;
533