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