Youtube: Add a parser that uses /get_video_info, with a fallback to the old method
[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],
24     'hd' => [37, 22, 35, 18, 34, 6, 5, 38],
25     'h264' => [18, 34, 37, 22, 35, 6, 5, 38],
26     'high' => [34, 35, 18, 37, 22, 6, 5, 38],
27     'normal' => [6, 5, 34, 35, 18, 22, 37, 38]);
28 my %videoformats = (
29     38 => 'mp4,h264,4k',
30     37 => 'mp4,h264,1080p',
31     35 => 'flv,h264,large',
32     34 => 'flv,h264',
33     22 => 'mp4,h264,720p',
34     18 => 'mp4,h264',
35     5 => 'flv,flv',
36     );
37
38 sub new {
39     my $class = shift;
40     my $self = $class->SUPER::new();
41
42     $self->{'NAME'} = 'youtube';
43     $self->{'PATTERNS'} = ['(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch(?:_popup)?\?(?:.+=.+&)*v=([-a-zA-Z0-9_]+))',
44                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/watch\#\!v=([-a-zA-Z0-9_]+))',
45                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/v/([-a-zA-Z0-9_]+))',
46                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/[[:alnum:]]+\?v=([-a-zA-Z0-9_]+))',
47                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/(?:user/)?[[:alnum:]]+#p/(?:\w+/)+\d+/([-a-zA-Z0-9_]+))',
48                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/watch\?v=([-a-zA-Z0-9_]+))',
49                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtu\.be/([-a-zA-Z0-9_]+))',
50                            '(https?://(?:[-a-zA-Z0-9_.]+\.)*youtube\.(?:com|de|co.uk)/user/\w+\?.*/([-a-zA-Z0-9_]+))'];
51     $self->{'_PARAMS'} = {
52             'QUALITY' => ['normal', 'Quality of the video to download.', {
53                     'normal' => 'standard resolution flash video',
54                     'high' => 'higher resolution flash video',
55                     'h264' => 'high resolution MPEG4 video',
56                     'hd' => 'HD720 resolution'}],
57             'USERNAME' => ['', 'Username to use for YouTube login'],
58             'PASSWORD' => ['', 'Password to use for YouTube login']};
59
60     bless($self, $class);
61     $self->_prepare_parameters();
62
63     return $self;
64 }
65
66 sub _parse {
67     my $self = shift;
68     my $url = shift;
69     my $pattern = shift;
70     my $id;
71     my $res;
72
73     my $url =~ m|$pattern|;
74     my $url = $1;
75     my $id = $2;
76
77     $self->debug("Matched id %s from pattern %s", $id, $pattern);
78
79     $res = $self->_parse_by_video_info($url, $id);
80     if (defined($res) && ref($res)) {
81         return $res;
82     } else {
83         $res = $self->_parse_by_scrape($url, $id);
84     }
85
86     return $res;
87 }
88
89 sub _parse_by_video_info {
90     my $self = shift;
91     my $url = shift;
92     my $id = shift;
93     my $quality = $self->_getval('QUALITY');
94     my $metadata;
95     my $videourl;
96     my $ua = $self->{_ua};
97     my $preflist;
98     my $r;
99     my $content;
100     my $urls;
101
102     $metadata->{'URL'} = $url;
103     $metadata->{'ID'} = $id;
104     $metadata->{'TYPE'} = 'video';
105     $metadata->{'SOURCE'} = $self->{'NAME'};
106     $metadata->{'TITLE'} = undef;
107     $metadata->{'DLURL'} = undef;
108     $metadata->{'COOKIE'} = undef;
109
110     $preflist = $preflist{$quality};
111     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
112
113     $videourl = sprintf('https://www.youtube.com/get_video_info?video_id=%s&eurl=%s',
114             $id, 'http%3A%2F%2Fwww%2Eyoutube%2Ecom%2F');
115     $self->debug("Video info URL: %s", $videourl);
116
117     $r = $ua->get($videourl);
118     unless($r->is_success()) {
119         $self->debug('Could not download %s: %s', $videourl, $r->code());
120         return undef;
121     }
122
123     $content = $r->content();
124     $self->debug('Content from get_video_info: %s', $content);
125
126     # Decode content
127     $content = { split /[&=]/, $content };
128
129     if ($content->{'status'} ne 'ok') {
130         $self->debug("Non OK status code found: %s", $content->{'status'});
131         return undef;
132     }
133
134     unless(exists($content->{'fmt_url_map'}) and exists($content->{'title'})) {
135         $self->debug("No fmt_url_map or no title found");
136         return undef;
137     }
138
139     # Decode fmt_url_map
140     $urls = $content->{'fmt_url_map'};
141     $urls =~ s/%(..)/chr(hex($1))/ge;
142     $urls = { split /[\|,]/, $urls };
143
144     foreach (keys(%{$urls})) {
145         if (exists($videoformats{$_})) {
146             $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
147         } else {
148             $self->error('Unknown format %s: %s', $_, $urls->{$_});
149         }
150     }
151
152     foreach (@{$preflist}) {
153         if (exists($urls->{$_})) {
154             $self->debug("Selected URL with quality level %s", $_);
155             $metadata->{'DLURL'} = $urls->{$_};
156             last;
157         }
158     }
159
160     $self->debug('URL found: %s', $metadata->{'DLURL'});
161
162     $metadata->{'TITLE'} = $content->{'title'};
163     $metadata->{'TITLE'} =~ s/\+/ /g;
164     $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
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('https://www.youtube.com/watch?v=%s', $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'} = encode("utf8",
231                                          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 =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
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 =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
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 =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
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                         my $u = $urls{$_};
326                         $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
327                         $urls{$_} = $u;
328                     }
329                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
330                 } else {
331                     $self->error('fmt_url_map not found in PLAYER_CONFIG');
332                     return undef;
333                 }
334             }
335
336             if (%urls) {
337                 foreach (keys(%urls)) {
338                     if (exists($videoformats{$_})) {
339                         $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls{$_});
340                     } else {
341                         $self->error('Unknown format %s: %s', $_, $urls{$_});
342                     }
343                 }
344
345                 foreach (@{$preflist}) {
346                     if (exists($urls{$_})) {
347                         $self->debug("Selected URL with quality level %s", $_);
348                         $metadata->{'DLURL'} = $urls{$_};
349                         last;
350                     }
351                 }
352
353                 $self->debug('URL found: %s', $metadata->{'DLURL'});
354                 last SWF_ARGS;
355             }
356         } elsif ('div' eq $tag->[0]) {
357             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
358                 # Search forward to the next <div>
359                 $tag = $p->get_tag('div');
360                 $self->error("Could not get video data for youtube %s: %s",
361                         $metadata->{'ID'}, $p->get_trimmed_text());
362                 return undef;
363             }
364         }
365     }
366
367     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
368         $self->error('Could not determine download URL');
369         return undef;
370     }
371
372     return $metadata;
373 }
374
375 sub __login {
376     my $self = shift;
377     my $videourl = shift;
378     my $ua = shift;
379     my $user = $self->_getval('USERNAME');
380     my $pass = $self->_getval('PASSWORD');
381     my $r;
382     my $p;
383     my $c;
384     my $token;
385
386     sub check_cookie {
387
388         my $jar = shift;
389         my $key = shift;
390         my $found = undef;
391
392         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
393
394         return $found;
395     }
396
397     sub get_all_cookies {
398
399         my $jar = shift;
400         my $key = shift;
401         my $val = "";
402         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
403
404         return $val;
405     }
406
407     if (($user eq '') or ($pass eq '')) {
408         $self->error('No username or password defined for YouTube');
409         return undef;
410     }
411
412     $self->debug('Logging in');
413     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
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('input')) {
421         $self->debug("%s", Dumper($tag));
422         if ($tag->[1]{name} eq 'GALX') {
423             $token = $tag->[1]{value};
424             last;
425         }
426     }
427     $self->debug("GALX = %s", $token);
428     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
429     unless($r->is_success()) {
430         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
431         return undef;
432     }
433     $c = $r -> decoded_content();
434     $p = HTML::TokeParser->new(\$c);
435     while (my $tag = $p->get_tag('script')) {
436         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
437             $token = $1;
438             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
439             last;
440         }
441     }
442     $r = $ua->get($token);
443     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
444         $self->error('Could not log into YouTube');
445         return undef;
446     }
447
448     $self->debug("Got a cookie");
449
450     $r = $ua->get($videourl);
451     if ($r->base->as_string() =~ m,/verify_age,) {
452         $self->debug("Looking for session token...");
453         $c = $r->decoded_content();
454         $p = HTML::TokeParser->new(\$c);
455         while (my $tag = $p->get_tag('script')) {
456             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
457                 $token = $1;
458                 last;
459             }
460         }
461
462         unless(defined($token)) {
463             $self->error("Could not find session token");
464             return undef;
465         }
466
467         $self->debug('Authenticating session...');
468         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
469     }
470
471 # Apparently there is no longer a specific "is_adult" cookie
472 # or, by the looks of it, anything similar
473 #
474 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
475 #        $self->error('Could not authenticate session');
476 #        return undef;
477 #    }
478
479     my $cookie = get_all_cookies($ua->cookie_jar);
480     return ($ua->get($videourl), $cookie);
481 }
482
483 1;