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