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