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