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