Merge branch 'master' of http://10.200.0.3/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     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
58     $self->{'NAME'} = 'youtube';
59     $self->{_SELFTESTURL} = 'http://www.youtube.com/watch?v=dMH0bHeiRNg';
60     $self->{_SELFTESTTITLE} = 'Evolution of Dance - By Judson Laipply';
61     $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?.*?v=([-a-zA-Z0-9_]+))',
62                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
63                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-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     $self->{'_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     bless($self, $class);
80     $self->_prepare_parameters();
81
82     return $self;
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|\x27SWF_ARGS\x27:\s+(.+),|) {
249 #                my $args = $1;
250 #
251 #                $self->debug("Found SWF_ARGS: %s", $args);
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->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
262 #                    my $urls =  $r->{'fmt_url_map'};
263 #
264 #                    $self->debug("Video has fmt_url_map: %s", $urls);
265 #
266 #                    $urls = $self->decode_hexurl($urls);
267 #                    %urls = split(/[\|,]/, $urls);
268 #                    $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
269 #
270 #                } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
271 #                    my $thash = $r->{'t'};
272 #
273 #                    if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
274 #                        my $fmt = $r->{'fmt_map'};
275 #                        my @fmt;
276 #
277 #                        $self->debug('Video has fmt_map');
278 #                        $fmt = $self->decode_hexurl($fmt);
279 #                        @fmt = split(/,/, $fmt);
280 #                        foreach (@fmt) {
281 #                            @_=split(/\//);
282 #                            $urls{$_[0]} =  sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s', 
283 #                                $metadata->{'ID'},
284 #                                $_[0],
285 #                                $thash);
286 #                        }
287 #                        $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
288 #
289 #                    } else {
290 #                        $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
291 #                            $metadata->{'ID'},
292 #                            $thash);
293 #                        $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
294 #                    }
295 #                } else {
296 #                    $self->error('Neither fmt_url_map nor t found in video information hash');
297 #                    return undef;
298 #                }
299 #            } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
300 #                my $urls = $1;
301 #                $self->debug("Video has fmt_url_map: %s", $urls);
302 #
303 #                $urls = $self->decode_hexurl($urls);
304 #                %urls = split(/[\|,]/, $urls);
305 #                $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
306 #            } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
307              if ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)(?:\}\);)?|) {
308                 my $args = $1;
309                 $self->debug("Found PLAYER_CONFIG: %s", $args);
310
311                 $jsp = videosite::JSArrayParser->new();
312                 $self->debug("Using %s to parse", ref($jsp));
313                 $r = $jsp->parse($args);
314
315                 unless(defined($r)) {
316                     $self->error("Found information hash, but could not parse");
317                     return undef;
318                 }
319
320                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
321                     $self->error("Video URL seems to point to a live stream, cannot save this");
322                     return undef;
323                 }
324
325                 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
326                     my $urls = $r->{'args'}->{'fmt_url_map'};
327
328                     $self->debug("Video has fmt_url_map: %s", $urls);
329
330                     %urls = split(/[\|,]/, $urls);
331                     foreach (keys(%urls)) {
332                         $urls{$_} = $self->decode_hexurl($urls{$_});
333                     }
334                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
335                 } elsif (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
336                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
337
338                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), url_encoded_fmt_stream_map");
339                 } else {
340                     $self->error('fmt_url_map not found in PLAYER_CONFIG');
341                     return undef;
342                 }
343             } elsif ($e =~ m|yt\.playerConfig\s*=\s*(.+);\n|) {
344                 my $args = $1;
345                 $self->debug("Found yt.playerConfig: %s", $args);
346
347                 $jsp = videosite::JSArrayParser->new();
348                 $self->debug("Using %s to parse", ref($jsp));
349                 $r = $jsp->parse($args);
350
351                 unless(defined($r)) {
352                     $self->error("Found information hash, but could not parse");
353                     return undef;
354                 }
355
356                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
357                     $self->error("Video URL seems to point to a live stream, cannot save this");
358                     return undef;
359                 }
360
361                 if (exists($r->{'args'}) and exists($r->{'args'}->{'url_encoded_fmt_stream_map'}) and ($r->{'args'}->{'url_encoded_fmt_stream_map'} ne '')) {
362                     %urls = %{$self->_decode_url_encoded_fmt_stream_map($r->{'args'}->{'url_encoded_fmt_stream_map'}, 0)};
363
364                     $self->debug("Pagetype: 2012 (yt.playerConfig), url_encoded_fmt_stream_map");
365                 } else {
366                     $self->error('url_map not found in yt.playerConfig');
367                     return undef;
368                 }
369             }
370
371
372             if (%urls) {
373                 $self->__pick_url(\%urls, $preflist, $metadata);
374                 last SWF_ARGS;
375             }
376         } elsif ('div' eq $tag->[0]) {
377             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
378                 # Search forward to the next <div>
379                 $tag = $p->get_tag('div');
380                 $self->error("Could not get video data for youtube %s: %s",
381                         $metadata->{'ID'}, $p->get_trimmed_text());
382                 return undef;
383             }
384         }
385     }
386
387     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
388         $self->error('Could not determine download URL');
389         return undef;
390     }
391
392     return $metadata;
393 }
394
395 sub __login {
396     my $self = shift;
397     my $videourl = shift;
398     my $ua = shift;
399     my $user = $self->_getval('USERNAME');
400     my $pass = $self->_getval('PASSWORD');
401     my $r;
402     my $p;
403     my $c;
404     my $token;
405
406     sub check_cookie {
407
408         my $jar = shift;
409         my $key = shift;
410         my $found = undef;
411
412         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
413
414         return $found;
415     }
416
417     sub get_all_cookies {
418
419         my $jar = shift;
420         my $key = shift;
421         my $val = "";
422         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
423
424         return $val;
425     }
426
427     if (($user eq '') or ($pass eq '')) {
428         $self->error('No username or password defined for YouTube');
429         return undef;
430     }
431
432     $self->debug('Logging in');
433     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
434     unless($r->is_success()) {
435         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
436         return undef;
437     }
438     $c = $r->decoded_content();
439     $p = HTML::TokeParser->new(\$c);
440     while (my $tag = $p->get_tag('input')) {
441         $self->debug("%s", Dumper($tag));
442         if ($tag->[1]{name} eq 'GALX') {
443             $token = $tag->[1]{value};
444             last;
445         }
446     }
447     $self->debug("GALX = %s", $token);
448     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
449     unless($r->is_success()) {
450         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
451         return undef;
452     }
453     $c = $r -> decoded_content();
454     $p = HTML::TokeParser->new(\$c);
455     while (my $tag = $p->get_tag('script')) {
456         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
457             $token = $1;
458             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
459             last;
460         }
461     }
462     $r = $ua->get($token);
463     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
464         $self->error('Could not log into YouTube');
465         return undef;
466     }
467
468     $self->debug("Got a cookie");
469
470     $r = $ua->get($videourl);
471     if ($r->base->as_string() =~ m,/verify_age,) {
472         $self->debug("Looking for session token...");
473         $c = $r->decoded_content();
474         $p = HTML::TokeParser->new(\$c);
475         while (my $tag = $p->get_tag('script')) {
476             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
477                 $token = $1;
478                 last;
479             }
480         }
481
482         unless(defined($token)) {
483             $self->error("Could not find session token");
484             return undef;
485         }
486
487         $self->debug('Authenticating session...');
488         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
489     }
490
491 # Apparently there is no longer a specific "is_adult" cookie
492 # or, by the looks of it, anything similar
493 #
494 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
495 #        $self->error('Could not authenticate session');
496 #        return undef;
497 #    }
498
499     my $cookie = get_all_cookies($ua->cookie_jar);
500     return ($ua->get($videourl), $cookie);
501 }
502
503 # Take an encoded url_encoded_fmt_stream_map and return a hash
504 # matching video IDs to download URLs
505 sub _decode_url_encoded_fmt_stream_map {
506     my $self = shift;
507     my $data = shift;
508     my $dataencoded = shift;
509     my @data;
510
511     $data = $self->decode_hexurl($data) if $dataencoded;
512     # This will
513     # - Split the decoded string into segments (along ,)
514     # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
515     # - URL-decode each key and value _again_
516     #
517     # @data will be an array of hash references
518     
519     @data = map { { map { $self->decode_hexurl($_) } split /[&=]/  } } split /,/, $data;
520     $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
521
522     # From each array entry, pick the itag and the url values and return that
523     # as a hash reference
524     
525     return { map { $_->{'itag'}, $_->{'url'} } @data };
526 }
527
528
529
530 sub __pick_url {
531     my $self = shift;
532     my $urls = shift;
533     my $preflist = shift;
534     my $metadata = shift;
535
536     foreach (keys(%{$urls})) {
537         if (exists($videoformats{$_})) {
538             $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
539         } else {
540             $self->error('Unknown format %s: %s', $_, $urls->{$_});
541         }
542     }
543
544     foreach (@{$preflist}) {
545         if (exists($urls->{$_})) {
546             $self->debug("Selected URL with quality level %s", $_);
547             $metadata->{'DLURL'} = $urls->{$_};
548             if (exists($videoformats{$_})) {
549                 $metadata->{'FORMAT'} = $videoformats{$_};
550             } else {
551                 $metadata->{'FORMAT'} = 'unknown';
552             }
553             last;
554         }
555     }
556
557     $self->debug('URL found: %s', $metadata->{'DLURL'});
558 }
559
560 1;
561