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