YouTube: fix some warnings
[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 = { split /[&=]/, $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     unless(exists($content->{'fmt_url_map'}) and exists($content->{'title'})) {
138         $self->debug("No fmt_url_map or no title found");
139         return undef;
140     }
141
142     # Decode fmt_url_map
143     $urls = $content->{'fmt_url_map'};
144     $urls =~ s/%(..)/chr(hex($1))/ge;
145     $urls = { split /[\|,]/, $urls };
146
147     $self->__pick_url($urls, $preflist, $metadata);
148
149     $metadata->{'TITLE'} = $content->{'title'};
150     $metadata->{'TITLE'} =~ s/\+/ /g;
151     $metadata->{'TITLE'} =~ s/%(..)/chr(hex($1))/ge;
152     $metadata->{'TITLE'} = decode("utf8", $metadata->{'TITLE'});
153
154     $self->debug('Title found: %s', $metadata->{'TITLE'});
155
156     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
157         $self->error('Could not determine download URL');
158         return undef;
159     }
160
161     return $metadata;
162 }
163
164 sub _parse_by_scrape {
165     my $self = shift;
166     my $url = shift;
167     my $id = shift;
168     my $content;
169     my $metadata = {};
170     my $p;
171     my $e;
172     my $tag;
173     my $ua = $self->ua();
174     my $r;
175     my $videourl;
176     my $quality = $self->_getval('QUALITY');
177     my $preflist;
178     my $jsp;
179
180     $metadata->{'URL'} = $url;
181     $metadata->{'ID'} = $id;
182     $metadata->{'TYPE'} = 'video';
183     $metadata->{'SOURCE'} = $self->{'NAME'};
184     $metadata->{'TITLE'} = undef;
185     $metadata->{'DLURL'} = undef;
186     $metadata->{'COOKIE'} = undef;
187
188
189     $preflist = $preflist{$quality};
190     $self->debug("Quality: %s, preflist: [%s]", $quality, join(", ", @{$preflist}));
191
192     $videourl = sprintf('https://www.youtube.com/watch?v=%s', $id);
193
194     unless(defined($r = $ua->get($videourl))) {
195         $self->error('Could not download %s', $url);
196         return undef;
197     }
198
199     if ($r->base->as_string() =~ m,/verify_age,) {
200         $self->debug('Video requires age verification');
201         my @logindata = $self->__login($videourl, $ua);
202         $r = $logindata[0];
203         $metadata->{'COOKIE'} = $logindata[1];
204         unless(defined($r)) {
205             $self->error('Could not log into YouTube');
206             return undef;
207         }
208     }
209     $content = $r->content();
210
211     $p = HTML::TokeParser->new(\$content);
212
213     SWF_ARGS: while ($tag = $p->get_tag('div', 'meta', 'script')) {
214         if ('meta' eq $tag->[0]) {
215             if (exists($tag->[1]->{'name'}) and ('title' eq $tag->[1]->{'name'})) {
216                 $metadata->{'TITLE'} = $tag->[1]->{'content'};
217                 # Convert HTML entities in the title. This is a bit convoluted.
218                 $metadata->{'TITLE'} = decode_entities(
219                                            decode("utf8", $metadata->{'TITLE'}));
220                     
221                 $self->debug('Title found: %s', $metadata->{'TITLE'});
222             }
223         } elsif ('script' eq $tag->[0]) {
224             my %urls;
225
226             $e = $p->get_text();
227             $self->debug("Found script: %s", $e);
228
229             if ($e =~ m|\x27SWF_ARGS\x27:\s+(.+),|) {
230                 my $args = $1;
231
232                 $self->debug("Found SWF_ARGS: %s", $args);
233                 $jsp = videosite::JSArrayParser->new();
234                 $self->debug("Using %s to parse", ref($jsp));
235                 $r = $jsp->parse($args);
236
237                 unless(defined($r)) {
238                     $self->error("Found information hash, but could not parse");
239                     return undef;
240                 }
241
242                 if (exists($r->{'fmt_url_map'}) and ($r->{'fmt_url_map'} ne '')) {
243                     my $urls =  $r->{'fmt_url_map'};
244
245                     $self->debug("Video has fmt_url_map: %s", $urls);
246
247                     $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
248                     %urls = split(/[\|,]/, $urls);
249                     $self->debug("Pagetype: old (SWF_ARGS), fmt_url_map");
250
251                 } elsif (exists($r->{'t'}) and ($r->{'t'} ne '')) {
252                     my $thash = $r->{'t'};
253
254                     if (exists($r->{'fmt_map'}) && ($r->{'fmt_map'} ne '')) {
255                         my $fmt = $r->{'fmt_map'};
256                         my @fmt;
257
258                         $self->debug('Video has fmt_map');
259                         $fmt =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
260                         @fmt = split(/,/, $fmt);
261                         foreach (@fmt) {
262                             @_=split(/\//);
263                             $urls{$_[0]} =  sprintf('http://www.youtube.com/get_video?video_id=%s&fmt=%d&t=%s', 
264                                 $metadata->{'ID'},
265                                 $_[0],
266                                 $thash);
267                         }
268                         $self->debug("Pagetype: 2009 (SWF_ARGS), t with fmt_map");
269
270                     } else {
271                         $urls{5} = sprintf('http://www.youtube.com/get_video?video_id=%s&t=%s',
272                             $metadata->{'ID'},
273                             $thash);
274                         $self->debug("Pagetype: 2009 (SWF_ARGS), t without fmt_map");
275                     }
276                 } else {
277                     $self->error('Neither fmt_url_map nor t found in video information hash');
278                     return undef;
279                 }
280             } elsif ($e =~ m|var swfHTML = .*fmt_url_map=([^\&]+)\&|) {
281                 my $urls = $1;
282                 $self->debug("Video has fmt_url_map: %s", $urls);
283
284                 $urls =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
285                 %urls = split(/[\|,]/, $urls);
286                 $self->debug("Pagetype: 2010 (swfHTML), fmt_url_map");
287             } elsif ($e =~ m|\x27PLAYER_CONFIG\x27:\s+(.+)\}\);|) {
288                 my $args = $1;
289                 $self->debug("Found PLAYER_CONFIG: %s", $args);
290
291                 $jsp = videosite::JSArrayParser->new();
292                 $self->debug("Using %s to parse", ref($jsp));
293                 $r = $jsp->parse($args);
294
295                 unless(defined($r)) {
296                     $self->error("Found information hash, but could not parse");
297                     return undef;
298                 }
299
300                 if (exists($r->{'args'}) and exists($r->{'args'}->{'ps'}) and ($r->{'args'}->{'ps'} eq 'live')) {
301                     $self->error("Video URL seems to point to a live stream, cannot save this");
302                     return undef;
303                 }
304
305                 if (exists($r->{'args'}) and exists($r->{'args'}->{'fmt_url_map'}) and ($r->{'args'}->{'fmt_url_map'} ne '')) {
306                     my $urls = $r->{'args'}->{'fmt_url_map'};
307
308                     $self->debug("Video has fmt_url_map: %s", $urls);
309
310                     %urls = split(/[\|,]/, $urls);
311                     foreach (keys(%urls)) {
312                         my $u = $urls{$_};
313                         $u =~ s/%([[:xdigit:]]{2})/chr(hex($1))/ge;
314                         $urls{$_} = $u;
315                     }
316                     $self->debug("Pagetype: 2011 (PLAYER_CONFIG), fmt_url_map");
317                 } else {
318                     $self->error('fmt_url_map not found in PLAYER_CONFIG');
319                     return undef;
320                 }
321             }
322
323             if (%urls) {
324                 $self->__pick_url(\%urls, $preflist, $metadata);
325                 last SWF_ARGS;
326             }
327         } elsif ('div' eq $tag->[0]) {
328             if (exists($tag->[1]->{'id'}) and ('watch-player-unavailable-message-container' eq $tag->[1]->{'id'})) {
329                 # Search forward to the next <div>
330                 $tag = $p->get_tag('div');
331                 $self->error("Could not get video data for youtube %s: %s",
332                         $metadata->{'ID'}, $p->get_trimmed_text());
333                 return undef;
334             }
335         }
336     }
337
338     unless(defined($metadata->{'DLURL'}) && defined($metadata->{'TITLE'})) {
339         $self->error('Could not determine download URL');
340         return undef;
341     }
342
343     return $metadata;
344 }
345
346 sub __login {
347     my $self = shift;
348     my $videourl = shift;
349     my $ua = shift;
350     my $user = $self->_getval('USERNAME');
351     my $pass = $self->_getval('PASSWORD');
352     my $r;
353     my $p;
354     my $c;
355     my $token;
356
357     sub check_cookie {
358
359         my $jar = shift;
360         my $key = shift;
361         my $found = undef;
362
363         $jar->scan(sub { $found = 1 if ( $key eq $_[1]) });
364
365         return $found;
366     }
367
368     sub get_all_cookies {
369
370         my $jar = shift;
371         my $key = shift;
372         my $val = "";
373         $jar->scan(sub { $val .= "; " if !( $val eq "" ); $val .= "$_[1]=$_[2]" });
374
375         return $val;
376     }
377
378     if (($user eq '') or ($pass eq '')) {
379         $self->error('No username or password defined for YouTube');
380         return undef;
381     }
382
383     $self->debug('Logging in');
384     $r = $ua->get('https://www.google.com/accounts/ServiceLoginAuth?service=youtube');
385     unless($r->is_success()) {
386         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
387         return undef;
388     }
389     $c = $r->decoded_content();
390     $p = HTML::TokeParser->new(\$c);
391     while (my $tag = $p->get_tag('input')) {
392         $self->debug("%s", Dumper($tag));
393         if ($tag->[1]{name} eq 'GALX') {
394             $token = $tag->[1]{value};
395             last;
396         }
397     }
398     $self->debug("GALX = %s", $token);
399     $r = $ua->post('https://www.google.com/accounts/ServiceLoginAuth?service=youtube', { 'service' => 'youtube', 'Email' => $user, 'Passwd' => $pass, 'GALX' => $token });
400     unless($r->is_success()) {
401         $self->debug("Could not get login page (make sure your LWP supports HTTPS!)");
402         return undef;
403     }
404     $c = $r -> decoded_content();
405     $p = HTML::TokeParser->new(\$c);
406     while (my $tag = $p->get_tag('script')) {
407         if($p->get_text() =~ /location\.replace\("(.+)"\)/) {
408             $token = $1;
409             $token =~ s/\\x([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
410             last;
411         }
412     }
413     $r = $ua->get($token);
414     unless(check_cookie($ua->cookie_jar, 'LOGIN_INFO')) {
415         $self->error('Could not log into YouTube');
416         return undef;
417     }
418
419     $self->debug("Got a cookie");
420
421     $r = $ua->get($videourl);
422     if ($r->base->as_string() =~ m,/verify_age,) {
423         $self->debug("Looking for session token...");
424         $c = $r->decoded_content();
425         $p = HTML::TokeParser->new(\$c);
426         while (my $tag = $p->get_tag('script')) {
427             if ($p->get_text() =~ /'XSRF_TOKEN': '(.+)'/) {
428                 $token = $1;
429                 last;
430             }
431         }
432
433         unless(defined($token)) {
434             $self->error("Could not find session token");
435             return undef;
436         }
437
438         $self->debug('Authenticating session...');
439         $r = $ua->post($r->base->as_string, { 'next_url' => $r->base->path, 'action_confirm' => 'Confirm Birth Date', 'session_token' => $token });
440     }
441
442 # Apparently there is no longer a specific "is_adult" cookie
443 # or, by the looks of it, anything similar
444 #
445 #    unless(check_cookie($ua->cookie_jar, 'is_adult')) {
446 #        $self->error('Could not authenticate session');
447 #        return undef;
448 #    }
449
450     my $cookie = get_all_cookies($ua->cookie_jar);
451     return ($ua->get($videourl), $cookie);
452 }
453
454 sub __pick_url {
455     my $self = shift;
456     my $urls = shift;
457     my $preflist = shift;
458     my $metadata = shift;
459
460     foreach (keys(%{$urls})) {
461         if (exists($videoformats{$_})) {
462             $self->debug('Found URL for format %s (%s): %s', $_, $videoformats{$_}, $urls->{$_});
463         } else {
464             $self->error('Unknown format %s: %s', $_, $urls->{$_});
465         }
466     }
467
468     foreach (@{$preflist}) {
469         if (exists($urls->{$_})) {
470             $self->debug("Selected URL with quality level %s", $_);
471             $metadata->{'DLURL'} = $urls->{$_};
472             last;
473         }
474     }
475
476     $self->debug('URL found: %s', $metadata->{'DLURL'});
477 }
478
479 1;