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