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