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