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