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