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