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