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