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