11 from .common import InfoExtractor, SearchInfoExtractor
12 from .subtitles import SubtitlesInfoExtractor
13 from ..jsinterp import JSInterpreter
14 from ..swfinterp import SWFInterpreter
19 compat_urllib_request,
26 get_element_by_attribute,
37 class YoutubeBaseInfoExtractor(InfoExtractor):
38 """Provide base functions for Youtube extractors"""
39 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
40 _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
41 _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
42 _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
43 _NETRC_MACHINE = 'youtube'
44 # If True it will raise an error if no login info is provided
45 _LOGIN_REQUIRED = False
47 def _set_language(self):
48 return bool(self._download_webpage(
50 note=u'Setting language', errnote='unable to set language',
55 Attempt to log in to YouTube.
56 True is returned if successful or skipped.
57 False is returned if login failed.
59 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
61 (username, password) = self._get_login_info()
62 # No authentication to be performed
64 if self._LOGIN_REQUIRED:
65 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
68 login_page = self._download_webpage(
69 self._LOGIN_URL, None,
70 note=u'Downloading login page',
71 errnote=u'unable to fetch login page', fatal=False)
72 if login_page is False:
75 galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
76 login_page, u'Login GALX parameter')
80 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
85 u'PersistentCookie': u'yes',
87 u'bgresponse': u'js_disabled',
88 u'checkConnection': u'',
89 u'checkedDomains': u'youtube',
94 u'signIn': u'Sign in',
96 u'service': u'youtube',
101 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
103 login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
104 login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
106 req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
107 login_results = self._download_webpage(
109 note=u'Logging in', errnote=u'unable to log in', fatal=False)
110 if login_results is False:
113 if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
114 raise ExtractorError(u'Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
117 # TODO add SMS and phone call support - these require making a request and then prompting the user
119 if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
120 tfa_code = self._get_tfa_info()
123 self._downloader.report_warning(u'Two-factor authentication required. Provide it with --twofactor <code>')
124 self._downloader.report_warning(u'(Note that only TOTP (Google Authenticator App) codes work at this time.)')
127 # Unlike the first login form, secTok and timeStmp are both required for the TFA form
129 match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
131 self._downloader.report_warning(u'Failed to get secTok - did the page structure change?')
132 secTok = match.group(1)
133 match = re.search(r'id="timeStmp"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
135 self._downloader.report_warning(u'Failed to get timeStmp - did the page structure change?')
136 timeStmp = match.group(1)
139 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
141 u'smsUserPin': tfa_code,
142 u'smsVerifyPin': u'Verify',
144 u'PersistentCookie': u'yes',
145 u'checkConnection': u'',
146 u'checkedDomains': u'youtube',
149 u'timeStmp': timeStmp,
150 u'service': u'youtube',
153 tfa_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in tfa_form_strs.items())
154 tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii')
156 tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
157 tfa_results = self._download_webpage(
159 note=u'Submitting TFA code', errnote=u'unable to submit tfa', fatal=False)
161 if tfa_results is False:
164 if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', tfa_results) is not None:
165 self._downloader.report_warning(u'Two-factor code expired. Please try again, or use a one-use backup code instead.')
167 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
168 self._downloader.report_warning(u'unable to log in - did the page structure change?')
170 if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
171 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.')
174 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
175 self._downloader.report_warning(u'unable to log in: bad username or password')
179 def _confirm_age(self):
182 'action_confirm': 'Confirm',
184 req = compat_urllib_request.Request(self._AGE_URL,
185 compat_urllib_parse.urlencode(age_form).encode('ascii'))
187 self._download_webpage(
189 note=u'Confirming age', errnote=u'Unable to confirm age')
192 def _real_initialize(self):
193 if self._downloader is None:
195 if not self._set_language():
197 if not self._login():
202 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
203 IE_DESC = u'YouTube.com'
204 _VALID_URL = r"""(?x)^
206 (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
207 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
208 (?:www\.)?deturl\.com/www\.youtube\.com/|
209 (?:www\.)?pwnyoutube\.com/|
210 (?:www\.)?yourepeat\.com/|
211 tube\.majestyc\.net/|
212 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
213 (?:.*?\#/)? # handle anchor (#/) redirect urls
214 (?: # the various things that can precede the ID:
215 (?:(?:v|embed|e)/) # v/ or embed/ or e/
216 |(?: # or the v= param in all its forms
217 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
218 (?:\?|\#!?) # the params delimiter ? or # or #!
219 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
223 |youtu\.be/ # just youtu.be/xxxx
224 |https?://(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
226 )? # all until now is optional -> you can pass the naked ID
227 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
228 (?(1).+)? # if we found the ID, everything can follow
230 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
232 '5': {'ext': 'flv', 'width': 400, 'height': 240},
233 '6': {'ext': 'flv', 'width': 450, 'height': 270},
234 '13': {'ext': '3gp'},
235 '17': {'ext': '3gp', 'width': 176, 'height': 144},
236 '18': {'ext': 'mp4', 'width': 640, 'height': 360},
237 '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
238 '34': {'ext': 'flv', 'width': 640, 'height': 360},
239 '35': {'ext': 'flv', 'width': 854, 'height': 480},
240 '36': {'ext': '3gp', 'width': 320, 'height': 240},
241 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
242 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
243 '43': {'ext': 'webm', 'width': 640, 'height': 360},
244 '44': {'ext': 'webm', 'width': 854, 'height': 480},
245 '45': {'ext': 'webm', 'width': 1280, 'height': 720},
246 '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
250 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
251 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
252 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
253 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
254 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
255 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
256 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
258 # Apple HTTP Live Streaming
259 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
260 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
261 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
262 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
263 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
264 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
265 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
268 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
269 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
270 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
271 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
272 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
273 '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
274 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
275 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
278 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
279 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
280 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
283 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
284 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
285 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
286 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
287 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
288 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
289 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
290 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
291 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
292 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
293 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
294 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
295 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
296 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
297 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
300 '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 48, 'preference': -50},
301 '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
304 '_rtmp': {'protocol': 'rtmp'},
310 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
311 u"file": u"BaW_jenozKc.mp4",
313 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
314 u"uploader": u"Philipp Hagemeister",
315 u"uploader_id": u"phihag",
316 u"upload_date": u"20121002",
317 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 .",
318 u"categories": [u'Science & Technology'],
322 u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
323 u"file": u"UxxajLWwzqY.mp4",
324 u"note": u"Test generic use_cipher_signature video (#897)",
326 u"upload_date": u"20120506",
327 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
328 u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
329 u"uploader": u"Icona Pop",
330 u"uploader_id": u"IconaPop"
334 u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
335 u"file": u"07FYdnEawAQ.mp4",
336 u"note": u"Test VEVO video with age protection (#956)",
338 u"upload_date": u"20130703",
339 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
340 u"description": u"md5:64249768eec3bc4276236606ea996373",
341 u"uploader": u"justintimberlakeVEVO",
342 u"uploader_id": u"justintimberlakeVEVO"
346 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
347 u"file": u"yZIXLfi8CZQ.mp4",
348 u"note": u"Embed-only video (#1746)",
350 u"upload_date": u"20120608",
351 u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
352 u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
353 u"uploader": u"SET India",
354 u"uploader_id": u"setindia"
358 u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
359 u"file": u"a9LDPn-MO4I.m4a",
360 u"note": u"256k DASH audio (format 141) via DASH manifest",
362 u"upload_date": "20121002",
363 u"uploader_id": "8KVIDEO",
364 u"description": "No description available.",
365 u"uploader": "8KVIDEO",
366 u"title": "UHDTV TEST 8K VIDEO.mp4"
369 u"youtube_include_dash_manifest": True,
373 # DASH manifest with encrypted signature
375 u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
377 u'id': u'IB3lcPjvWLA',
379 u'title': u'Afrojack - The Spark ft. Spree Wilson',
380 u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
381 u'uploader': u'AfrojackVEVO',
382 u'uploader_id': u'AfrojackVEVO',
383 u'upload_date': u'20131011',
386 u'youtube_include_dash_manifest': True,
394 def suitable(cls, url):
395 """Receives a URL and returns True if suitable for this IE."""
396 if YoutubePlaylistIE.suitable(url): return False
397 return re.match(cls._VALID_URL, url) is not None
399 def __init__(self, *args, **kwargs):
400 super(YoutubeIE, self).__init__(*args, **kwargs)
401 self._player_cache = {}
403 def report_video_info_webpage_download(self, video_id):
404 """Report attempt to download video info webpage."""
405 self.to_screen(u'%s: Downloading video info webpage' % video_id)
407 def report_information_extraction(self, video_id):
408 """Report attempt to extract video information."""
409 self.to_screen(u'%s: Extracting video information' % video_id)
411 def report_unavailable_format(self, video_id, format):
412 """Report extracted video URL."""
413 self.to_screen(u'%s: Format %s not available' % (video_id, format))
415 def report_rtmp_download(self):
416 """Indicate the download will use the RTMP protocol."""
417 self.to_screen(u'RTMP download detected')
419 def _signature_cache_id(self, example_sig):
420 """ Return a string representation of a signature """
421 return u'.'.join(compat_str(len(part)) for part in example_sig.split('.'))
423 def _extract_signature_function(self, video_id, player_url, example_sig):
425 r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
428 raise ExtractorError('Cannot identify player %r' % player_url)
429 player_type = id_m.group('ext')
430 player_id = id_m.group('id')
432 # Read from filesystem cache
433 func_id = '%s_%s_%s' % (
434 player_type, player_id, self._signature_cache_id(example_sig))
435 assert os.path.basename(func_id) == func_id
436 cache_dir = get_cachedir(self._downloader.params)
438 cache_enabled = cache_dir is not None
440 cache_fn = os.path.join(os.path.expanduser(cache_dir),
444 with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
445 cache_spec = json.load(cachef)
446 return lambda s: u''.join(s[i] for i in cache_spec)
448 pass # No cache available
450 if player_type == 'js':
451 code = self._download_webpage(
452 player_url, video_id,
453 note=u'Downloading %s player %s' % (player_type, player_id),
454 errnote=u'Download of %s failed' % player_url)
455 res = self._parse_sig_js(code)
456 elif player_type == 'swf':
457 urlh = self._request_webpage(
458 player_url, video_id,
459 note=u'Downloading %s player %s' % (player_type, player_id),
460 errnote=u'Download of %s failed' % player_url)
462 res = self._parse_sig_swf(code)
464 assert False, 'Invalid player type %r' % player_type
468 test_string = u''.join(map(compat_chr, range(len(example_sig))))
469 cache_res = res(test_string)
470 cache_spec = [ord(c) for c in cache_res]
472 os.makedirs(os.path.dirname(cache_fn))
473 except OSError as ose:
474 if ose.errno != errno.EEXIST:
476 write_json_file(cache_spec, cache_fn)
478 tb = traceback.format_exc()
479 self._downloader.report_warning(
480 u'Writing cache to %r failed: %s' % (cache_fn, tb))
484 def _print_sig_code(self, func, example_sig):
485 def gen_sig_code(idxs):
486 def _genslice(start, end, step):
487 starts = u'' if start == 0 else str(start)
488 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
489 steps = u'' if step == 1 else (u':%d' % step)
490 return u's[%s%s%s]' % (starts, ends, steps)
493 start = '(Never used)' # Quelch pyflakes warnings - start will be
494 # set as soon as step is set
495 for i, prev in zip(idxs[1:], idxs[:-1]):
499 yield _genslice(start, prev, step)
502 if i - prev in [-1, 1]:
507 yield u's[%d]' % prev
511 yield _genslice(start, i, step)
513 test_string = u''.join(map(compat_chr, range(len(example_sig))))
514 cache_res = func(test_string)
515 cache_spec = [ord(c) for c in cache_res]
516 expr_code = u' + '.join(gen_sig_code(cache_spec))
517 signature_id_tuple = '(%s)' % (
518 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
519 code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
520 u' return %s\n') % (signature_id_tuple, expr_code)
521 self.to_screen(u'Extracted signature function:\n' + code)
523 def _parse_sig_js(self, jscode):
524 funcname = self._search_regex(
525 r'signature=([$a-zA-Z]+)', jscode,
526 u'Initial JS player signature function name')
528 jsi = JSInterpreter(jscode)
529 initial_function = jsi.extract_function(funcname)
530 return lambda s: initial_function([s])
532 def _parse_sig_swf(self, file_contents):
533 swfi = SWFInterpreter(file_contents)
534 TARGET_CLASSNAME = u'SignatureDecipher'
535 searched_class = swfi.extract_class(TARGET_CLASSNAME)
536 initial_function = swfi.extract_function(searched_class, u'decipher')
537 return lambda s: initial_function([s])
539 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
540 """Turn the encrypted s field into a working signature"""
542 if player_url is None:
543 raise ExtractorError(u'Cannot decrypt signature without player_url')
545 if player_url.startswith(u'//'):
546 player_url = u'https:' + player_url
548 player_id = (player_url, self._signature_cache_id(s))
549 if player_id not in self._player_cache:
550 func = self._extract_signature_function(
551 video_id, player_url, s
553 self._player_cache[player_id] = func
554 func = self._player_cache[player_id]
555 if self._downloader.params.get('youtube_print_sig_code'):
556 self._print_sig_code(func, s)
558 except Exception as e:
559 tb = traceback.format_exc()
560 raise ExtractorError(
561 u'Signature extraction failed: ' + tb, cause=e)
563 def _get_available_subtitles(self, video_id, webpage):
565 sub_list = self._download_webpage(
566 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
567 video_id, note=False)
568 except ExtractorError as err:
569 self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
571 lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
576 params = compat_urllib_parse.urlencode({
579 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
580 'name': unescapeHTML(l[0]).encode('utf-8'),
582 url = u'https://www.youtube.com/api/timedtext?' + params
583 sub_lang_list[lang] = url
584 if not sub_lang_list:
585 self._downloader.report_warning(u'video doesn\'t have subtitles')
589 def _get_available_automatic_caption(self, video_id, webpage):
590 """We need the webpage for getting the captions url, pass it as an
591 argument to speed up the process."""
592 sub_format = self._downloader.params.get('subtitlesformat', 'srt')
593 self.to_screen(u'%s: Looking for automatic captions' % video_id)
594 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
595 err_msg = u'Couldn\'t find automatic captions for %s' % video_id
597 self._downloader.report_warning(err_msg)
599 player_config = json.loads(mobj.group(1))
601 args = player_config[u'args']
602 caption_url = args[u'ttsurl']
603 timestamp = args[u'timestamp']
604 # We get the available subtitles
605 list_params = compat_urllib_parse.urlencode({
610 list_url = caption_url + '&' + list_params
611 caption_list = self._download_xml(list_url, video_id)
612 original_lang_node = caption_list.find('track')
613 if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
614 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
616 original_lang = original_lang_node.attrib['lang_code']
619 for lang_node in caption_list.findall('target'):
620 sub_lang = lang_node.attrib['lang_code']
621 params = compat_urllib_parse.urlencode({
622 'lang': original_lang,
628 sub_lang_list[sub_lang] = caption_url + '&' + params
630 # An extractor error can be raise by the download process if there are
631 # no automatic captions but there are subtitles
632 except (KeyError, ExtractorError):
633 self._downloader.report_warning(err_msg)
637 def extract_id(cls, url):
638 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
640 raise ExtractorError(u'Invalid URL: %s' % url)
641 video_id = mobj.group(2)
644 def _extract_from_m3u8(self, manifest_url, video_id):
646 def _get_urls(_manifest):
647 lines = _manifest.split('\n')
648 urls = filter(lambda l: l and not l.startswith('#'),
651 manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
652 formats_urls = _get_urls(manifest)
653 for format_url in formats_urls:
654 itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
655 url_map[itag] = format_url
658 def _extract_annotations(self, video_id):
659 url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
660 return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
662 def _real_extract(self, url):
664 u'http' if self._downloader.params.get('prefer_insecure', False)
667 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
668 mobj = re.search(self._NEXT_URL_RE, url)
670 url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
671 video_id = self.extract_id(url)
674 url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
675 video_webpage = self._download_webpage(url, video_id)
677 # Attempt to extract SWF player URL
678 mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
680 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
685 self.report_video_info_webpage_download(video_id)
686 if re.search(r'player-age-gate-content">', video_webpage) is not None:
687 self.report_age_confirmation()
689 # We simulate the access to the video from www.youtube.com/v/{video_id}
690 # this can be viewed without login into Youtube
691 data = compat_urllib_parse.urlencode({
692 'video_id': video_id,
693 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
694 'sts': self._search_regex(
695 r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
697 video_info_url = proto + '://www.youtube.com/get_video_info?' + data
698 video_info_webpage = self._download_webpage(video_info_url, video_id,
700 errnote='unable to download video info webpage')
701 video_info = compat_parse_qs(video_info_webpage)
704 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
705 video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
706 % (video_id, el_type))
707 video_info_webpage = self._download_webpage(video_info_url, video_id,
709 errnote='unable to download video info webpage')
710 video_info = compat_parse_qs(video_info_webpage)
711 if 'token' in video_info:
713 if 'token' not in video_info:
714 if 'reason' in video_info:
715 raise ExtractorError(
716 u'YouTube said: %s' % video_info['reason'][0],
717 expected=True, video_id=video_id)
719 raise ExtractorError(
720 u'"token" parameter not in video info for unknown reason',
723 if 'view_count' in video_info:
724 view_count = int(video_info['view_count'][0])
728 # Check for "rental" videos
729 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
730 raise ExtractorError(u'"rental" videos not supported')
732 # Start extracting information
733 self.report_information_extraction(video_id)
736 if 'author' not in video_info:
737 raise ExtractorError(u'Unable to extract uploader name')
738 video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
741 video_uploader_id = None
742 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
744 video_uploader_id = mobj.group(1)
746 self._downloader.report_warning(u'unable to extract uploader nickname')
749 if 'title' in video_info:
750 video_title = video_info['title'][0]
752 self._downloader.report_warning(u'Unable to extract video title')
756 # We try first to get a high quality image:
757 m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
758 video_webpage, re.DOTALL)
759 if m_thumb is not None:
760 video_thumbnail = m_thumb.group(1)
761 elif 'thumbnail_url' not in video_info:
762 self._downloader.report_warning(u'unable to extract video thumbnail')
763 video_thumbnail = None
764 else: # don't panic if we can't find it
765 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
769 mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
772 r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
775 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
776 upload_date = unified_strdate(upload_date)
778 m_cat_container = get_element_by_id("eow-category", video_webpage)
780 category = self._html_search_regex(
781 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
783 video_categories = None if category is None else [category]
785 video_categories = None
788 video_description = get_element_by_id("eow-description", video_webpage)
789 if video_description:
790 video_description = re.sub(r'''(?x)
792 (?:[a-zA-Z-]+="[^"]+"\s+)*?
794 (?:[a-zA-Z-]+="[^"]+"\s+)*?
795 class="yt-uix-redirect-link"\s*>
798 ''', r'\1', video_description)
799 video_description = clean_html(video_description)
801 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
803 video_description = unescapeHTML(fd_mobj.group(1))
805 video_description = u''
807 def _extract_count(klass):
808 count = self._search_regex(
809 r'class="%s">([\d,]+)</span>' % re.escape(klass),
810 video_webpage, klass, default=None)
811 if count is not None:
812 return int(count.replace(',', ''))
814 like_count = _extract_count(u'likes-count')
815 dislike_count = _extract_count(u'dislikes-count')
818 video_subtitles = self.extract_subtitles(video_id, video_webpage)
820 if self._downloader.params.get('listsubtitles', False):
821 self._list_available_subtitles(video_id, video_webpage)
824 if 'length_seconds' not in video_info:
825 self._downloader.report_warning(u'unable to extract video duration')
826 video_duration = None
828 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
831 video_annotations = None
832 if self._downloader.params.get('writeannotations', False):
833 video_annotations = self._extract_annotations(video_id)
835 # Decide which formats to download
837 mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
839 raise ValueError('Could not find vevo ID')
840 json_code = uppercase_escape(mobj.group(1))
841 ytplayer_config = json.loads(json_code)
842 args = ytplayer_config['args']
843 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
844 # this signatures are encrypted
845 if 'url_encoded_fmt_stream_map' not in args:
846 raise ValueError(u'No stream_map present') # caught below
847 re_signature = re.compile(r'[&,]s=')
848 m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
850 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
851 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
852 m_s = re_signature.search(args.get('adaptive_fmts', u''))
854 if 'adaptive_fmts' in video_info:
855 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
857 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
861 def _map_to_format_list(urlmap):
863 for itag, video_real_url in urlmap.items():
866 'url': video_real_url,
867 'player_url': player_url,
869 if itag in self._formats:
870 dct.update(self._formats[itag])
874 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
875 self.report_rtmp_download()
877 'format_id': '_rtmp',
879 'url': video_info['conn'][0],
880 'player_url': player_url,
882 elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
883 encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
884 if 'rtmpe%3Dyes' in encoded_url_map:
885 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
887 for url_data_str in encoded_url_map.split(','):
888 url_data = compat_parse_qs(url_data_str)
889 if 'itag' not in url_data or 'url' not in url_data:
891 format_id = url_data['itag'][0]
892 url = url_data['url'][0]
894 if 'sig' in url_data:
895 url += '&signature=' + url_data['sig'][0]
896 elif 's' in url_data:
897 encrypted_sig = url_data['s'][0]
900 jsplayer_url_json = self._search_regex(
901 r'"assets":.+?"js":\s*("[^"]+")',
902 video_webpage, u'JS player URL')
903 player_url = json.loads(jsplayer_url_json)
904 if player_url is None:
905 player_url_json = self._search_regex(
906 r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
907 video_webpage, u'age gate player URL')
908 player_url = json.loads(player_url_json)
910 if self._downloader.params.get('verbose'):
911 if player_url is None:
912 player_version = 'unknown'
913 player_desc = 'unknown'
915 if player_url.endswith('swf'):
916 player_version = self._search_regex(
917 r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
918 u'flash player', fatal=False)
919 player_desc = 'flash player %s' % player_version
921 player_version = self._search_regex(
922 r'html5player-([^/]+?)(?:/html5player)?\.js',
924 'html5 player', fatal=False)
925 player_desc = u'html5 player %s' % player_version
927 parts_sizes = self._signature_cache_id(encrypted_sig)
928 self.to_screen(u'{%s} signature length %s, %s' %
929 (format_id, parts_sizes, player_desc))
931 signature = self._decrypt_signature(
932 encrypted_sig, video_id, player_url, age_gate)
933 url += '&signature=' + signature
934 if 'ratebypass' not in url:
935 url += '&ratebypass=yes'
936 url_map[format_id] = url
937 formats = _map_to_format_list(url_map)
938 elif video_info.get('hlsvp'):
939 manifest_url = video_info['hlsvp'][0]
940 url_map = self._extract_from_m3u8(manifest_url, video_id)
941 formats = _map_to_format_list(url_map)
943 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
945 # Look for the DASH manifest
946 if (self._downloader.params.get('youtube_include_dash_manifest', False)):
948 # The DASH manifest used needs to be the one from the original video_webpage.
949 # The one found in get_video_info seems to be using different signatures.
950 # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
951 # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
952 # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
954 dash_manifest_url = video_info.get('dashmpd')[0]
956 dash_manifest_url = ytplayer_config['args']['dashmpd']
957 def decrypt_sig(mobj):
959 dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
960 return '/signature/%s' % dec_s
961 dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
962 dash_doc = self._download_xml(
963 dash_manifest_url, video_id,
964 note=u'Downloading DASH manifest',
965 errnote=u'Could not download DASH manifest')
966 for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
967 url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
970 format_id = r.attrib['id']
971 video_url = url_el.text
972 filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
974 'format_id': format_id,
976 'width': int_or_none(r.attrib.get('width')),
977 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
978 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
979 'filesize': filesize,
982 existing_format = next(
984 if fo['format_id'] == format_id)
985 except StopIteration:
986 f.update(self._formats.get(format_id, {}))
989 existing_format.update(f)
991 except (ExtractorError, KeyError) as e:
992 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
994 self._sort_formats(formats)
998 'uploader': video_uploader,
999 'uploader_id': video_uploader_id,
1000 'upload_date': upload_date,
1001 'title': video_title,
1002 'thumbnail': video_thumbnail,
1003 'description': video_description,
1004 'categories': video_categories,
1005 'subtitles': video_subtitles,
1006 'duration': video_duration,
1007 'age_limit': 18 if age_gate else 0,
1008 'annotations': video_annotations,
1009 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
1010 'view_count': view_count,
1011 'like_count': like_count,
1012 'dislike_count': dislike_count,
1016 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
1017 IE_DESC = u'YouTube.com playlists'
1018 _VALID_URL = r"""(?x)(?:
1023 (?:course|view_play_list|my_playlists|artist|playlist|watch)
1024 \? (?:.*?&)*? (?:p|a|list)=
1028 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
1029 # Top tracks, they can also include dots
1034 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
1036 _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
1037 _MORE_PAGES_INDICATOR = r'data-link-type="next"'
1038 _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&[^"]*?index=(?P<index>\d+)'
1039 IE_NAME = u'youtube:playlist'
1041 def _real_initialize(self):
1044 def _ids_to_results(self, ids):
1045 return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
1048 def _extract_mix(self, playlist_id):
1049 # The mixes are generated from a a single video
1050 # the id of the playlist is just 'RD' + video_id
1051 url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
1052 webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
1053 search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
1054 title_span = (search_title('playlist-title') or
1055 search_title('title long-title') or search_title('title'))
1056 title = clean_html(title_span)
1057 video_re = r'''(?x)data-video-username=".*?".*?
1058 href="/watch\?v=([0-9A-Za-z_-]{11})&[^"]*?list=%s''' % re.escape(playlist_id)
1059 ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
1060 url_results = self._ids_to_results(ids)
1062 return self.playlist_result(url_results, playlist_id, title)
1064 def _real_extract(self, url):
1065 # Extract playlist id
1066 mobj = re.match(self._VALID_URL, url)
1068 raise ExtractorError(u'Invalid URL: %s' % url)
1069 playlist_id = mobj.group(1) or mobj.group(2)
1071 # Check if it's a video-specific URL
1072 query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
1073 if 'v' in query_dict:
1074 video_id = query_dict['v'][0]
1075 if self._downloader.params.get('noplaylist'):
1076 self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
1077 return self.url_result(video_id, 'Youtube', video_id=video_id)
1079 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1081 if playlist_id.startswith('RD'):
1082 # Mixes require a custom extraction process
1083 return self._extract_mix(playlist_id)
1084 if playlist_id.startswith('TL'):
1085 raise ExtractorError(u'For downloading YouTube.com top lists, use '
1086 u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
1088 url = self._TEMPLATE_URL % playlist_id
1089 page = self._download_webpage(url, playlist_id)
1090 more_widget_html = content_html = page
1092 # Check if the playlist exists or is private
1093 if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
1094 raise ExtractorError(
1095 u'The playlist doesn\'t exist or is private, use --username or '
1096 '--netrc to access it.',
1099 # Extract the video ids from the playlist pages
1102 for page_num in itertools.count(1):
1103 matches = re.finditer(self._VIDEO_RE, content_html)
1104 # We remove the duplicates and the link with index 0
1105 # (it's not the first video of the playlist)
1106 new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
1109 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1113 more = self._download_json(
1114 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
1115 'Downloading page #%s' % page_num,
1116 transform_source=uppercase_escape)
1117 content_html = more['content_html']
1118 more_widget_html = more['load_more_widget_html']
1120 playlist_title = self._html_search_regex(
1121 r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1124 url_results = self._ids_to_results(ids)
1125 return self.playlist_result(url_results, playlist_id, playlist_title)
1128 class YoutubeTopListIE(YoutubePlaylistIE):
1129 IE_NAME = u'youtube:toplist'
1130 IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1131 u' (Example: "yttoplist:music:Top Tracks")')
1132 _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1134 def _real_extract(self, url):
1135 mobj = re.match(self._VALID_URL, url)
1136 channel = mobj.group('chann')
1137 title = mobj.group('title')
1138 query = compat_urllib_parse.urlencode({'title': title})
1139 playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
1140 channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
1141 link = self._html_search_regex(playlist_re, channel_page, u'list')
1142 url = compat_urlparse.urljoin('https://www.youtube.com/', link)
1144 video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1146 # sometimes the webpage doesn't contain the videos
1147 # retry until we get them
1148 for i in itertools.count(0):
1149 msg = u'Downloading Youtube mix'
1151 msg += ', retry #%d' % i
1152 webpage = self._download_webpage(url, title, msg)
1153 ids = orderedSet(re.findall(video_re, webpage))
1156 url_results = self._ids_to_results(ids)
1157 return self.playlist_result(url_results, playlist_title=title)
1160 class YoutubeChannelIE(InfoExtractor):
1161 IE_DESC = u'YouTube.com channels'
1162 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1163 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
1164 _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'
1165 IE_NAME = u'youtube:channel'
1167 def extract_videos_from_page(self, page):
1169 for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
1170 if mobj.group(1) not in ids_in_page:
1171 ids_in_page.append(mobj.group(1))
1174 def _real_extract(self, url):
1175 # Extract channel id
1176 mobj = re.match(self._VALID_URL, url)
1178 raise ExtractorError(u'Invalid URL: %s' % url)
1180 # Download channel page
1181 channel_id = mobj.group(1)
1183 url = 'https://www.youtube.com/channel/%s/videos' % channel_id
1184 channel_page = self._download_webpage(url, channel_id)
1185 autogenerated = re.search(r'''(?x)
1187 channel-header-autogenerated-label|
1188 yt-channel-title-autogenerated
1189 )[^"]*"''', channel_page) is not None
1192 # The videos are contained in a single page
1193 # the ajax pages can't be used, they are empty
1194 video_ids = self.extract_videos_from_page(channel_page)
1196 # Download all channel pages using the json-based channel_ajax query
1197 for pagenum in itertools.count(1):
1198 url = self._MORE_PAGES_URL % (pagenum, channel_id)
1199 page = self._download_json(
1200 url, channel_id, note=u'Downloading page #%s' % pagenum,
1201 transform_source=uppercase_escape)
1203 ids_in_page = self.extract_videos_from_page(page['content_html'])
1204 video_ids.extend(ids_in_page)
1206 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1209 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1211 url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
1212 for video_id in video_ids]
1213 return self.playlist_result(url_entries, channel_id)
1216 class YoutubeUserIE(InfoExtractor):
1217 IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
1218 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1219 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
1220 _GDATA_PAGE_SIZE = 50
1221 _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1222 IE_NAME = u'youtube:user'
1225 def suitable(cls, url):
1226 # Don't return True if the url can be extracted with other youtube
1227 # extractor, the regex would is too permissive and it would match.
1228 other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
1229 if any(ie.suitable(url) for ie in other_ies): return False
1230 else: return super(YoutubeUserIE, cls).suitable(url)
1232 def _real_extract(self, url):
1234 mobj = re.match(self._VALID_URL, url)
1236 raise ExtractorError(u'Invalid URL: %s' % url)
1238 username = mobj.group(1)
1240 # Download video ids using YouTube Data API. Result size per
1241 # query is limited (currently to 50 videos) so we need to query
1242 # page by page until there are no video ids - it means we got
1245 def download_page(pagenum):
1246 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1248 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
1249 page = self._download_webpage(
1250 gdata_url, username,
1251 u'Downloading video ids from %d to %d' % (
1252 start_index, start_index + self._GDATA_PAGE_SIZE))
1255 response = json.loads(page)
1256 except ValueError as err:
1257 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
1258 if 'entry' not in response['feed']:
1261 # Extract video identifiers
1262 entries = response['feed']['entry']
1263 for entry in entries:
1264 title = entry['title']['$t']
1265 video_id = entry['id']['$t'].split('/')[-1]
1269 'ie_key': 'Youtube',
1273 url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
1275 return self.playlist_result(url_results, playlist_title=username)
1278 class YoutubeSearchIE(SearchInfoExtractor):
1279 IE_DESC = u'YouTube.com searches'
1280 _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1282 IE_NAME = u'youtube:search'
1283 _SEARCH_KEY = 'ytsearch'
1285 def _get_n_results(self, query, n):
1286 """Get a specified number of results for a query"""
1293 while (PAGE_SIZE * pagenum) < limit:
1294 result_url = self._API_URL % (
1295 compat_urllib_parse.quote_plus(query.encode('utf-8')),
1296 (PAGE_SIZE * pagenum) + 1)
1297 data_json = self._download_webpage(
1298 result_url, video_id=u'query "%s"' % query,
1299 note=u'Downloading page %s' % (pagenum + 1),
1300 errnote=u'Unable to download API page')
1301 data = json.loads(data_json)
1302 api_response = data['data']
1304 if 'items' not in api_response:
1305 raise ExtractorError(
1306 u'[youtube] No video results', expected=True)
1308 new_ids = list(video['id'] for video in api_response['items'])
1309 video_ids += new_ids
1311 limit = min(n, api_response['totalItems'])
1314 if len(video_ids) > n:
1315 video_ids = video_ids[:n]
1316 videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
1317 for video_id in video_ids]
1318 return self.playlist_result(videos, query)
1321 class YoutubeSearchDateIE(YoutubeSearchIE):
1322 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
1323 _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1324 _SEARCH_KEY = 'ytsearchdate'
1325 IE_DESC = u'YouTube.com searches, newest videos first'
1328 class YoutubeSearchURLIE(InfoExtractor):
1329 IE_DESC = u'YouTube.com search URLs'
1330 IE_NAME = u'youtube:search_url'
1331 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
1333 def _real_extract(self, url):
1334 mobj = re.match(self._VALID_URL, url)
1335 query = compat_urllib_parse.unquote_plus(mobj.group('query'))
1337 webpage = self._download_webpage(url, query)
1338 result_code = self._search_regex(
1339 r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
1341 part_codes = re.findall(
1342 r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
1344 for part_code in part_codes:
1345 part_title = self._html_search_regex(
1346 [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
1347 part_url_snippet = self._html_search_regex(
1348 r'(?s)href="([^"]+)"', part_code, 'item URL')
1349 part_url = compat_urlparse.urljoin(
1350 'https://www.youtube.com/', part_url_snippet)
1354 'title': part_title,
1358 '_type': 'playlist',
1364 class YoutubeShowIE(InfoExtractor):
1365 IE_DESC = u'YouTube.com (multi-season) shows'
1366 _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
1367 IE_NAME = u'youtube:show'
1369 def _real_extract(self, url):
1370 mobj = re.match(self._VALID_URL, url)
1371 show_name = mobj.group(1)
1372 webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
1373 # There's one playlist for each season of the show
1374 m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
1375 self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
1376 return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
1379 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
1381 Base class for extractors that fetch info from
1382 http://www.youtube.com/feed_ajax
1383 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1385 _LOGIN_REQUIRED = True
1386 # use action_load_personal_feed instead of action_load_system_feed
1387 _PERSONAL_FEED = False
1390 def _FEED_TEMPLATE(self):
1391 action = 'action_load_system_feed'
1392 if self._PERSONAL_FEED:
1393 action = 'action_load_personal_feed'
1394 return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
1398 return u'youtube:%s' % self._FEED_NAME
1400 def _real_initialize(self):
1403 def _real_extract(self, url):
1406 for i in itertools.count(1):
1407 info = self._download_json(self._FEED_TEMPLATE % paging,
1408 u'%s feed' % self._FEED_NAME,
1409 u'Downloading page %s' % i)
1410 feed_html = info.get('feed_html') or info.get('content_html')
1411 m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
1412 ids = orderedSet(m.group(1) for m in m_ids)
1413 feed_entries.extend(
1414 self.url_result(video_id, 'Youtube', video_id=video_id)
1415 for video_id in ids)
1417 r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1421 paging = mobj.group('paging')
1422 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1424 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
1425 IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
1426 _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1427 _FEED_NAME = 'subscriptions'
1428 _PLAYLIST_TITLE = u'Youtube Subscriptions'
1430 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
1431 IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1432 _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1433 _FEED_NAME = 'recommended'
1434 _PLAYLIST_TITLE = u'Youtube Recommended videos'
1436 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
1437 IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1438 _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1439 _FEED_NAME = 'watch_later'
1440 _PLAYLIST_TITLE = u'Youtube Watch Later'
1441 _PERSONAL_FEED = True
1443 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
1444 IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
1445 _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
1446 _FEED_NAME = 'history'
1447 _PERSONAL_FEED = True
1448 _PLAYLIST_TITLE = u'Youtube Watch History'
1450 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1451 IE_NAME = u'youtube:favorites'
1452 IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1453 _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1454 _LOGIN_REQUIRED = True
1456 def _real_extract(self, url):
1457 webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1458 playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
1459 return self.url_result(playlist_id, 'YoutubePlaylist')
1462 class YoutubeTruncatedURLIE(InfoExtractor):
1463 IE_NAME = 'youtube:truncated_url'
1464 IE_DESC = False # Do not list
1465 _VALID_URL = r'''(?x)
1466 (?:https?://)?[^/]+/watch\?(?:
1468 annotation_id=annotation_[^&]+
1470 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1474 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1475 'only_matching': True,
1477 'url': 'http://www.youtube.com/watch?',
1478 'only_matching': True,
1481 def _real_extract(self, url):
1482 raise ExtractorError(
1483 u'Did you forget to quote the URL? Remember that & is a meta '
1484 u'character in most shells, so you want to put the URL in quotes, '
1486 u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1487 u' or simply youtube-dl BaW_jenozKc .',