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