Merge pull request #954 from gitprojs/generic
[youtube-dl] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 import json
4 import netrc
5 import re
6 import socket
7
8 from .common import InfoExtractor, SearchInfoExtractor
9 from ..utils import (
10     compat_http_client,
11     compat_parse_qs,
12     compat_urllib_error,
13     compat_urllib_parse,
14     compat_urllib_request,
15     compat_str,
16
17     clean_html,
18     get_element_by_id,
19     ExtractorError,
20     unescapeHTML,
21     unified_strdate,
22 )
23
24
25 class YoutubeIE(InfoExtractor):
26     """Information extractor for youtube.com."""
27
28     _VALID_URL = r"""^
29                      (
30                          (?:https?://)?                                       # http(s):// (optional)
31                          (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
32                             tube\.majestyc\.net/)                             # the various hostnames, with wildcard subdomains
33                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
34                          (?:                                                  # the various things that can precede the ID:
35                              (?:(?:v|embed|e)/)                               # v/ or embed/ or e/
36                              |(?:                                             # or the v= param in all its forms
37                                  (?:watch(?:_popup)?(?:\.php)?)?              # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
38                                  (?:\?|\#!?)                                  # the params delimiter ? or # or #!
39                                  (?:.*?&)?                                    # any other preceding param (like /?s=tuff&v=xxxx)
40                                  v=
41                              )
42                          )?                                                   # optional -> youtube.com/xxxx is OK
43                      )?                                                       # all until now is optional -> you can pass the naked ID
44                      ([0-9A-Za-z_-]+)                                         # here is it! the YouTube video ID
45                      (?(1).+)?                                                # if we found the ID, everything can follow
46                      $"""
47     _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
48     _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
49     _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
50     _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
51     _NETRC_MACHINE = 'youtube'
52     # Listed in order of quality
53     _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
54     _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
55     _video_extensions = {
56         '13': '3gp',
57         '17': 'mp4',
58         '18': 'mp4',
59         '22': 'mp4',
60         '37': 'mp4',
61         '38': 'mp4',
62         '43': 'webm',
63         '44': 'webm',
64         '45': 'webm',
65         '46': 'webm',
66     }
67     _video_dimensions = {
68         '5': '240x400',
69         '6': '???',
70         '13': '???',
71         '17': '144x176',
72         '18': '360x640',
73         '22': '720x1280',
74         '34': '360x640',
75         '35': '480x854',
76         '37': '1080x1920',
77         '38': '3072x4096',
78         '43': '360x640',
79         '44': '480x854',
80         '45': '720x1280',
81         '46': '1080x1920',
82     }
83     IE_NAME = u'youtube'
84     _TESTS = [
85         {
86             u"url":  u"http://www.youtube.com/watch?v=BaW_jenozKc",
87             u"file":  u"BaW_jenozKc.mp4",
88             u"info_dict": {
89                 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
90                 u"uploader": u"Philipp Hagemeister",
91                 u"uploader_id": u"phihag",
92                 u"upload_date": u"20121002",
93                 u"description": u"test chars:  \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
94             }
95         },
96         {
97             u"url":  u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
98             u"file":  u"1ltcDfZMA3U.flv",
99             u"note": u"Test VEVO video (#897)",
100             u"info_dict": {
101                 u"upload_date": u"20070518",
102                 u"title": u"Maps - It Will Find You",
103                 u"description": u"Music video by Maps performing It Will Find You.",
104                 u"uploader": u"MuteUSA",
105                 u"uploader_id": u"MuteUSA"
106             }
107         },
108         {
109             u"url":  u"http://www.youtube.com/watch?v=UxxajLWwzqY",
110             u"file":  u"UxxajLWwzqY.mp4",
111             u"note": u"Test generic use_cipher_signature video (#897)",
112             u"info_dict": {
113                 u"upload_date": u"20120506",
114                 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
115                 u"description": u"md5:b085c9804f5ab69f4adea963a2dceb3c",
116                 u"uploader": u"IconaPop",
117                 u"uploader_id": u"IconaPop"
118             }
119         }
120     ]
121
122
123     @classmethod
124     def suitable(cls, url):
125         """Receives a URL and returns True if suitable for this IE."""
126         if YoutubePlaylistIE.suitable(url): return False
127         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
128
129     def report_lang(self):
130         """Report attempt to set language."""
131         self.to_screen(u'Setting language')
132
133     def report_login(self):
134         """Report attempt to log in."""
135         self.to_screen(u'Logging in')
136
137     def report_video_webpage_download(self, video_id):
138         """Report attempt to download video webpage."""
139         self.to_screen(u'%s: Downloading video webpage' % video_id)
140
141     def report_video_info_webpage_download(self, video_id):
142         """Report attempt to download video info webpage."""
143         self.to_screen(u'%s: Downloading video info webpage' % video_id)
144
145     def report_video_subtitles_download(self, video_id):
146         """Report attempt to download video info webpage."""
147         self.to_screen(u'%s: Checking available subtitles' % video_id)
148
149     def report_video_subtitles_request(self, video_id, sub_lang, format):
150         """Report attempt to download video info webpage."""
151         self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
152
153     def report_video_subtitles_available(self, video_id, sub_lang_list):
154         """Report available subtitles."""
155         sub_lang = ",".join(list(sub_lang_list.keys()))
156         self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
157
158     def report_information_extraction(self, video_id):
159         """Report attempt to extract video information."""
160         self.to_screen(u'%s: Extracting video information' % video_id)
161
162     def report_unavailable_format(self, video_id, format):
163         """Report extracted video URL."""
164         self.to_screen(u'%s: Format %s not available' % (video_id, format))
165
166     def report_rtmp_download(self):
167         """Indicate the download will use the RTMP protocol."""
168         self.to_screen(u'RTMP download detected')
169
170     def _decrypt_signature(self, s):
171         """Decrypt the key"""
172
173         if len(s) == 88:
174             return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12]
175         elif len(s) == 87:
176             return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1]
177         elif len(s) == 86:
178             return s[2:63] + s[82] + s[64:82] + s[63]
179         elif len(s) == 85:
180             return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1]
181         elif len(s) == 84:
182             return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26]
183         elif len(s) == 83:
184             return s[52] + s[81:55:-1] + s[2] + s[54:52:-1] + s[82] + s[51:36:-1] + s[55] + s[35:2:-1] + s[36]
185         elif len(s) == 82:
186             return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34]
187
188         else:
189             raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
190
191     def _get_available_subtitles(self, video_id):
192         self.report_video_subtitles_download(video_id)
193         request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
194         try:
195             sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
196         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
197             return (u'unable to download video subtitles: %s' % compat_str(err), None)
198         sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
199         sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
200         if not sub_lang_list:
201             return (u'video doesn\'t have subtitles', None)
202         return sub_lang_list
203
204     def _list_available_subtitles(self, video_id):
205         sub_lang_list = self._get_available_subtitles(video_id)
206         self.report_video_subtitles_available(video_id, sub_lang_list)
207
208     def _request_subtitle(self, sub_lang, sub_name, video_id, format):
209         """
210         Return tuple:
211         (error_message, sub_lang, sub)
212         """
213         self.report_video_subtitles_request(video_id, sub_lang, format)
214         params = compat_urllib_parse.urlencode({
215             'lang': sub_lang,
216             'name': sub_name,
217             'v': video_id,
218             'fmt': format,
219         })
220         url = 'http://www.youtube.com/api/timedtext?' + params
221         try:
222             sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
223         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
224             return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
225         if not sub:
226             return (u'Did not fetch video subtitles', None, None)
227         return (None, sub_lang, sub)
228
229     def _request_automatic_caption(self, video_id, webpage):
230         """We need the webpage for getting the captions url, pass it as an
231            argument to speed up the process."""
232         sub_lang = self._downloader.params.get('subtitleslang') or 'en'
233         sub_format = self._downloader.params.get('subtitlesformat')
234         self.to_screen(u'%s: Looking for automatic captions' % video_id)
235         mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
236         err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
237         if mobj is None:
238             return [(err_msg, None, None)]
239         player_config = json.loads(mobj.group(1))
240         try:
241             args = player_config[u'args']
242             caption_url = args[u'ttsurl']
243             timestamp = args[u'timestamp']
244             params = compat_urllib_parse.urlencode({
245                 'lang': 'en',
246                 'tlang': sub_lang,
247                 'fmt': sub_format,
248                 'ts': timestamp,
249                 'kind': 'asr',
250             })
251             subtitles_url = caption_url + '&' + params
252             sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
253             return [(None, sub_lang, sub)]
254         except KeyError:
255             return [(err_msg, None, None)]
256
257     def _extract_subtitle(self, video_id):
258         """
259         Return a list with a tuple:
260         [(error_message, sub_lang, sub)]
261         """
262         sub_lang_list = self._get_available_subtitles(video_id)
263         sub_format = self._downloader.params.get('subtitlesformat')
264         if  isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
265             return [(sub_lang_list[0], None, None)]
266         if self._downloader.params.get('subtitleslang', False):
267             sub_lang = self._downloader.params.get('subtitleslang')
268         elif 'en' in sub_lang_list:
269             sub_lang = 'en'
270         else:
271             sub_lang = list(sub_lang_list.keys())[0]
272         if not sub_lang in sub_lang_list:
273             return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
274
275         subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
276         return [subtitle]
277
278     def _extract_all_subtitles(self, video_id):
279         sub_lang_list = self._get_available_subtitles(video_id)
280         sub_format = self._downloader.params.get('subtitlesformat')
281         if  isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
282             return [(sub_lang_list[0], None, None)]
283         subtitles = []
284         for sub_lang in sub_lang_list:
285             subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
286             subtitles.append(subtitle)
287         return subtitles
288
289     def _print_formats(self, formats):
290         print('Available formats:')
291         for x in formats:
292             print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
293
294     def _real_initialize(self):
295         if self._downloader is None:
296             return
297
298         username = None
299         password = None
300         downloader_params = self._downloader.params
301
302         # Attempt to use provided username and password or .netrc data
303         if downloader_params.get('username', None) is not None:
304             username = downloader_params['username']
305             password = downloader_params['password']
306         elif downloader_params.get('usenetrc', False):
307             try:
308                 info = netrc.netrc().authenticators(self._NETRC_MACHINE)
309                 if info is not None:
310                     username = info[0]
311                     password = info[2]
312                 else:
313                     raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
314             except (IOError, netrc.NetrcParseError) as err:
315                 self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
316                 return
317
318         # Set language
319         request = compat_urllib_request.Request(self._LANG_URL)
320         try:
321             self.report_lang()
322             compat_urllib_request.urlopen(request).read()
323         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
324             self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
325             return
326
327         # No authentication to be performed
328         if username is None:
329             return
330
331         request = compat_urllib_request.Request(self._LOGIN_URL)
332         try:
333             login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
334         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
335             self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
336             return
337
338         galx = None
339         dsh = None
340         match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
341         if match:
342           galx = match.group(1)
343
344         match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
345         if match:
346           dsh = match.group(1)
347
348         # Log in
349         login_form_strs = {
350                 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
351                 u'Email': username,
352                 u'GALX': galx,
353                 u'Passwd': password,
354                 u'PersistentCookie': u'yes',
355                 u'_utf8': u'霱',
356                 u'bgresponse': u'js_disabled',
357                 u'checkConnection': u'',
358                 u'checkedDomains': u'youtube',
359                 u'dnConn': u'',
360                 u'dsh': dsh,
361                 u'pstMsg': u'0',
362                 u'rmShown': u'1',
363                 u'secTok': u'',
364                 u'signIn': u'Sign in',
365                 u'timeStmp': u'',
366                 u'service': u'youtube',
367                 u'uilel': u'3',
368                 u'hl': u'en_US',
369         }
370         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
371         # chokes on unicode
372         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
373         login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
374         request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
375         try:
376             self.report_login()
377             login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
378             if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
379                 self._downloader.report_warning(u'unable to log in: bad username or password')
380                 return
381         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
382             self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
383             return
384
385         # Confirm age
386         age_form = {
387                 'next_url':     '/',
388                 'action_confirm':   'Confirm',
389                 }
390         request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
391         try:
392             self.report_age_confirmation()
393             compat_urllib_request.urlopen(request).read().decode('utf-8')
394         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
395             raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
396
397     def _extract_id(self, url):
398         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
399         if mobj is None:
400             raise ExtractorError(u'Invalid URL: %s' % url)
401         video_id = mobj.group(2)
402         return video_id
403
404     def _real_extract(self, url):
405         # Extract original video URL from URL with redirection, like age verification, using next_url parameter
406         mobj = re.search(self._NEXT_URL_RE, url)
407         if mobj:
408             url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
409         video_id = self._extract_id(url)
410
411         # Get video webpage
412         self.report_video_webpage_download(video_id)
413         url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
414         request = compat_urllib_request.Request(url)
415         try:
416             video_webpage_bytes = compat_urllib_request.urlopen(request).read()
417         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
418             raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
419
420         video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
421
422         # Attempt to extract SWF player URL
423         mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
424         if mobj is not None:
425             player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
426         else:
427             player_url = None
428
429         # Get video info
430         self.report_video_info_webpage_download(video_id)
431         for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
432             video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
433                     % (video_id, el_type))
434             video_info_webpage = self._download_webpage(video_info_url, video_id,
435                                     note=False,
436                                     errnote='unable to download video info webpage')
437             video_info = compat_parse_qs(video_info_webpage)
438             if 'token' in video_info:
439                 break
440         if 'token' not in video_info:
441             if 'reason' in video_info:
442                 raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0])
443             else:
444                 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
445
446         # Check for "rental" videos
447         if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
448             raise ExtractorError(u'"rental" videos not supported')
449
450         # Start extracting information
451         self.report_information_extraction(video_id)
452
453         # uploader
454         if 'author' not in video_info:
455             raise ExtractorError(u'Unable to extract uploader name')
456         video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
457
458         # uploader_id
459         video_uploader_id = None
460         mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
461         if mobj is not None:
462             video_uploader_id = mobj.group(1)
463         else:
464             self._downloader.report_warning(u'unable to extract uploader nickname')
465
466         # title
467         if 'title' not in video_info:
468             raise ExtractorError(u'Unable to extract video title')
469         video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
470
471         # thumbnail image
472         if 'thumbnail_url' not in video_info:
473             self._downloader.report_warning(u'unable to extract video thumbnail')
474             video_thumbnail = ''
475         else:   # don't panic if we can't find it
476             video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
477
478         # upload date
479         upload_date = None
480         mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
481         if mobj is not None:
482             upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
483             upload_date = unified_strdate(upload_date)
484
485         # description
486         video_description = get_element_by_id("eow-description", video_webpage)
487         if video_description:
488             video_description = clean_html(video_description)
489         else:
490             fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
491             if fd_mobj:
492                 video_description = unescapeHTML(fd_mobj.group(1))
493             else:
494                 video_description = u''
495
496         # subtitles
497         video_subtitles = None
498
499         if self._downloader.params.get('writesubtitles', False):
500             video_subtitles = self._extract_subtitle(video_id)
501             if video_subtitles:
502                 (sub_error, sub_lang, sub) = video_subtitles[0]
503                 if sub_error:
504                     self._downloader.report_warning(sub_error)
505         
506         if self._downloader.params.get('writeautomaticsub', False):
507             video_subtitles = self._request_automatic_caption(video_id, video_webpage)
508             (sub_error, sub_lang, sub) = video_subtitles[0]
509             if sub_error:
510                 self._downloader.report_warning(sub_error)
511
512         if self._downloader.params.get('allsubtitles', False):
513             video_subtitles = self._extract_all_subtitles(video_id)
514             for video_subtitle in video_subtitles:
515                 (sub_error, sub_lang, sub) = video_subtitle
516                 if sub_error:
517                     self._downloader.report_warning(sub_error)
518
519         if self._downloader.params.get('listsubtitles', False):
520             self._list_available_subtitles(video_id)
521             return
522
523         if 'length_seconds' not in video_info:
524             self._downloader.report_warning(u'unable to extract video duration')
525             video_duration = ''
526         else:
527             video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
528
529         # Decide which formats to download
530         req_format = self._downloader.params.get('format', None)
531
532         try:
533             mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
534             if not mobj:
535                 raise ValueError('Could not find vevo ID')
536             info = json.loads(mobj.group(1))
537             args = info['args']
538             # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
539             # this signatures are encrypted
540             m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
541             if m_s is not None:
542                 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
543                 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
544         except ValueError:
545             pass
546
547         if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
548             self.report_rtmp_download()
549             video_url_list = [(None, video_info['conn'][0])]
550         elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
551             url_map = {}
552             for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
553                 url_data = compat_parse_qs(url_data_str)
554                 if 'itag' in url_data and 'url' in url_data:
555                     url = url_data['url'][0]
556                     if 'sig' in url_data:
557                         url += '&signature=' + url_data['sig'][0]
558                     elif 's' in url_data:
559                         if self._downloader.params.get('verbose'):
560                             s = url_data['s'][0]
561                             player = self._search_regex(r'html5player-(.+?)\.js', video_webpage,
562                                 'html5 player', fatal=False)
563                             self.to_screen('encrypted signature length %d (%d.%d), itag %s, html5 player %s' %
564                                 (len(s), len(s.split('.')[0]), len(s.split('.')[1]), url_data['itag'][0], player))
565                         signature = self._decrypt_signature(url_data['s'][0])
566                         url += '&signature=' + signature
567                     if 'ratebypass' not in url:
568                         url += '&ratebypass=yes'
569                     url_map[url_data['itag'][0]] = url
570
571             format_limit = self._downloader.params.get('format_limit', None)
572             available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
573             if format_limit is not None and format_limit in available_formats:
574                 format_list = available_formats[available_formats.index(format_limit):]
575             else:
576                 format_list = available_formats
577             existing_formats = [x for x in format_list if x in url_map]
578             if len(existing_formats) == 0:
579                 raise ExtractorError(u'no known formats available for video')
580             if self._downloader.params.get('listformats', None):
581                 self._print_formats(existing_formats)
582                 return
583             if req_format is None or req_format == 'best':
584                 video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
585             elif req_format == 'worst':
586                 video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
587             elif req_format in ('-1', 'all'):
588                 video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
589             else:
590                 # Specific formats. We pick the first in a slash-delimeted sequence.
591                 # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
592                 req_formats = req_format.split('/')
593                 video_url_list = None
594                 for rf in req_formats:
595                     if rf in url_map:
596                         video_url_list = [(rf, url_map[rf])]
597                         break
598                 if video_url_list is None:
599                     raise ExtractorError(u'requested format not available')
600         else:
601             raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
602
603         results = []
604         for format_param, video_real_url in video_url_list:
605             # Extension
606             video_extension = self._video_extensions.get(format_param, 'flv')
607
608             video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
609                                               self._video_dimensions.get(format_param, '???'))
610
611             results.append({
612                 'id':       video_id,
613                 'url':      video_real_url,
614                 'uploader': video_uploader,
615                 'uploader_id': video_uploader_id,
616                 'upload_date':  upload_date,
617                 'title':    video_title,
618                 'ext':      video_extension,
619                 'format':   video_format,
620                 'thumbnail':    video_thumbnail,
621                 'description':  video_description,
622                 'player_url':   player_url,
623                 'subtitles':    video_subtitles,
624                 'duration':     video_duration
625             })
626         return results
627
628 class YoutubePlaylistIE(InfoExtractor):
629     """Information Extractor for YouTube playlists."""
630
631     _VALID_URL = r"""(?:
632                         (?:https?://)?
633                         (?:\w+\.)?
634                         youtube\.com/
635                         (?:
636                            (?:course|view_play_list|my_playlists|artist|playlist|watch)
637                            \? (?:.*?&)*? (?:p|a|list)=
638                         |  p/
639                         )
640                         ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
641                         .*
642                      |
643                         ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
644                      )"""
645     _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
646     _MAX_RESULTS = 50
647     IE_NAME = u'youtube:playlist'
648
649     @classmethod
650     def suitable(cls, url):
651         """Receives a URL and returns True if suitable for this IE."""
652         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
653
654     def _real_extract(self, url):
655         # Extract playlist id
656         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
657         if mobj is None:
658             raise ExtractorError(u'Invalid URL: %s' % url)
659
660         # Download playlist videos from API
661         playlist_id = mobj.group(1) or mobj.group(2)
662         page_num = 1
663         videos = []
664
665         while True:
666             url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
667             page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
668
669             try:
670                 response = json.loads(page)
671             except ValueError as err:
672                 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
673
674             if 'feed' not in response:
675                 raise ExtractorError(u'Got a malformed response from YouTube API')
676             playlist_title = response['feed']['title']['$t']
677             if 'entry' not in response['feed']:
678                 # Number of videos is a multiple of self._MAX_RESULTS
679                 break
680
681             for entry in response['feed']['entry']:
682                 index = entry['yt$position']['$t']
683                 if 'media$group' in entry and 'media$player' in entry['media$group']:
684                     videos.append((index, entry['media$group']['media$player']['url']))
685
686             if len(response['feed']['entry']) < self._MAX_RESULTS:
687                 break
688             page_num += 1
689
690         videos = [v[1] for v in sorted(videos)]
691
692         url_results = [self.url_result(url, 'Youtube') for url in videos]
693         return [self.playlist_result(url_results, playlist_id, playlist_title)]
694
695
696 class YoutubeChannelIE(InfoExtractor):
697     """Information Extractor for YouTube channels."""
698
699     _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
700     _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
701     _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
702     _MORE_PAGES_URL = 'http://www.youtube.com/channel_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
703     IE_NAME = u'youtube:channel'
704
705     def extract_videos_from_page(self, page):
706         ids_in_page = []
707         for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
708             if mobj.group(1) not in ids_in_page:
709                 ids_in_page.append(mobj.group(1))
710         return ids_in_page
711
712     def _real_extract(self, url):
713         # Extract channel id
714         mobj = re.match(self._VALID_URL, url)
715         if mobj is None:
716             raise ExtractorError(u'Invalid URL: %s' % url)
717
718         # Download channel page
719         channel_id = mobj.group(1)
720         video_ids = []
721         pagenum = 1
722
723         url = self._TEMPLATE_URL % (channel_id, pagenum)
724         page = self._download_webpage(url, channel_id,
725                                       u'Downloading page #%s' % pagenum)
726
727         # Extract video identifiers
728         ids_in_page = self.extract_videos_from_page(page)
729         video_ids.extend(ids_in_page)
730
731         # Download any subsequent channel pages using the json-based channel_ajax query
732         if self._MORE_PAGES_INDICATOR in page:
733             while True:
734                 pagenum = pagenum + 1
735
736                 url = self._MORE_PAGES_URL % (pagenum, channel_id)
737                 page = self._download_webpage(url, channel_id,
738                                               u'Downloading page #%s' % pagenum)
739
740                 page = json.loads(page)
741
742                 ids_in_page = self.extract_videos_from_page(page['content_html'])
743                 video_ids.extend(ids_in_page)
744
745                 if self._MORE_PAGES_INDICATOR  not in page['load_more_widget_html']:
746                     break
747
748         self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
749
750         urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
751         url_entries = [self.url_result(url, 'Youtube') for url in urls]
752         return [self.playlist_result(url_entries, channel_id)]
753
754
755 class YoutubeUserIE(InfoExtractor):
756     """Information Extractor for YouTube users."""
757
758     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
759     _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
760     _GDATA_PAGE_SIZE = 50
761     _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
762     _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
763     IE_NAME = u'youtube:user'
764
765     def _real_extract(self, url):
766         # Extract username
767         mobj = re.match(self._VALID_URL, url)
768         if mobj is None:
769             raise ExtractorError(u'Invalid URL: %s' % url)
770
771         username = mobj.group(1)
772
773         # Download video ids using YouTube Data API. Result size per
774         # query is limited (currently to 50 videos) so we need to query
775         # page by page until there are no video ids - it means we got
776         # all of them.
777
778         video_ids = []
779         pagenum = 0
780
781         while True:
782             start_index = pagenum * self._GDATA_PAGE_SIZE + 1
783
784             gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
785             page = self._download_webpage(gdata_url, username,
786                                           u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
787
788             # Extract video identifiers
789             ids_in_page = []
790
791             for mobj in re.finditer(self._VIDEO_INDICATOR, page):
792                 if mobj.group(1) not in ids_in_page:
793                     ids_in_page.append(mobj.group(1))
794
795             video_ids.extend(ids_in_page)
796
797             # A little optimization - if current page is not
798             # "full", ie. does not contain PAGE_SIZE video ids then
799             # we can assume that this page is the last one - there
800             # are no more ids on further pages - no need to query
801             # again.
802
803             if len(ids_in_page) < self._GDATA_PAGE_SIZE:
804                 break
805
806             pagenum += 1
807
808         urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
809         url_results = [self.url_result(url, 'Youtube') for url in urls]
810         return [self.playlist_result(url_results, playlist_title = username)]
811
812 class YoutubeSearchIE(SearchInfoExtractor):
813     """Information Extractor for YouTube search queries."""
814     _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
815     _MAX_RESULTS = 1000
816     IE_NAME = u'youtube:search'
817     _SEARCH_KEY = 'ytsearch'
818
819     def report_download_page(self, query, pagenum):
820         """Report attempt to download search page with given number."""
821         self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
822
823     def _get_n_results(self, query, n):
824         """Get a specified number of results for a query"""
825
826         video_ids = []
827         pagenum = 0
828         limit = n
829
830         while (50 * pagenum) < limit:
831             self.report_download_page(query, pagenum+1)
832             result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
833             request = compat_urllib_request.Request(result_url)
834             try:
835                 data = compat_urllib_request.urlopen(request).read().decode('utf-8')
836             except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
837                 raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
838             api_response = json.loads(data)['data']
839
840             if not 'items' in api_response:
841                 raise ExtractorError(u'[youtube] No video results')
842
843             new_ids = list(video['id'] for video in api_response['items'])
844             video_ids += new_ids
845
846             limit = min(n, api_response['totalItems'])
847             pagenum += 1
848
849         if len(video_ids) > n:
850             video_ids = video_ids[:n]
851         videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
852         return self.playlist_result(videos, query)