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