Redtube: Fix grabber
[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->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
59                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
60                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
61                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
62                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
63                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
64                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
65                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
66     $self->{'_PARAMS'} = {
67             'QUALITY' => ['normal', 'Quality of the video to download.', {
68                     'normal' => 'standard resolution flash video',
69                     'high' => 'higher resolution flash video',
70                     'h264' => 'high resolution MPEG4 video',
71                     'hd' => 'HD720 resolution'}],
72             'USERNAME' => ['', 'Username to use for YouTube login'],
73             'PASSWORD' => ['', 'Password to use for YouTube login'],
74             'HTTPS' => [1, 'Whether to use HTTPS (if available) to connect to YouTube']};
75
76     bless($self, $class);
77     $self->_prepare_parameters();
78
79     return $self;
80 }
81
82 sub _parse {
83     my $self = shift;
84     my $url = shift;
85     my $pattern = shift;
86     my $id;
87     my $res;
88
89     $url =~ m|$pattern|;
90     $url = $1;
91     $id = $2;
92
93     $self->debug("Matched id %s from pattern %s", $id, $pattern);
94
95     $res = $self->_parse_by_video_info($url, $id);
96     if (defined($res) && ref($res)) {
97         return $res;
98     } else {
99         $res = $self->_parse_by_scrape($url, $id);
100     }
101
102     return $res;
103 }
104
105 sub _parse_by_video_info {
106     my $self = shift;
107     my $url = shift;
108     my $id = shift;
109     my $quality = $self->_getval('QUALITY');
110     my $metadata;
111     my $videourl;
112     my $ua = $self->ua();
113     my $preflist;
114     my $r;
115     my $content;
116     my $urls;
117
118     $metadata->{'URL'} = $url;
119     $metadata->{'ID'} = $id;
120     $metadata->{'TYPE'} = 'video';
121     $metadata->{'SOURCE'} = $self->{'NAME'};
122     $metadata->{'TITLE'} = undef;
123     $metadata->{'DLURL'} = undef;
124     $metadata->{'COOKIE'} = undef;
125
126     $preflist = $preflist{$quality};
127     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
128
129     $videourl = sprintf('%s://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
130             $self->_getval('HTTPS')?'https':'http', $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
131     $self->debug("Video info URL: %s", $videourl);
132
133     $r = $ua->get($videourl);
134     unless($r->is_success()) {
135         $self->debug('Could not download %s: %s', $videourl, $r->code());
136         return undef;
137     }
138
139     $content = $r->content();
140     $self->debug('Content from get_video_info: %s', $content);
141
142     # Decode content
143     $content = $self->decode_querystring($content);
144
145     if ($content->{'status'} ne 'ok') {
146         $self->debug("Non OK status code found: %s", $content->{'status'});
147         return undef;
148     }
149
150     if (exists($content->{'fmt_url_map'})) {
151         # Decode fmt_url_map
152         $urls = $self->decode_hexurl($content->{'fmt_url_map'});
153         $urls = { split /[\|,]/, $urls };
154     } elsif (exists($content->{'url_encoded_fmt_stream_map'})) {
155         $urls = $self->_decode_url_encoded_fmt_stream_map($content->{'url_encoded_fmt_stream_map'}, 1);
156     } else {
157         $self->debug("No URL data found");
158         return undef;
159     }
160
161     unless(exists($content->{'title'})) {
162         $self->debug("No title found");
163         return undef;
164     }
165
166     $self->__pick_url($urls, $preflist, $metadata);
167
168     $metadata->{'TITLE'} = $content->{'title'};
169     $metadata->{'TITLE'} =~ s/\+/ /g;
170     $metadata->{'TITLE'} = $self->decode_hexurl($metadata->{'TITLE'});
171     $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
172
173     $self->debug('Title found: %s', $metadata->{'TITLE'});
174
175     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
176         $self->error('Could not determine download URL');
177         return undef;
178     }
179
180     return $metadata;
181 }
182
183 sub _parse_by_scrape {
184     my $self = shift;
185     my $url = shift;
186     my $id = shift;
187     my $content;
188     my $metadata = {};
189     my $p;
190     my $e;
191     my $tag;
192     my $ua = $self->ua();
193     my $r;
194     my $videourl;
195     my $quality = $self->_getval('QUALITY');
196     my $preflist;
197     my $jsp;
198
199     $metadata->{'URL'} = $url;
200     $metadata->{'ID'} = $id;
201     $metadata->{'TYPE'} = 'video';
202     $metadata->{'SOURCE'} = $self->{'NAME'};
203     $metadata->{'TITLE'} = undef;
204     $metadata->{'DLURL'} = undef;
205     $metadata->{'COOKIE'} = 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         $metadata->{'COOKIE'} = $logindata[1];
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                 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             }
343
344             if (%urls) {
345                 $self->__pick_url(\%urls, $preflist, $metadata);
346                 last SWF_ARGS;
347             }
348         } elsif ('div' eq $tag->[0]) {
349             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
350                 # Search forward to the next <div>
351                 $tag = $p->get_tag('div');
352                 $self->error("Could not get video data for youtube %s: %s",
353                         $metadata->{'ID'}, $p->get_trimmed_text());
354                 return undef;
355             }
356         }
357     }
358
359     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
360         $self->error('Could not determine download URL');
361         return undef;
362     }
363
364     return $metadata;
365 }
366
367 sub __login {
368     my $self = shift;
369     my $videourl = shift;
370     my $ua = shift;
371     my $user = $self->_getval('USERNAME');
372     my $pass = $self->_getval('PASSWORD');
373     my $r;
374     my $p;
375     my $c;
376     my $token;
377
378     sub check_cookie {
379
380         my $jar = shift;
381         my $key = shift;
382         my $found = undef;
383
384         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
385
386         return $found;
387     }
388
389     sub get_all_cookies {
390
391         my $jar = shift;
392         my $key = shift;
393         my $val = "";
394         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
395
396         return $val;
397     }
398
399     if (($user eq '') or ($pass eq '')) {
400         $self->error('No username or password defined for YouTube');
401         return undef;
402     }
403
404     $self->debug('Logging in');
405     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
406     unless($r->is_success()) {
407         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
408         return undef;
409     }
410     $c = $r->decoded_content();
411     $p = HTML::TokeParser->new(\$c);
412     while (my $tag = $p->get_tag('input')) {
413         $self->debug("%s", Dumper($tag));
414         if ($tag->[1]{name} eq 'GALX') {
415             $token = $tag->[1]{value};
416             last;
417         }
418     }
419     $self->debug("GALX = %s", $token);
420     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
421     unless($r->is_success()) {
422         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
423         return undef;
424     }
425     $c = $r -> decoded_content();
426     $p = HTML::TokeParser->new(\$c);
427     while (my $tag = $p->get_tag('script')) {
428         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
429             $token = $1;
430             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
431             last;
432         }
433     }
434     $r = $ua->get($token);
435     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
436         $self->error('Could not log into YouTube');
437         return undef;
438     }
439
440     $self->debug("Got a cookie");
441
442     $r = $ua->get($videourl);
443     if ($r->base->as_string() =~ m,/verify_age,) {
444         $self->debug("Looking for session token...");
445         $c = $r->decoded_content();
446         $p = HTML::TokeParser->new(\$c);
447         while (my $tag = $p->get_tag('script')) {
448             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
449                 $token = $1;
450                 last;
451             }
452         }
453
454         unless(defined($token)) {
455             $self->error("Could not find session token");
456             return undef;
457         }
458
459         $self->debug('Authenticating session...');
460         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
461     }
462
463 # Apparently there is no longer a specific "is_adult" cookie
464 # or, by the looks of it, anything similar
465 #
466 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
467 #        $self->error('Could not authenticate session');
468 #        return undef;
469 #    }
470
471     my $cookie = get_all_cookies($ua->cookie_jar);
472     return ($ua->get($videourl), $cookie);
473 }
474
475 # Take an encoded url_encoded_fmt_stream_map and return a hash
476 # matching video IDs to download URLs
477 sub _decode_url_encoded_fmt_stream_map {
478     my $self = shift;
479     my $data = shift;
480     my $dataencoded = shift;
481     my @data;
482
483     $data = $self->decode_hexurl($data) if $dataencoded;
484     # This will
485     # - Split the decoded string into segments (along ,)
486     # - Interpret each segment as a concatenated key-value list (key and value separated by =, pairs separated by &
487     # - URL-decode each key and value _again_
488     #
489     # @data will be an array of hash references
490     
491     @data = map { { map { $self->decode_hexurl($_) } split /[&=]/  } } split /,/, $data;
492     $self->debug("_decode_url_encoded_fmt_stream_map() decoded %s", Dumper(\@data));
493
494     # From each array entry, pick the itag and the url values and return that
495     # as a hash reference
496     
497     return { map { $_->{'itag'}, $_->{'url'} } @data };
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