Merge remote-tracking branch 'drags/yt-feed-loadmore'
[youtube-dl] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 import itertools
4 import json
5 import os.path
6 import re
7 import traceback
8
9 from .common import InfoExtractor, SearchInfoExtractor
10 from .subtitles import SubtitlesInfoExtractor
11 from ..jsinterp import JSInterpreter
12 from ..swfinterp import SWFInterpreter
13 from ..utils import (
14     compat_chr,
15     compat_parse_qs,
16     compat_urllib_parse,
17     compat_urllib_request,
18     compat_urlparse,
19     compat_str,
20
21     clean_html,
22     get_element_by_id,
23     get_element_by_attribute,
24     ExtractorError,
25     int_or_none,
26     PagedList,
27     unescapeHTML,
28     unified_strdate,
29     orderedSet,
30     uppercase_escape,
31 )
32
33 class YoutubeBaseInfoExtractor(InfoExtractor):
34     """Provide base functions for Youtube extractors"""
35     _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
36     _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
37     _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
38     _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
39     _NETRC_MACHINE = 'youtube'
40     # If True it will raise an error if no login info is provided
41     _LOGIN_REQUIRED = False
42
43     def _set_language(self):
44         return bool(self._download_webpage(
45             self._LANG_URL, None,
46             note=u'Setting language', errnote='unable to set language',
47             fatal=False))
48
49     def _login(self):
50         """
51         Attempt to log in to YouTube.
52         True is returned if successful or skipped.
53         False is returned if login failed.
54
55         If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
56         """
57         (username, password) = self._get_login_info()
58         # No authentication to be performed
59         if username is None:
60             if self._LOGIN_REQUIRED:
61                 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
62             return True
63
64         login_page = self._download_webpage(
65             self._LOGIN_URL, None,
66             note=u'Downloading login page',
67             errnote=u'unable to fetch login page', fatal=False)
68         if login_page is False:
69             return
70
71         galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
72                                   login_page, u'Login GALX parameter')
73
74         # Log in
75         login_form_strs = {
76                 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
77                 u'Email': username,
78                 u'GALX': galx,
79                 u'Passwd': password,
80
81                 u'PersistentCookie': u'yes',
82                 u'_utf8': u'霱',
83                 u'bgresponse': u'js_disabled',
84                 u'checkConnection': u'',
85                 u'checkedDomains': u'youtube',
86                 u'dnConn': u'',
87                 u'pstMsg': u'0',
88                 u'rmShown': u'1',
89                 u'secTok': u'',
90                 u'signIn': u'Sign in',
91                 u'timeStmp': u'',
92                 u'service': u'youtube',
93                 u'uilel': u'3',
94                 u'hl': u'en_US',
95         }
96
97         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
98         # chokes on unicode
99         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
100         login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
101
102         req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
103         login_results = self._download_webpage(
104             req, None,
105             note=u'Logging in', errnote=u'unable to log in', fatal=False)
106         if login_results is False:
107             return False
108
109         if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
110             raise ExtractorError(u'Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
111
112         # Two-Factor
113         # TODO add SMS and phone call support - these require making a request and then prompting the user
114
115         if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
116             tfa_code = self._get_tfa_info()
117
118             if tfa_code is None:
119                 self._downloader.report_warning(u'Two-factor authentication required. Provide it with --twofactor <code>')
120                 self._downloader.report_warning(u'(Note that only TOTP (Google Authenticator App) codes work at this time.)')
121                 return False
122
123             # Unlike the first login form, secTok and timeStmp are both required for the TFA form
124
125             match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
126             if match is None:
127                 self._downloader.report_warning(u'Failed to get secTok - did the page structure change?')
128             secTok = match.group(1)
129             match = re.search(r'id="timeStmp"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
130             if match is None:
131                 self._downloader.report_warning(u'Failed to get timeStmp - did the page structure change?')
132             timeStmp = match.group(1)
133
134             tfa_form_strs = {
135                 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
136                 u'smsToken': u'',
137                 u'smsUserPin': tfa_code,
138                 u'smsVerifyPin': u'Verify',
139
140                 u'PersistentCookie': u'yes',
141                 u'checkConnection': u'',
142                 u'checkedDomains': u'youtube',
143                 u'pstMsg': u'1',
144                 u'secTok': secTok,
145                 u'timeStmp': timeStmp,
146                 u'service': u'youtube',
147                 u'hl': u'en_US',
148             }
149             tfa_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in tfa_form_strs.items())
150             tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii')
151
152             tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
153             tfa_results = self._download_webpage(
154                 tfa_req, None,
155                 note=u'Submitting TFA code', errnote=u'unable to submit tfa', fatal=False)
156
157             if tfa_results is False:
158                 return False
159
160             if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', tfa_results) is not None:
161                 self._downloader.report_warning(u'Two-factor code expired. Please try again, or use a one-use backup code instead.')
162                 return False
163             if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
164                 self._downloader.report_warning(u'unable to log in - did the page structure change?')
165                 return False
166             if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
167                 self._downloader.report_warning(u'Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
168                 return False
169
170         if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
171             self._downloader.report_warning(u'unable to log in: bad username or password')
172             return False
173         return True
174
175     def _confirm_age(self):
176         age_form = {
177             'next_url': '/',
178             'action_confirm': 'Confirm',
179         }
180         req = compat_urllib_request.Request(self._AGE_URL,
181             compat_urllib_parse.urlencode(age_form).encode('ascii'))
182
183         self._download_webpage(
184             req, None,
185             note=u'Confirming age', errnote=u'Unable to confirm age')
186         return True
187
188     def _real_initialize(self):
189         if self._downloader is None:
190             return
191         if not self._set_language():
192             return
193         if not self._login():
194             return
195         self._confirm_age()
196
197
198 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
199     IE_DESC = u'YouTube.com'
200     _VALID_URL = r"""(?x)^
201                      (
202                          (?:https?://|//)                                    # http(s):// or protocol-independent URL
203                          (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
204                             (?:www\.)?deturl\.com/www\.youtube\.com/|
205                             (?:www\.)?pwnyoutube\.com/|
206                             (?:www\.)?yourepeat\.com/|
207                             tube\.majestyc\.net/|
208                             youtube\.googleapis\.com/)                        # the various hostnames, with wildcard subdomains
209                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
210                          (?:                                                  # the various things that can precede the ID:
211                              (?:(?:v|embed|e)/)                               # v/ or embed/ or e/
212                              |(?:                                             # or the v= param in all its forms
213                                  (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)?  # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
214                                  (?:\?|\#!?)                                  # the params delimiter ? or # or #!
215                                  (?:.*?&)?                                    # any other preceding param (like /?s=tuff&v=xxxx)
216                                  v=
217                              )
218                          ))
219                          |youtu\.be/                                          # just youtu.be/xxxx
220                          |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
221                          )
222                      )?                                                       # all until now is optional -> you can pass the naked ID
223                      ([0-9A-Za-z_-]{11})                                      # here is it! the YouTube video ID
224                      (?(1).+)?                                                # if we found the ID, everything can follow
225                      $"""
226     _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
227     _formats = {
228         '5': {'ext': 'flv', 'width': 400, 'height': 240},
229         '6': {'ext': 'flv', 'width': 450, 'height': 270},
230         '13': {'ext': '3gp'},
231         '17': {'ext': '3gp', 'width': 176, 'height': 144},
232         '18': {'ext': 'mp4', 'width': 640, 'height': 360},
233         '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
234         '34': {'ext': 'flv', 'width': 640, 'height': 360},
235         '35': {'ext': 'flv', 'width': 854, 'height': 480},
236         '36': {'ext': '3gp', 'width': 320, 'height': 240},
237         '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
238         '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
239         '43': {'ext': 'webm', 'width': 640, 'height': 360},
240         '44': {'ext': 'webm', 'width': 854, 'height': 480},
241         '45': {'ext': 'webm', 'width': 1280, 'height': 720},
242         '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
243
244
245         # 3d videos
246         '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
247         '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
248         '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
249         '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
250         '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
251         '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
252         '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
253
254         # Apple HTTP Live Streaming
255         '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
256         '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
257         '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
258         '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
259         '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
260         '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
261         '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
262
263         # DASH mp4 video
264         '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
265         '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
266         '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
267         '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
268         '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
269         '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
270         '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
271         '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
272
273         # Dash mp4 audio
274         '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
275         '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
276         '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
277
278         # Dash webm
279         '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
280         '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
281         '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
282         '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
283         '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
284         '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
285         '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
286         '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
287         '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
288         '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
289         '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
290         '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
291         '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
292         '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
293         '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
294
295         # Dash webm audio
296         '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
297         '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
298
299         # RTMP (unnamed)
300         '_rtmp': {'protocol': 'rtmp'},
301     }
302
303     IE_NAME = u'youtube'
304     _TESTS = [
305         {
306             u"url":  u"http://www.youtube.com/watch?v=BaW_jenozKc",
307             u"file":  u"BaW_jenozKc.mp4",
308             u"info_dict": {
309                 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
310                 u"uploader": u"Philipp Hagemeister",
311                 u"uploader_id": u"phihag",
312                 u"upload_date": u"20121002",
313                 u"description": u"test chars:  \"'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .",
314                 u"categories": [u'Science & Technology'],
315                 'like_count': int,
316                 'dislike_count': int,
317             }
318         },
319         {
320             u"url":  u"http://www.youtube.com/watch?v=UxxajLWwzqY",
321             u"file":  u"UxxajLWwzqY.mp4",
322             u"note": u"Test generic use_cipher_signature video (#897)",
323             u"info_dict": {
324                 u"upload_date": u"20120506",
325                 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
326                 u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
327                 u"uploader": u"Icona Pop",
328                 u"uploader_id": u"IconaPop"
329             }
330         },
331         {
332             u"url":  u"https://www.youtube.com/watch?v=07FYdnEawAQ",
333             u"file":  u"07FYdnEawAQ.mp4",
334             u"note": u"Test VEVO video with age protection (#956)",
335             u"info_dict": {
336                 u"upload_date": u"20130703",
337                 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
338                 u"description": u"md5:64249768eec3bc4276236606ea996373",
339                 u"uploader": u"justintimberlakeVEVO",
340                 u"uploader_id": u"justintimberlakeVEVO"
341             }
342         },
343         {
344             u"url":  u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
345             u"file":  u"yZIXLfi8CZQ.mp4",
346             u"note": u"Embed-only video (#1746)",
347             u"info_dict": {
348                 u"upload_date": u"20120608",
349                 u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
350                 u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
351                 u"uploader": u"SET India",
352                 u"uploader_id": u"setindia"
353             }
354         },
355         {
356             u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
357             u"file": u"a9LDPn-MO4I.m4a",
358             u"note": u"256k DASH audio (format 141) via DASH manifest",
359             u"info_dict": {
360                 u"upload_date": "20121002",
361                 u"uploader_id": "8KVIDEO",
362                 u"description": "No description available.",
363                 u"uploader": "8KVIDEO",
364                 u"title": "UHDTV TEST 8K VIDEO.mp4"
365             },
366             u"params": {
367                 u"youtube_include_dash_manifest": True,
368                 u"format": "141",
369             },
370         },
371         # DASH manifest with encrypted signature
372         {
373             u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
374             u'info_dict': {
375                 u'id': u'IB3lcPjvWLA',
376                 u'ext': u'm4a',
377                 u'title': u'Afrojack - The Spark ft. Spree Wilson',
378                 u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
379                 u'uploader': u'AfrojackVEVO',
380                 u'uploader_id': u'AfrojackVEVO',
381                 u'upload_date': u'20131011',
382             },
383             u"params": {
384                 u'youtube_include_dash_manifest': True,
385                 u'format': '141',
386             },
387         },
388     ]
389
390
391     @classmethod
392     def suitable(cls, url):
393         """Receives a URL and returns True if suitable for this IE."""
394         if YoutubePlaylistIE.suitable(url): return False
395         return re.match(cls._VALID_URL, url) is not None
396
397     def __init__(self, *args, **kwargs):
398         super(YoutubeIE, self).__init__(*args, **kwargs)
399         self._player_cache = {}
400
401     def report_video_info_webpage_download(self, video_id):
402         """Report attempt to download video info webpage."""
403         self.to_screen(u'%s: Downloading video info webpage' % video_id)
404
405     def report_information_extraction(self, video_id):
406         """Report attempt to extract video information."""
407         self.to_screen(u'%s: Extracting video information' % video_id)
408
409     def report_unavailable_format(self, video_id, format):
410         """Report extracted video URL."""
411         self.to_screen(u'%s: Format %s not available' % (video_id, format))
412
413     def report_rtmp_download(self):
414         """Indicate the download will use the RTMP protocol."""
415         self.to_screen(u'RTMP download detected')
416
417     def _signature_cache_id(self, example_sig):
418         """ Return a string representation of a signature """
419         return u'.'.join(compat_str(len(part)) for part in example_sig.split('.'))
420
421     def _extract_signature_function(self, video_id, player_url, example_sig):
422         id_m = re.match(
423             r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
424             player_url)
425         if not id_m:
426             raise ExtractorError('Cannot identify player %r' % player_url)
427         player_type = id_m.group('ext')
428         player_id = id_m.group('id')
429
430         # Read from filesystem cache
431         func_id = '%s_%s_%s' % (
432             player_type, player_id, self._signature_cache_id(example_sig))
433         assert os.path.basename(func_id) == func_id
434
435         cache_spec = self._downloader.cache.load(u'youtube-sigfuncs', func_id)
436         if cache_spec is not None:
437             return lambda s: u''.join(s[i] for i in cache_spec)
438
439         if player_type == 'js':
440             code = self._download_webpage(
441                 player_url, video_id,
442                 note=u'Downloading %s player %s' % (player_type, player_id),
443                 errnote=u'Download of %s failed' % player_url)
444             res = self._parse_sig_js(code)
445         elif player_type == 'swf':
446             urlh = self._request_webpage(
447                 player_url, video_id,
448                 note=u'Downloading %s player %s' % (player_type, player_id),
449                 errnote=u'Download of %s failed' % player_url)
450             code = urlh.read()
451             res = self._parse_sig_swf(code)
452         else:
453             assert False, 'Invalid player type %r' % player_type
454
455         if cache_spec is None:
456             test_string = u''.join(map(compat_chr, range(len(example_sig))))
457             cache_res = res(test_string)
458             cache_spec = [ord(c) for c in cache_res]
459
460         self._downloader.cache.store(u'youtube-sigfuncs', func_id, cache_spec)
461         return res
462
463     def _print_sig_code(self, func, example_sig):
464         def gen_sig_code(idxs):
465             def _genslice(start, end, step):
466                 starts = u'' if start == 0 else str(start)
467                 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
468                 steps = u'' if step == 1 else (u':%d' % step)
469                 return u's[%s%s%s]' % (starts, ends, steps)
470
471             step = None
472             start = '(Never used)'  # Quelch pyflakes warnings - start will be
473                                     # set as soon as step is set
474             for i, prev in zip(idxs[1:], idxs[:-1]):
475                 if step is not None:
476                     if i - prev == step:
477                         continue
478                     yield _genslice(start, prev, step)
479                     step = None
480                     continue
481                 if i - prev in [-1, 1]:
482                     step = i - prev
483                     start = prev
484                     continue
485                 else:
486                     yield u's[%d]' % prev
487             if step is None:
488                 yield u's[%d]' % i
489             else:
490                 yield _genslice(start, i, step)
491
492         test_string = u''.join(map(compat_chr, range(len(example_sig))))
493         cache_res = func(test_string)
494         cache_spec = [ord(c) for c in cache_res]
495         expr_code = u' + '.join(gen_sig_code(cache_spec))
496         signature_id_tuple = '(%s)' % (
497             ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
498         code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
499                 u'    return %s\n') % (signature_id_tuple, expr_code)
500         self.to_screen(u'Extracted signature function:\n' + code)
501
502     def _parse_sig_js(self, jscode):
503         funcname = self._search_regex(
504             r'signature=([$a-zA-Z]+)', jscode,
505              u'Initial JS player signature function name')
506
507         jsi = JSInterpreter(jscode)
508         initial_function = jsi.extract_function(funcname)
509         return lambda s: initial_function([s])
510
511     def _parse_sig_swf(self, file_contents):
512         swfi = SWFInterpreter(file_contents)
513         TARGET_CLASSNAME = u'SignatureDecipher'
514         searched_class = swfi.extract_class(TARGET_CLASSNAME)
515         initial_function = swfi.extract_function(searched_class, u'decipher')
516         return lambda s: initial_function([s])
517
518     def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
519         """Turn the encrypted s field into a working signature"""
520
521         if player_url is None:
522             raise ExtractorError(u'Cannot decrypt signature without player_url')
523
524         if player_url.startswith(u'//'):
525             player_url = u'https:' + player_url
526         try:
527             player_id = (player_url, self._signature_cache_id(s))
528             if player_id not in self._player_cache:
529                 func = self._extract_signature_function(
530                     video_id, player_url, s
531                 )
532                 self._player_cache[player_id] = func
533             func = self._player_cache[player_id]
534             if self._downloader.params.get('youtube_print_sig_code'):
535                 self._print_sig_code(func, s)
536             return func(s)
537         except Exception as e:
538             tb = traceback.format_exc()
539             raise ExtractorError(
540                 u'Signature extraction failed: ' + tb, cause=e)
541
542     def _get_available_subtitles(self, video_id, webpage):
543         try:
544             sub_list = self._download_webpage(
545                 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
546                 video_id, note=False)
547         except ExtractorError as err:
548             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
549             return {}
550         lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
551
552         sub_lang_list = {}
553         for l in lang_list:
554             lang = l[1]
555             if lang in sub_lang_list:
556                 continue
557             params = compat_urllib_parse.urlencode({
558                 'lang': lang,
559                 'v': video_id,
560                 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
561                 'name': unescapeHTML(l[0]).encode('utf-8'),
562             })
563             url = u'https://www.youtube.com/api/timedtext?' + params
564             sub_lang_list[lang] = url
565         if not sub_lang_list:
566             self._downloader.report_warning(u'video doesn\'t have subtitles')
567             return {}
568         return sub_lang_list
569
570     def _get_available_automatic_caption(self, video_id, webpage):
571         """We need the webpage for getting the captions url, pass it as an
572            argument to speed up the process."""
573         sub_format = self._downloader.params.get('subtitlesformat', 'srt')
574         self.to_screen(u'%s: Looking for automatic captions' % video_id)
575         mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
576         err_msg = u'Couldn\'t find automatic captions for %s' % video_id
577         if mobj is None:
578             self._downloader.report_warning(err_msg)
579             return {}
580         player_config = json.loads(mobj.group(1))
581         try:
582             args = player_config[u'args']
583             caption_url = args[u'ttsurl']
584             timestamp = args[u'timestamp']
585             # We get the available subtitles
586             list_params = compat_urllib_parse.urlencode({
587                 'type': 'list',
588                 'tlangs': 1,
589                 'asrs': 1,
590             })
591             list_url = caption_url + '&' + list_params
592             caption_list = self._download_xml(list_url, video_id)
593             original_lang_node = caption_list.find('track')
594             if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
595                 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
596                 return {}
597             original_lang = original_lang_node.attrib['lang_code']
598
599             sub_lang_list = {}
600             for lang_node in caption_list.findall('target'):
601                 sub_lang = lang_node.attrib['lang_code']
602                 params = compat_urllib_parse.urlencode({
603                     'lang': original_lang,
604                     'tlang': sub_lang,
605                     'fmt': sub_format,
606                     'ts': timestamp,
607                     'kind': 'asr',
608                 })
609                 sub_lang_list[sub_lang] = caption_url + '&' + params
610             return sub_lang_list
611         # An extractor error can be raise by the download process if there are
612         # no automatic captions but there are subtitles
613         except (KeyError, ExtractorError):
614             self._downloader.report_warning(err_msg)
615             return {}
616
617     @classmethod
618     def extract_id(cls, url):
619         mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
620         if mobj is None:
621             raise ExtractorError(u'Invalid URL: %s' % url)
622         video_id = mobj.group(2)
623         return video_id
624
625     def _extract_from_m3u8(self, manifest_url, video_id):
626         url_map = {}
627         def _get_urls(_manifest):
628             lines = _manifest.split('\n')
629             urls = filter(lambda l: l and not l.startswith('#'),
630                             lines)
631             return urls
632         manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
633         formats_urls = _get_urls(manifest)
634         for format_url in formats_urls:
635             itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
636             url_map[itag] = format_url
637         return url_map
638
639     def _extract_annotations(self, video_id):
640         url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
641         return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
642
643     def _real_extract(self, url):
644         proto = (
645             u'http' if self._downloader.params.get('prefer_insecure', False)
646             else u'https')
647
648         # Extract original video URL from URL with redirection, like age verification, using next_url parameter
649         mobj = re.search(self._NEXT_URL_RE, url)
650         if mobj:
651             url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
652         video_id = self.extract_id(url)
653
654         # Get video webpage
655         url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
656         video_webpage = self._download_webpage(url, video_id)
657
658         # Attempt to extract SWF player URL
659         mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
660         if mobj is not None:
661             player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
662         else:
663             player_url = None
664
665         # Get video info
666         self.report_video_info_webpage_download(video_id)
667         if re.search(r'player-age-gate-content">', video_webpage) is not None:
668             self.report_age_confirmation()
669             age_gate = True
670             # We simulate the access to the video from www.youtube.com/v/{video_id}
671             # this can be viewed without login into Youtube
672             data = compat_urllib_parse.urlencode({
673                 'video_id': video_id,
674                 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
675                 'sts': self._search_regex(
676                     r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
677             })
678             video_info_url = proto + '://www.youtube.com/get_video_info?' + data
679             video_info_webpage = self._download_webpage(video_info_url, video_id,
680                                     note=False,
681                                     errnote='unable to download video info webpage')
682             video_info = compat_parse_qs(video_info_webpage)
683         else:
684             age_gate = False
685             for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
686                 video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
687                         % (video_id, el_type))
688                 video_info_webpage = self._download_webpage(video_info_url, video_id,
689                                         note=False,
690                                         errnote='unable to download video info webpage')
691                 video_info = compat_parse_qs(video_info_webpage)
692                 if 'token' in video_info:
693                     break
694         if 'token' not in video_info:
695             if 'reason' in video_info:
696                 raise ExtractorError(
697                     u'YouTube said: %s' % video_info['reason'][0],
698                     expected=True, video_id=video_id)
699             else:
700                 raise ExtractorError(
701                     u'"token" parameter not in video info for unknown reason',
702                     video_id=video_id)
703
704         if 'view_count' in video_info:
705             view_count = int(video_info['view_count'][0])
706         else:
707             view_count = None
708
709         # Check for "rental" videos
710         if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
711             raise ExtractorError(u'"rental" videos not supported')
712
713         # Start extracting information
714         self.report_information_extraction(video_id)
715
716         # uploader
717         if 'author' not in video_info:
718             raise ExtractorError(u'Unable to extract uploader name')
719         video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
720
721         # uploader_id
722         video_uploader_id = None
723         mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
724         if mobj is not None:
725             video_uploader_id = mobj.group(1)
726         else:
727             self._downloader.report_warning(u'unable to extract uploader nickname')
728
729         # title
730         if 'title' in video_info:
731             video_title = video_info['title'][0]
732         else:
733             self._downloader.report_warning(u'Unable to extract video title')
734             video_title = u'_'
735
736         # thumbnail image
737         # We try first to get a high quality image:
738         m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
739                             video_webpage, re.DOTALL)
740         if m_thumb is not None:
741             video_thumbnail = m_thumb.group(1)
742         elif 'thumbnail_url' not in video_info:
743             self._downloader.report_warning(u'unable to extract video thumbnail')
744             video_thumbnail = None
745         else:   # don't panic if we can't find it
746             video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
747
748         # upload date
749         upload_date = None
750         mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
751         if mobj is None:
752             mobj = re.search(
753                 r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
754                 video_webpage)
755         if mobj is not None:
756             upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
757             upload_date = unified_strdate(upload_date)
758
759         m_cat_container = self._search_regex(
760             r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
761             video_webpage, 'categories', fatal=False)
762         if m_cat_container:
763             category = self._html_search_regex(
764                 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
765                 default=None)
766             video_categories = None if category is None else [category]
767         else:
768             video_categories = None
769
770         # description
771         video_description = get_element_by_id("eow-description", video_webpage)
772         if video_description:
773             video_description = re.sub(r'''(?x)
774                 <a\s+
775                     (?:[a-zA-Z-]+="[^"]+"\s+)*?
776                     title="([^"]+)"\s+
777                     (?:[a-zA-Z-]+="[^"]+"\s+)*?
778                     class="yt-uix-redirect-link"\s*>
779                 [^<]+
780                 </a>
781             ''', r'\1', video_description)
782             video_description = clean_html(video_description)
783         else:
784             fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
785             if fd_mobj:
786                 video_description = unescapeHTML(fd_mobj.group(1))
787             else:
788                 video_description = u''
789
790         def _extract_count(count_name):
791             count = self._search_regex(
792                 r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
793                 video_webpage, count_name, default=None)
794             if count is not None:
795                 return int(count.replace(',', ''))
796             return None
797         like_count = _extract_count(u'like')
798         dislike_count = _extract_count(u'dislike')
799
800         # subtitles
801         video_subtitles = self.extract_subtitles(video_id, video_webpage)
802
803         if self._downloader.params.get('listsubtitles', False):
804             self._list_available_subtitles(video_id, video_webpage)
805             return
806
807         if 'length_seconds' not in video_info:
808             self._downloader.report_warning(u'unable to extract video duration')
809             video_duration = None
810         else:
811             video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
812
813         # annotations
814         video_annotations = None
815         if self._downloader.params.get('writeannotations', False):
816                 video_annotations = self._extract_annotations(video_id)
817
818         # Decide which formats to download
819         try:
820             mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
821             if not mobj:
822                 raise ValueError('Could not find vevo ID')
823             json_code = uppercase_escape(mobj.group(1))
824             ytplayer_config = json.loads(json_code)
825             args = ytplayer_config['args']
826             # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
827             # this signatures are encrypted
828             if 'url_encoded_fmt_stream_map' not in args:
829                 raise ValueError(u'No stream_map present')  # caught below
830             re_signature = re.compile(r'[&,]s=')
831             m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
832             if m_s is not None:
833                 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
834                 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
835             m_s = re_signature.search(args.get('adaptive_fmts', u''))
836             if m_s is not None:
837                 if 'adaptive_fmts' in video_info:
838                     video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
839                 else:
840                     video_info['adaptive_fmts'] = [args['adaptive_fmts']]
841         except ValueError:
842             pass
843
844         def _map_to_format_list(urlmap):
845             formats = []
846             for itag, video_real_url in urlmap.items():
847                 dct = {
848                     'format_id': itag,
849                     'url': video_real_url,
850                     'player_url': player_url,
851                 }
852                 if itag in self._formats:
853                     dct.update(self._formats[itag])
854                 formats.append(dct)
855             return formats
856
857         if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
858             self.report_rtmp_download()
859             formats = [{
860                 'format_id': '_rtmp',
861                 'protocol': 'rtmp',
862                 'url': video_info['conn'][0],
863                 'player_url': player_url,
864             }]
865         elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
866             encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
867             if 'rtmpe%3Dyes' in encoded_url_map:
868                 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
869             url_map = {}
870             for url_data_str in encoded_url_map.split(','):
871                 url_data = compat_parse_qs(url_data_str)
872                 if 'itag' not in url_data or 'url' not in url_data:
873                     continue
874                 format_id = url_data['itag'][0]
875                 url = url_data['url'][0]
876
877                 if 'sig' in url_data:
878                     url += '&signature=' + url_data['sig'][0]
879                 elif 's' in url_data:
880                     encrypted_sig = url_data['s'][0]
881
882                     if not age_gate:
883                         jsplayer_url_json = self._search_regex(
884                             r'"assets":.+?"js":\s*("[^"]+")',
885                             video_webpage, u'JS player URL')
886                         player_url = json.loads(jsplayer_url_json)
887                     if player_url is None:
888                         player_url_json = self._search_regex(
889                             r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
890                             video_webpage, u'age gate player URL')
891                         player_url = json.loads(player_url_json)
892
893                     if self._downloader.params.get('verbose'):
894                         if player_url is None:
895                             player_version = 'unknown'
896                             player_desc = 'unknown'
897                         else:
898                             if player_url.endswith('swf'):
899                                 player_version = self._search_regex(
900                                     r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
901                                     u'flash player', fatal=False)
902                                 player_desc = 'flash player %s' % player_version
903                             else:
904                                 player_version = self._search_regex(
905                                     r'html5player-([^/]+?)(?:/html5player)?\.js',
906                                     player_url,
907                                     'html5 player', fatal=False)
908                                 player_desc = u'html5 player %s' % player_version
909
910                         parts_sizes = self._signature_cache_id(encrypted_sig)
911                         self.to_screen(u'{%s} signature length %s, %s' %
912                             (format_id, parts_sizes, player_desc))
913
914                     signature = self._decrypt_signature(
915                         encrypted_sig, video_id, player_url, age_gate)
916                     url += '&signature=' + signature
917                 if 'ratebypass' not in url:
918                     url += '&ratebypass=yes'
919                 url_map[format_id] = url
920             formats = _map_to_format_list(url_map)
921         elif video_info.get('hlsvp'):
922             manifest_url = video_info['hlsvp'][0]
923             url_map = self._extract_from_m3u8(manifest_url, video_id)
924             formats = _map_to_format_list(url_map)
925         else:
926             raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
927
928         # Look for the DASH manifest
929         if (self._downloader.params.get('youtube_include_dash_manifest', False)):
930             try:
931                 # The DASH manifest used needs to be the one from the original video_webpage.
932                 # The one found in get_video_info seems to be using different signatures.
933                 # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
934                 # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
935                 # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
936                 if age_gate:
937                     dash_manifest_url = video_info.get('dashmpd')[0]
938                 else:
939                     dash_manifest_url = ytplayer_config['args']['dashmpd']
940                 def decrypt_sig(mobj):
941                     s = mobj.group(1)
942                     dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
943                     return '/signature/%s' % dec_s
944                 dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
945                 dash_doc = self._download_xml(
946                     dash_manifest_url, video_id,
947                     note=u'Downloading DASH manifest',
948                     errnote=u'Could not download DASH manifest')
949                 for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
950                     url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
951                     if url_el is None:
952                         continue
953                     format_id = r.attrib['id']
954                     video_url = url_el.text
955                     filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
956                     f = {
957                         'format_id': format_id,
958                         'url': video_url,
959                         'width': int_or_none(r.attrib.get('width')),
960                         'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
961                         'asr': int_or_none(r.attrib.get('audioSamplingRate')),
962                         'filesize': filesize,
963                     }
964                     try:
965                         existing_format = next(
966                             fo for fo in formats
967                             if fo['format_id'] == format_id)
968                     except StopIteration:
969                         f.update(self._formats.get(format_id, {}))
970                         formats.append(f)
971                     else:
972                         existing_format.update(f)
973
974             except (ExtractorError, KeyError) as e:
975                 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
976
977         self._sort_formats(formats)
978
979         return {
980             'id':           video_id,
981             'uploader':     video_uploader,
982             'uploader_id':  video_uploader_id,
983             'upload_date':  upload_date,
984             'title':        video_title,
985             'thumbnail':    video_thumbnail,
986             'description':  video_description,
987             'categories':   video_categories,
988             'subtitles':    video_subtitles,
989             'duration':     video_duration,
990             'age_limit':    18 if age_gate else 0,
991             'annotations':  video_annotations,
992             'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
993             'view_count':   view_count,
994             'like_count': like_count,
995             'dislike_count': dislike_count,
996             'formats':      formats,
997         }
998
999 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
1000     IE_DESC = u'YouTube.com playlists'
1001     _VALID_URL = r"""(?x)(?:
1002                         (?:https?://)?
1003                         (?:\w+\.)?
1004                         youtube\.com/
1005                         (?:
1006                            (?:course|view_play_list|my_playlists|artist|playlist|watch)
1007                            \? (?:.*?&)*? (?:p|a|list)=
1008                         |  p/
1009                         )
1010                         (
1011                             (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
1012                             # Top tracks, they can also include dots 
1013                             |(?:MC)[\w\.]*
1014                         )
1015                         .*
1016                      |
1017                         ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
1018                      )"""
1019     _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
1020     _MORE_PAGES_INDICATOR = r'data-link-type="next"'
1021     _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
1022     IE_NAME = u'youtube:playlist'
1023
1024     def _real_initialize(self):
1025         self._login()
1026
1027     def _ids_to_results(self, ids):
1028         return [
1029             self.url_result(vid_id, 'Youtube', video_id=vid_id)
1030             for vid_id in ids]
1031
1032     def _extract_mix(self, playlist_id):
1033         # The mixes are generated from a a single video
1034         # the id of the playlist is just 'RD' + video_id
1035         url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
1036         webpage = self._download_webpage(
1037             url, playlist_id, u'Downloading Youtube mix')
1038         search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
1039         title_span = (
1040             search_title('playlist-title') or
1041             search_title('title long-title') or
1042             search_title('title'))
1043         title = clean_html(title_span)
1044         ids = orderedSet(re.findall(
1045             r'''(?xs)data-video-username=".*?".*?
1046                        href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
1047             webpage))
1048         url_results = self._ids_to_results(ids)
1049
1050         return self.playlist_result(url_results, playlist_id, title)
1051
1052     def _real_extract(self, url):
1053         # Extract playlist id
1054         mobj = re.match(self._VALID_URL, url)
1055         if mobj is None:
1056             raise ExtractorError(u'Invalid URL: %s' % url)
1057         playlist_id = mobj.group(1) or mobj.group(2)
1058
1059         # Check if it's a video-specific URL
1060         query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
1061         if 'v' in query_dict:
1062             video_id = query_dict['v'][0]
1063             if self._downloader.params.get('noplaylist'):
1064                 self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
1065                 return self.url_result(video_id, 'Youtube', video_id=video_id)
1066             else:
1067                 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1068
1069         if playlist_id.startswith('RD'):
1070             # Mixes require a custom extraction process
1071             return self._extract_mix(playlist_id)
1072         if playlist_id.startswith('TL'):
1073             raise ExtractorError(u'For downloading YouTube.com top lists, use '
1074                 u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
1075
1076         url = self._TEMPLATE_URL % playlist_id
1077         page = self._download_webpage(url, playlist_id)
1078         more_widget_html = content_html = page
1079
1080         # Check if the playlist exists or is private
1081         if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
1082             raise ExtractorError(
1083                 u'The playlist doesn\'t exist or is private, use --username or '
1084                 '--netrc to access it.',
1085                 expected=True)
1086
1087         # Extract the video ids from the playlist pages
1088         ids = []
1089
1090         for page_num in itertools.count(1):
1091             matches = re.finditer(self._VIDEO_RE, content_html)
1092             # We remove the duplicates and the link with index 0
1093             # (it's not the first video of the playlist)
1094             new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
1095             ids.extend(new_ids)
1096
1097             mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1098             if not mobj:
1099                 break
1100
1101             more = self._download_json(
1102                 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
1103                 'Downloading page #%s' % page_num,
1104                 transform_source=uppercase_escape)
1105             content_html = more['content_html']
1106             more_widget_html = more['load_more_widget_html']
1107
1108         playlist_title = self._html_search_regex(
1109             r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1110             page, u'title')
1111
1112         url_results = self._ids_to_results(ids)
1113         return self.playlist_result(url_results, playlist_id, playlist_title)
1114
1115
1116 class YoutubeTopListIE(YoutubePlaylistIE):
1117     IE_NAME = u'youtube:toplist'
1118     IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1119         u' (Example: "yttoplist:music:Top Tracks")')
1120     _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1121
1122     def _real_extract(self, url):
1123         mobj = re.match(self._VALID_URL, url)
1124         channel = mobj.group('chann')
1125         title = mobj.group('title')
1126         query = compat_urllib_parse.urlencode({'title': title})
1127         playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
1128         channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
1129         link = self._html_search_regex(playlist_re, channel_page, u'list')
1130         url = compat_urlparse.urljoin('https://www.youtube.com/', link)
1131         
1132         video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1133         ids = []
1134         # sometimes the webpage doesn't contain the videos
1135         # retry until we get them
1136         for i in itertools.count(0):
1137             msg = u'Downloading Youtube mix'
1138             if i > 0:
1139                 msg += ', retry #%d' % i
1140
1141             webpage = self._download_webpage(url, title, msg)
1142             ids = orderedSet(re.findall(video_re, webpage))
1143             if ids:
1144                 break
1145         url_results = self._ids_to_results(ids)
1146         return self.playlist_result(url_results, playlist_title=title)
1147
1148
1149 class YoutubeChannelIE(InfoExtractor):
1150     IE_DESC = u'YouTube.com channels'
1151     _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1152     _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
1153     _MORE_PAGES_URL = 'https://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
1154     IE_NAME = u'youtube:channel'
1155
1156     def extract_videos_from_page(self, page):
1157         ids_in_page = []
1158         for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
1159             if mobj.group(1) not in ids_in_page:
1160                 ids_in_page.append(mobj.group(1))
1161         return ids_in_page
1162
1163     def _real_extract(self, url):
1164         # Extract channel id
1165         mobj = re.match(self._VALID_URL, url)
1166         if mobj is None:
1167             raise ExtractorError(u'Invalid URL: %s' % url)
1168
1169         # Download channel page
1170         channel_id = mobj.group(1)
1171         video_ids = []
1172         url = 'https://www.youtube.com/channel/%s/videos' % channel_id
1173         channel_page = self._download_webpage(url, channel_id)
1174         autogenerated = re.search(r'''(?x)
1175                 class="[^"]*?(?:
1176                     channel-header-autogenerated-label|
1177                     yt-channel-title-autogenerated
1178                 )[^"]*"''', channel_page) is not None
1179
1180         if autogenerated:
1181             # The videos are contained in a single page
1182             # the ajax pages can't be used, they are empty
1183             video_ids = self.extract_videos_from_page(channel_page)
1184         else:
1185             # Download all channel pages using the json-based channel_ajax query
1186             for pagenum in itertools.count(1):
1187                 url = self._MORE_PAGES_URL % (pagenum, channel_id)
1188                 page = self._download_json(
1189                     url, channel_id, note=u'Downloading page #%s' % pagenum,
1190                     transform_source=uppercase_escape)
1191
1192                 ids_in_page = self.extract_videos_from_page(page['content_html'])
1193                 video_ids.extend(ids_in_page)
1194     
1195                 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1196                     break
1197
1198         self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1199
1200         url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
1201                        for video_id in video_ids]
1202         return self.playlist_result(url_entries, channel_id)
1203
1204
1205 class YoutubeUserIE(InfoExtractor):
1206     IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
1207     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1208     _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
1209     _GDATA_PAGE_SIZE = 50
1210     _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1211     IE_NAME = u'youtube:user'
1212
1213     @classmethod
1214     def suitable(cls, url):
1215         # Don't return True if the url can be extracted with other youtube
1216         # extractor, the regex would is too permissive and it would match.
1217         other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
1218         if any(ie.suitable(url) for ie in other_ies): return False
1219         else: return super(YoutubeUserIE, cls).suitable(url)
1220
1221     def _real_extract(self, url):
1222         # Extract username
1223         mobj = re.match(self._VALID_URL, url)
1224         if mobj is None:
1225             raise ExtractorError(u'Invalid URL: %s' % url)
1226
1227         username = mobj.group(1)
1228
1229         # Download video ids using YouTube Data API. Result size per
1230         # query is limited (currently to 50 videos) so we need to query
1231         # page by page until there are no video ids - it means we got
1232         # all of them.
1233
1234         def download_page(pagenum):
1235             start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1236
1237             gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
1238             page = self._download_webpage(
1239                 gdata_url, username,
1240                 u'Downloading video ids from %d to %d' % (
1241                     start_index, start_index + self._GDATA_PAGE_SIZE))
1242
1243             try:
1244                 response = json.loads(page)
1245             except ValueError as err:
1246                 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
1247             if 'entry' not in response['feed']:
1248                 return
1249
1250             # Extract video identifiers
1251             entries = response['feed']['entry']
1252             for entry in entries:
1253                 title = entry['title']['$t']
1254                 video_id = entry['id']['$t'].split('/')[-1]
1255                 yield {
1256                     '_type': 'url',
1257                     'url': video_id,
1258                     'ie_key': 'Youtube',
1259                     'id': video_id,
1260                     'title': title,
1261                 }
1262         url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
1263
1264         return self.playlist_result(url_results, playlist_title=username)
1265
1266
1267 class YoutubeSearchIE(SearchInfoExtractor):
1268     IE_DESC = u'YouTube.com searches'
1269     _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1270     _MAX_RESULTS = 1000
1271     IE_NAME = u'youtube:search'
1272     _SEARCH_KEY = 'ytsearch'
1273
1274     def _get_n_results(self, query, n):
1275         """Get a specified number of results for a query"""
1276
1277         video_ids = []
1278         pagenum = 0
1279         limit = n
1280         PAGE_SIZE = 50
1281
1282         while (PAGE_SIZE * pagenum) < limit:
1283             result_url = self._API_URL % (
1284                 compat_urllib_parse.quote_plus(query.encode('utf-8')),
1285                 (PAGE_SIZE * pagenum) + 1)
1286             data_json = self._download_webpage(
1287                 result_url, video_id=u'query "%s"' % query,
1288                 note=u'Downloading page %s' % (pagenum + 1),
1289                 errnote=u'Unable to download API page')
1290             data = json.loads(data_json)
1291             api_response = data['data']
1292
1293             if 'items' not in api_response:
1294                 raise ExtractorError(
1295                     u'[youtube] No video results', expected=True)
1296
1297             new_ids = list(video['id'] for video in api_response['items'])
1298             video_ids += new_ids
1299
1300             limit = min(n, api_response['totalItems'])
1301             pagenum += 1
1302
1303         if len(video_ids) > n:
1304             video_ids = video_ids[:n]
1305         videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
1306                   for video_id in video_ids]
1307         return self.playlist_result(videos, query)
1308
1309
1310 class YoutubeSearchDateIE(YoutubeSearchIE):
1311     IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
1312     _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1313     _SEARCH_KEY = 'ytsearchdate'
1314     IE_DESC = u'YouTube.com searches, newest videos first'
1315
1316
1317 class YoutubeSearchURLIE(InfoExtractor):
1318     IE_DESC = u'YouTube.com search URLs'
1319     IE_NAME = u'youtube:search_url'
1320     _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
1321
1322     def _real_extract(self, url):
1323         mobj = re.match(self._VALID_URL, url)
1324         query = compat_urllib_parse.unquote_plus(mobj.group('query'))
1325
1326         webpage = self._download_webpage(url, query)
1327         result_code = self._search_regex(
1328             r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
1329
1330         part_codes = re.findall(
1331             r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
1332         entries = []
1333         for part_code in part_codes:
1334             part_title = self._html_search_regex(
1335                 [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
1336             part_url_snippet = self._html_search_regex(
1337                 r'(?s)href="([^"]+)"', part_code, 'item URL')
1338             part_url = compat_urlparse.urljoin(
1339                 'https://www.youtube.com/', part_url_snippet)
1340             entries.append({
1341                 '_type': 'url',
1342                 'url': part_url,
1343                 'title': part_title,
1344             })
1345
1346         return {
1347             '_type': 'playlist',
1348             'entries': entries,
1349             'title': query,
1350         }
1351
1352
1353 class YoutubeShowIE(InfoExtractor):
1354     IE_DESC = u'YouTube.com (multi-season) shows'
1355     _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
1356     IE_NAME = u'youtube:show'
1357
1358     def _real_extract(self, url):
1359         mobj = re.match(self._VALID_URL, url)
1360         show_name = mobj.group(1)
1361         webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
1362         # There's one playlist for each season of the show
1363         m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
1364         self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
1365         return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
1366
1367
1368 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
1369     """
1370     Base class for extractors that fetch info from
1371     http://www.youtube.com/feed_ajax
1372     Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1373     """
1374     _LOGIN_REQUIRED = True
1375     # use action_load_personal_feed instead of action_load_system_feed
1376     _PERSONAL_FEED = False
1377
1378     @property
1379     def _FEED_TEMPLATE(self):
1380         action = 'action_load_system_feed'
1381         if self._PERSONAL_FEED:
1382             action = 'action_load_personal_feed'
1383         return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
1384
1385     @property
1386     def IE_NAME(self):
1387         return u'youtube:%s' % self._FEED_NAME
1388
1389     def _real_initialize(self):
1390         self._login()
1391
1392     def _real_extract(self, url):
1393         feed_entries = []
1394         paging = 0
1395         for i in itertools.count(1):
1396             info = self._download_json(self._FEED_TEMPLATE % paging,
1397                                           u'%s feed' % self._FEED_NAME,
1398                                           u'Downloading page %s' % i)
1399             feed_html = info.get('feed_html') or info.get('content_html')
1400             load_more_widget_html = info.get('load_more_widget_html') or feed_html
1401             m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
1402             ids = orderedSet(m.group(1) for m in m_ids)
1403             feed_entries.extend(
1404                 self.url_result(video_id, 'Youtube', video_id=video_id)
1405                 for video_id in ids)
1406             mobj = re.search(
1407                 r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1408                 load_more_widget_html)
1409             if mobj is None:
1410                 break
1411             paging = mobj.group('paging')
1412         return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1413
1414 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
1415     IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1416     _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1417     _FEED_NAME = 'recommended'
1418     _PLAYLIST_TITLE = u'Youtube Recommended videos'
1419
1420 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
1421     IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1422     _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1423     _FEED_NAME = 'watch_later'
1424     _PLAYLIST_TITLE = u'Youtube Watch Later'
1425     _PERSONAL_FEED = True
1426
1427 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
1428     IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
1429     _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
1430     _FEED_NAME = 'history'
1431     _PERSONAL_FEED = True
1432     _PLAYLIST_TITLE = u'Youtube Watch History'
1433
1434 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1435     IE_NAME = u'youtube:favorites'
1436     IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1437     _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1438     _LOGIN_REQUIRED = True
1439
1440     def _real_extract(self, url):
1441         webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1442         playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
1443         return self.url_result(playlist_id, 'YoutubePlaylist')
1444
1445
1446 class YoutubeSubscriptionsIE(YoutubePlaylistIE):
1447     IE_NAME = u'youtube:subscriptions'
1448     IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
1449     _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1450
1451     def _real_extract(self, url):
1452         title = u'Youtube Subscriptions'
1453         page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title)
1454
1455         # The extraction process is the same as for playlists, but the regex
1456         # for the video ids doesn't contain an index
1457         ids = []
1458         more_widget_html = content_html = page
1459
1460         for page_num in itertools.count(1):
1461             matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
1462             new_ids = orderedSet(matches)
1463             ids.extend(new_ids)
1464
1465             mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1466             if not mobj:
1467                 break
1468
1469             more = self._download_json(
1470                 'https://youtube.com/%s' % mobj.group('more'), title,
1471                 'Downloading page #%s' % page_num,
1472                 transform_source=uppercase_escape)
1473             content_html = more['content_html']
1474             more_widget_html = more['load_more_widget_html']
1475
1476         return {
1477             '_type': 'playlist',
1478             'title': title,
1479             'entries': self._ids_to_results(ids),
1480         }
1481
1482
1483 class YoutubeTruncatedURLIE(InfoExtractor):
1484     IE_NAME = 'youtube:truncated_url'
1485     IE_DESC = False  # Do not list
1486     _VALID_URL = r'''(?x)
1487         (?:https?://)?[^/]+/watch\?(?:
1488             feature=[a-z_]+|
1489             annotation_id=annotation_[^&]+
1490         )?$|
1491         (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1492     '''
1493
1494     _TESTS = [{
1495         'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1496         'only_matching': True,
1497     }, {
1498         'url': 'http://www.youtube.com/watch?',
1499         'only_matching': True,
1500     }]
1501
1502     def _real_extract(self, url):
1503         raise ExtractorError(
1504             u'Did you forget to quote the URL? Remember that & is a meta '
1505             u'character in most shells, so you want to put the URL in quotes, '
1506             u'like  youtube-dl '
1507             u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1508             u' or simply  youtube-dl BaW_jenozKc  .',
1509             expected=True)