3 from __future__ import unicode_literals
12 from .common import InfoExtractor, SearchInfoExtractor
13 from ..compat import (
18 compat_urllib_parse_unquote_plus,
19 compat_urllib_parse_urlencode,
20 compat_urllib_parse_urlparse,
23 from ..jsinterp import JSInterpreter
48 class YoutubeBaseInfoExtractor(InfoExtractor):
49 """Provide base functions for Youtube extractors"""
50 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
51 _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
53 _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
54 _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
55 _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
57 _NETRC_MACHINE = 'youtube'
58 # If True it will raise an error if no login info is provided
59 _LOGIN_REQUIRED = False
61 _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
63 def _ids_to_results(self, ids):
65 self.url_result(vid_id, 'Youtube', video_id=vid_id)
70 Attempt to log in to YouTube.
71 True is returned if successful or skipped.
72 False is returned if login failed.
74 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
76 username, password = self._get_login_info()
77 # No authentication to be performed
79 if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
80 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
83 login_page = self._download_webpage(
84 self._LOGIN_URL, None,
85 note='Downloading login page',
86 errnote='unable to fetch login page', fatal=False)
87 if login_page is False:
90 login_form = self._hidden_inputs(login_page)
92 def req(url, f_req, note, errnote):
93 data = login_form.copy()
96 'checkConnection': 'youtube',
97 'checkedDomains': 'youtube',
99 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
100 'f.req': json.dumps(f_req),
101 'flowName': 'GlifWebSignIn',
102 'flowEntry': 'ServiceLogin',
103 # TODO: reverse actual botguard identifier generation algo
104 'bgRequest': '["identifier",""]',
106 return self._download_json(
107 url, None, note=note, errnote=errnote,
108 transform_source=lambda s: re.sub(r'^[^[]*', '', s),
110 data=urlencode_postdata(data), headers={
111 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
112 'Google-Accounts-XSRF': 1,
116 self._downloader.report_warning(message)
120 None, [], None, 'US', None, None, 2, False, True,
124 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
126 1, [None, None, []], None, None, None, True
131 lookup_results = req(
132 self._LOOKUP_URL, lookup_req,
133 'Looking up account info', 'Unable to look up account info')
135 if lookup_results is False:
138 user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
140 warn('Unable to extract user hash')
145 None, 1, None, [1, None, None, None, [password, None, True]],
147 None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
148 1, [None, None, []], None, None, None, True
151 challenge_results = req(
152 self._CHALLENGE_URL, challenge_req,
153 'Logging in', 'Unable to log in')
155 if challenge_results is False:
158 login_res = try_get(challenge_results, lambda x: x[0][5], list)
160 login_msg = try_get(login_res, lambda x: x[5], compat_str)
162 'Unable to login: %s' % 'Invalid password'
163 if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
166 res = try_get(challenge_results, lambda x: x[0][-1], list)
168 warn('Unable to extract result entry')
171 login_challenge = try_get(res, lambda x: x[0][0], list)
173 challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
174 if challenge_str == 'TWO_STEP_VERIFICATION':
175 # SEND_SUCCESS - TFA code has been successfully sent to phone
176 # QUOTA_EXCEEDED - reached the limit of TFA codes
177 status = try_get(login_challenge, lambda x: x[5], compat_str)
178 if status == 'QUOTA_EXCEEDED':
179 warn('Exceeded the limit of TFA codes, try later')
182 tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
184 warn('Unable to extract TL')
187 tfa_code = self._get_tfa_info('2-step verification code')
191 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
192 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
195 tfa_code = remove_start(tfa_code, 'G-')
198 user_hash, None, 2, None,
200 9, None, None, None, None, None, None, None,
201 [None, tfa_code, True, 2]
205 self._TFA_URL.format(tl), tfa_req,
206 'Submitting TFA code', 'Unable to submit TFA code')
208 if tfa_results is False:
211 tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
213 tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
215 'Unable to finish TFA: %s' % 'Invalid TFA code'
216 if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
219 check_cookie_url = try_get(
220 tfa_results, lambda x: x[0][-1][2], compat_str)
223 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
224 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
225 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
227 challenge = CHALLENGES.get(
229 '%s returned error %s.' % (self.IE_NAME, challenge_str))
230 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
233 check_cookie_url = try_get(res, lambda x: x[2], compat_str)
235 if not check_cookie_url:
236 warn('Unable to extract CheckCookie URL')
239 check_cookie_results = self._download_webpage(
240 check_cookie_url, None, 'Checking cookie', fatal=False)
242 if check_cookie_results is False:
245 if 'https://myaccount.google.com/' not in check_cookie_results:
246 warn('Unable to log in')
251 def _real_initialize(self):
252 if self._downloader is None:
254 if not self._login():
257 _DEFAULT_API_DATA = {
261 'clientVersion': '2.20201021.03.00',
266 _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
267 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
268 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
270 def _call_api(self, ep, query, video_id, fatal=True):
271 data = self._DEFAULT_API_DATA.copy()
274 return self._download_json(
275 'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
276 note='Downloading API JSON', errnote='Unable to download API page',
277 data=json.dumps(data).encode('utf8'), fatal=fatal,
278 headers={'content-type': 'application/json'},
279 query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
281 def _extract_yt_initial_data(self, video_id, webpage):
282 return self._parse_json(
284 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
285 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
288 def _extract_ytcfg(self, video_id, webpage):
289 return self._parse_json(
291 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
292 default='{}'), video_id, fatal=False)
294 def _extract_video(self, renderer):
295 video_id = renderer['videoId']
298 (lambda x: x['title']['runs'][0]['text'],
299 lambda x: x['title']['simpleText']), compat_str)
300 description = try_get(
301 renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
303 duration = parse_duration(try_get(
304 renderer, lambda x: x['lengthText']['simpleText'], compat_str))
305 view_count_text = try_get(
306 renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
307 view_count = str_to_int(self._search_regex(
308 r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
309 'view count', default=None))
311 renderer, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
313 '_type': 'url_transparent',
314 'ie_key': YoutubeIE.ie_key(),
318 'description': description,
319 'duration': duration,
320 'view_count': view_count,
321 'uploader': uploader,
325 class YoutubeIE(YoutubeBaseInfoExtractor):
326 IE_DESC = 'YouTube.com'
327 _VALID_URL = r"""(?x)^
329 (?:https?://|//) # http(s):// or protocol-independent URL
330 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/|
331 (?:www\.)?deturl\.com/www\.youtube\.com/|
332 (?:www\.)?pwnyoutube\.com/|
333 (?:www\.)?hooktube\.com/|
334 (?:www\.)?yourepeat\.com/|
335 tube\.majestyc\.net/|
336 # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances
337 (?:(?:www|dev)\.)?invidio\.us/|
338 (?:(?:www|no)\.)?invidiou\.sh/|
339 (?:(?:www|fi)\.)?invidious\.snopyta\.org/|
340 (?:www\.)?invidious\.kabi\.tk/|
341 (?:www\.)?invidious\.13ad\.de/|
342 (?:www\.)?invidious\.mastodon\.host/|
343 (?:www\.)?invidious\.zapashcanon\.fr/|
344 (?:www\.)?invidious\.kavin\.rocks/|
345 (?:www\.)?invidious\.tube/|
346 (?:www\.)?invidiou\.site/|
347 (?:www\.)?invidious\.site/|
348 (?:www\.)?invidious\.xyz/|
349 (?:www\.)?invidious\.nixnet\.xyz/|
350 (?:www\.)?invidious\.drycat\.fr/|
351 (?:www\.)?tube\.poal\.co/|
352 (?:www\.)?tube\.connect\.cafe/|
353 (?:www\.)?vid\.wxzm\.sx/|
354 (?:www\.)?vid\.mint\.lgbt/|
355 (?:www\.)?yewtu\.be/|
356 (?:www\.)?yt\.elukerio\.org/|
357 (?:www\.)?yt\.lelux\.fi/|
358 (?:www\.)?invidious\.ggc-project\.de/|
359 (?:www\.)?yt\.maisputain\.ovh/|
360 (?:www\.)?invidious\.13ad\.de/|
361 (?:www\.)?invidious\.toot\.koeln/|
362 (?:www\.)?invidious\.fdn\.fr/|
363 (?:www\.)?watch\.nettohikari\.com/|
364 (?:www\.)?kgg2m7yk5aybusll\.onion/|
365 (?:www\.)?qklhadlycap4cnod\.onion/|
366 (?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion/|
367 (?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion/|
368 (?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion/|
369 (?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion/|
370 (?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p/|
371 (?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion/|
372 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
373 (?:.*?\#/)? # handle anchor (#/) redirect urls
374 (?: # the various things that can precede the ID:
375 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
376 |(?: # or the v= param in all its forms
377 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
378 (?:\?|\#!?) # the params delimiter ? or # or #!
379 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
384 youtu\.be| # just youtu.be/xxxx
385 vid\.plus| # or vid.plus/xxxx
386 zwearz\.com/watch| # or zwearz.com/watch/xxxx
388 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
390 )? # all until now is optional -> you can pass the naked ID
391 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
394 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
395 WL # WL are handled by the watch later IE
398 (?(1).+)? # if we found the ID, everything can follow
399 $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
401 r'/(?P<id>[a-zA-Z0-9_-]{8,})/player_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?/base\.js$',
402 r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
404 _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
411 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
415 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
416 'uploader': 'Philipp Hagemeister',
417 'uploader_id': 'phihag',
418 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
419 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
420 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
421 'upload_date': '20121002',
422 'description': '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 .',
423 'categories': ['Science & Technology'],
424 'tags': ['youtube-dl'],
428 'dislike_count': int,
434 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
435 'note': 'Embed-only video (#1746)',
439 'upload_date': '20120608',
440 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
441 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
442 'uploader': 'SET India',
443 'uploader_id': 'setindia',
444 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
447 'skip': 'Private video',
450 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
451 'note': 'Use the first video ID in the URL',
455 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
456 'uploader': 'Philipp Hagemeister',
457 'uploader_id': 'phihag',
458 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
459 'upload_date': '20121002',
460 'description': '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 .',
461 'categories': ['Science & Technology'],
462 'tags': ['youtube-dl'],
466 'dislike_count': int,
469 'skip_download': True,
473 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
474 'note': '256k DASH audio (format 141) via DASH manifest',
478 'upload_date': '20121002',
479 'uploader_id': '8KVIDEO',
480 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
482 'uploader': '8KVIDEO',
483 'title': 'UHDTV TEST 8K VIDEO.mp4'
486 'youtube_include_dash_manifest': True,
489 'skip': 'format 141 not served anymore',
491 # DASH manifest with encrypted signature
493 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
497 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
498 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
500 'uploader': 'AfrojackVEVO',
501 'uploader_id': 'AfrojackVEVO',
502 'upload_date': '20131011',
505 'youtube_include_dash_manifest': True,
506 'format': '141/bestaudio[ext=m4a]',
511 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
516 'upload_date': '20100909',
517 'uploader': 'Amazing Atheist',
518 'uploader_id': 'TheAmazingAtheist',
519 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
520 'title': 'Burning Everyone\'s Koran',
521 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms \r\n\r\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
524 # Normal age-gate video (No vevo, embed allowed), available via embed page
526 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
530 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
531 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
533 'uploader': 'The Witcher',
534 'uploader_id': 'WitcherGame',
535 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
536 'upload_date': '20140605',
541 # Age-gated video only available with authentication (unavailable
542 # via embed page workaround)
543 'url': 'XgnwCQzjau8',
544 'only_matching': True,
546 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
547 # YouTube Red ad is not captured for creator
549 'url': '__2ABJjxzNo',
554 'upload_date': '20100430',
555 'uploader_id': 'deadmau5',
556 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
557 'creator': 'deadmau5',
558 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
559 'uploader': 'deadmau5',
560 'title': 'Deadmau5 - Some Chords (HD)',
561 'alt_title': 'Some Chords',
563 'expected_warnings': [
564 'DASH manifest missing',
567 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
569 'url': 'lqQg6PlCWgI',
574 'upload_date': '20150827',
575 'uploader_id': 'olympic',
576 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
577 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
578 'uploader': 'Olympic',
579 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
582 'skip_download': 'requires avconv',
587 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
591 'stretched_ratio': 16 / 9.,
593 'upload_date': '20110310',
594 'uploader_id': 'AllenMeow',
595 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
596 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
598 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
601 # url_encoded_fmt_stream_map is empty string
603 'url': 'qEJwOuvDf7I',
607 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
609 'upload_date': '20150404',
610 'uploader_id': 'spbelect',
611 'uploader': 'Наблюдатели Петербурга',
614 'skip_download': 'requires avconv',
616 'skip': 'This live event has ended.',
618 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
620 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
624 'title': 'md5:7b81415841e02ecd4313668cde88737a',
625 'description': 'md5:116377fd2963b81ec4ce64b542173306',
627 'upload_date': '20150625',
628 'uploader_id': 'dorappi2000',
629 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
630 'uploader': 'dorappi2000',
631 'formats': 'mincount:31',
633 'skip': 'not actual anymore',
635 # DASH manifest with segment_list
637 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
638 'md5': '8ce563a1d667b599d21064e982ab9e31',
642 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
643 'uploader': 'Airtek',
644 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
645 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
646 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
649 'youtube_include_dash_manifest': True,
650 'format': '135', # bestvideo
652 'skip': 'This live event has ended.',
655 # Multifeed videos (multiple cameras), URL is for Main Camera
656 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
659 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
660 'description': 'md5:e03b909557865076822aa169218d6a5d',
666 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
667 'description': 'md5:e03b909557865076822aa169218d6a5d',
669 'upload_date': '20161111',
670 'uploader': 'Team PGP',
671 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
672 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
678 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
679 'description': 'md5:e03b909557865076822aa169218d6a5d',
681 'upload_date': '20161111',
682 'uploader': 'Team PGP',
683 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
684 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
690 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
691 'description': 'md5:e03b909557865076822aa169218d6a5d',
693 'upload_date': '20161111',
694 'uploader': 'Team PGP',
695 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
696 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
702 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
703 'description': 'md5:e03b909557865076822aa169218d6a5d',
705 'upload_date': '20161111',
706 'uploader': 'Team PGP',
707 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
708 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
712 'skip_download': True,
716 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
717 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
720 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
723 'skip': 'Not multifeed anymore',
726 'url': 'https://vid.plus/FlRa-iH7PGw',
727 'only_matching': True,
730 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
731 'only_matching': True,
734 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
735 # Also tests cut-off URL expansion in video description (see
736 # https://github.com/ytdl-org/youtube-dl/issues/1892,
737 # https://github.com/ytdl-org/youtube-dl/issues/8164)
738 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
742 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
743 'alt_title': 'Dark Walk - Position Music',
744 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
746 'upload_date': '20151119',
747 'uploader_id': 'IronSoulElf',
748 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
749 'uploader': 'IronSoulElf',
750 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
751 'track': 'Dark Walk - Position Music',
752 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
753 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
756 'skip_download': True,
760 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
761 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
762 'only_matching': True,
765 # Video with yt:stretch=17:0
766 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
770 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
771 'description': 'md5:ee18a25c350637c8faff806845bddee9',
772 'upload_date': '20151107',
773 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
774 'uploader': 'CH GAMER DROID',
777 'skip_download': True,
779 'skip': 'This video does not exist.',
782 # Video licensed under Creative Commons
783 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
787 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
788 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
790 'upload_date': '20150127',
791 'uploader_id': 'BerkmanCenter',
792 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
793 'uploader': 'The Berkman Klein Center for Internet & Society',
794 'license': 'Creative Commons Attribution license (reuse allowed)',
797 'skip_download': True,
801 # Channel-like uploader_url
802 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
806 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
807 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
809 'upload_date': '20151119',
810 'uploader': 'Bernie Sanders',
811 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
812 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
813 'license': 'Creative Commons Attribution license (reuse allowed)',
816 'skip_download': True,
820 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
821 'only_matching': True,
824 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
825 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
826 'only_matching': True,
829 # Rental video preview
830 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
834 'title': 'Piku - Trailer',
835 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
836 'upload_date': '20150811',
837 'uploader': 'FlixMatrix',
838 'uploader_id': 'FlixMatrixKaravan',
839 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
840 'license': 'Standard YouTube License',
843 'skip_download': True,
845 'skip': 'This video is not available.',
848 # YouTube Red video with episode data
849 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
853 'title': 'Isolation - Mind Field (Ep 1)',
854 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
856 'upload_date': '20170118',
857 'uploader': 'Vsauce',
858 'uploader_id': 'Vsauce',
859 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
860 'series': 'Mind Field',
865 'skip_download': True,
867 'expected_warnings': [
868 'Skipping DASH manifest',
872 # The following content has been identified by the YouTube community
873 # as inappropriate or offensive to some audiences.
874 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
878 'title': 'Race Differences in Intelligence',
879 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
881 'upload_date': '20140124',
882 'uploader': 'New Century Foundation',
883 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
884 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
887 'skip_download': True,
889 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
893 'url': '1t24XAntNCY',
894 'only_matching': True,
897 # geo restricted to JP
898 'url': 'sJL6WA-aGkQ',
899 'only_matching': True,
902 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
903 'only_matching': True,
907 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
908 'only_matching': True,
911 # Video with unsupported adaptive stream type formats
912 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
916 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
917 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
919 'upload_date': '20130923',
920 'uploader': 'Amelia Putri Harwita',
921 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
922 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
923 'formats': 'maxcount:10',
926 'skip_download': True,
927 'youtube_include_dash_manifest': False,
929 'skip': 'not actual anymore',
932 # Youtube Music Auto-generated description
933 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
937 'title': 'Voyeur Girl',
938 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
939 'upload_date': '20190312',
940 'uploader': 'Stephen - Topic',
941 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
943 'track': 'Voyeur Girl',
944 'album': 'it\'s too much love to know my dear',
945 'release_date': '20190313',
946 'release_year': 2019,
949 'skip_download': True,
953 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
954 'only_matching': True,
957 # invalid -> valid video id redirection
958 'url': 'DJztXj2GPfl',
962 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
963 'description': 'md5:bf577a41da97918e94fa9798d9228825',
964 'upload_date': '20090125',
965 'uploader': 'Prochorowka',
966 'uploader_id': 'Prochorowka',
967 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
968 'artist': 'Panjabi MC',
969 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
970 'album': 'Beware of the Boys (Mundian To Bach Ke)',
973 'skip_download': True,
975 'skip': 'Video unavailable',
978 # empty description results in an empty string
979 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
985 'upload_date': '20170613',
986 'uploader_id': 'ElevageOrVert',
987 'uploader': 'ElevageOrVert',
990 'skip_download': True,
994 # with '};' inside yt initial data (see [1])
995 # see [2] for an example with '};' inside ytInitialPlayerResponse
996 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
997 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
998 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1000 'id': 'CHqg6qOn4no',
1002 'title': 'Part 77 Sort a list of simple types in c#',
1003 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1004 'upload_date': '20130831',
1005 'uploader_id': 'kudvenkat',
1006 'uploader': 'kudvenkat',
1009 'skip_download': True,
1013 # another example of '};' in ytInitialData
1014 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1015 'only_matching': True,
1018 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1019 'only_matching': True,
1023 def __init__(self, *args, **kwargs):
1024 super(YoutubeIE, self).__init__(*args, **kwargs)
1025 self._code_cache = {}
1026 self._player_cache = {}
1028 def _signature_cache_id(self, example_sig):
1029 """ Return a string representation of a signature """
1030 return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
1033 def _extract_player_info(cls, player_url):
1034 for player_re in cls._PLAYER_INFO_RE:
1035 id_m = re.search(player_re, player_url)
1039 raise ExtractorError('Cannot identify player %r' % player_url)
1040 return id_m.group('id')
1042 def _extract_signature_function(self, video_id, player_url, example_sig):
1043 player_id = self._extract_player_info(player_url)
1045 # Read from filesystem cache
1046 func_id = 'js_%s_%s' % (
1047 player_id, self._signature_cache_id(example_sig))
1048 assert os.path.basename(func_id) == func_id
1050 cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
1051 if cache_spec is not None:
1052 return lambda s: ''.join(s[i] for i in cache_spec)
1054 if player_id not in self._code_cache:
1055 self._code_cache[player_id] = self._download_webpage(
1056 player_url, video_id,
1057 note='Downloading player ' + player_id,
1058 errnote='Download of %s failed' % player_url)
1059 code = self._code_cache[player_id]
1060 res = self._parse_sig_js(code)
1062 test_string = ''.join(map(compat_chr, range(len(example_sig))))
1063 cache_res = res(test_string)
1064 cache_spec = [ord(c) for c in cache_res]
1066 self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
1069 def _print_sig_code(self, func, example_sig):
1070 def gen_sig_code(idxs):
1071 def _genslice(start, end, step):
1072 starts = '' if start == 0 else str(start)
1073 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
1074 steps = '' if step == 1 else (':%d' % step)
1075 return 's[%s%s%s]' % (starts, ends, steps)
1078 # Quelch pyflakes warnings - start will be set when step is set
1079 start = '(Never used)'
1080 for i, prev in zip(idxs[1:], idxs[:-1]):
1081 if step is not None:
1082 if i - prev == step:
1084 yield _genslice(start, prev, step)
1087 if i - prev in [-1, 1]:
1092 yield 's[%d]' % prev
1096 yield _genslice(start, i, step)
1098 test_string = ''.join(map(compat_chr, range(len(example_sig))))
1099 cache_res = func(test_string)
1100 cache_spec = [ord(c) for c in cache_res]
1101 expr_code = ' + '.join(gen_sig_code(cache_spec))
1102 signature_id_tuple = '(%s)' % (
1103 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
1104 code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1105 ' return %s\n') % (signature_id_tuple, expr_code)
1106 self.to_screen('Extracted signature function:\n' + code)
1108 def _parse_sig_js(self, jscode):
1109 funcname = self._search_regex(
1110 (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1111 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1112 r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1113 r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1115 r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1116 r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
1117 r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1118 r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1119 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1120 r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1121 r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1122 r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
1123 jscode, 'Initial JS player signature function name', group='sig')
1125 jsi = JSInterpreter(jscode)
1126 initial_function = jsi.extract_function(funcname)
1127 return lambda s: initial_function([s])
1129 def _decrypt_signature(self, s, video_id, player_url):
1130 """Turn the encrypted s field into a working signature"""
1132 if player_url is None:
1133 raise ExtractorError('Cannot decrypt signature without player_url')
1135 if player_url.startswith('//'):
1136 player_url = 'https:' + player_url
1137 elif not re.match(r'https?://', player_url):
1138 player_url = compat_urlparse.urljoin(
1139 'https://www.youtube.com', player_url)
1141 player_id = (player_url, self._signature_cache_id(s))
1142 if player_id not in self._player_cache:
1143 func = self._extract_signature_function(
1144 video_id, player_url, s
1146 self._player_cache[player_id] = func
1147 func = self._player_cache[player_id]
1148 if self._downloader.params.get('youtube_print_sig_code'):
1149 self._print_sig_code(func, s)
1151 except Exception as e:
1152 tb = traceback.format_exc()
1153 raise ExtractorError(
1154 'Signature extraction failed: ' + tb, cause=e)
1156 def _mark_watched(self, video_id, player_response):
1157 playback_url = url_or_none(try_get(
1159 lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
1160 if not playback_url:
1162 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1163 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1165 # cpn generation algorithm is reverse engineered from base.js.
1166 # In fact it works even with dummy cpn.
1167 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
1168 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1174 playback_url = compat_urlparse.urlunparse(
1175 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1177 self._download_webpage(
1178 playback_url, video_id, 'Marking watched',
1179 'Unable to mark watched', fatal=False)
1182 def _extract_urls(webpage):
1183 # Embedded YouTube player
1185 unescapeHTML(mobj.group('url'))
1186 for mobj in re.finditer(r'''(?x)
1196 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1197 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1200 # lazyYT YouTube embed
1201 entries.extend(list(map(
1203 re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
1205 # Wordpress "YouTube Video Importer" plugin
1206 matches = re.findall(r'''(?x)<div[^>]+
1207 class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
1208 data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
1209 entries.extend(m[-1] for m in matches)
1214 def _extract_url(webpage):
1215 urls = YoutubeIE._extract_urls(webpage)
1216 return urls[0] if urls else None
1219 def extract_id(cls, url):
1220 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1222 raise ExtractorError('Invalid URL: %s' % url)
1223 video_id = mobj.group(2)
1226 def _extract_chapters_from_json(self, data, video_id, duration):
1227 chapters_list = try_get(
1229 lambda x: x['playerOverlays']
1230 ['playerOverlayRenderer']
1231 ['decoratedPlayerBarRenderer']
1232 ['decoratedPlayerBarRenderer']
1234 ['chapteredPlayerBarRenderer']
1237 if not chapters_list:
1240 def chapter_time(chapter):
1241 return float_or_none(
1244 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1248 for next_num, chapter in enumerate(chapters_list, start=1):
1249 start_time = chapter_time(chapter)
1250 if start_time is None:
1252 end_time = (chapter_time(chapters_list[next_num])
1253 if next_num < len(chapters_list) else duration)
1254 if end_time is None:
1257 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1260 'start_time': start_time,
1261 'end_time': end_time,
1266 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1267 return self._parse_json(self._search_regex(
1268 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1269 regex), webpage, name, default='{}'), video_id, fatal=False)
1271 def _real_extract(self, url):
1272 url, smuggled_data = unsmuggle_url(url, {})
1273 video_id = self._match_id(url)
1274 base_url = self.http_scheme() + '//www.youtube.com/'
1275 webpage_url = base_url + 'watch?v=' + video_id
1276 webpage = self._download_webpage(webpage_url, video_id, fatal=False)
1278 player_response = None
1280 player_response = self._extract_yt_initial_variable(
1281 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1282 video_id, 'initial player response')
1283 if not player_response:
1284 player_response = self._call_api(
1285 'player', {'videoId': video_id}, video_id)
1287 playability_status = player_response.get('playabilityStatus') or {}
1288 if playability_status.get('reason') == 'Sign in to confirm your age':
1289 pr = self._parse_json(try_get(compat_parse_qs(
1290 self._download_webpage(
1291 base_url + 'get_video_info', video_id,
1292 'Refetching age-gated info webpage',
1293 'unable to download video info webpage', query={
1294 'video_id': video_id,
1296 lambda x: x['player_response'][0],
1297 compat_str) or '{}', video_id)
1299 player_response = pr
1301 trailer_video_id = try_get(
1303 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1305 if trailer_video_id:
1306 return self.url_result(
1307 trailer_video_id, self.ie_key(), trailer_video_id)
1312 return x.get('simpleText') or ''.join([r['text'] for r in x['runs']])
1315 lambda x: self._html_search_meta(x, webpage, default=None)) \
1316 if webpage else lambda x: None
1318 video_details = player_response.get('videoDetails') or {}
1319 microformat = try_get(
1321 lambda x: x['microformat']['playerMicroformatRenderer'],
1323 video_title = video_details.get('title') \
1324 or get_text(microformat.get('title')) \
1325 or search_meta(['og:title', 'twitter:title', 'title'])
1326 video_description = video_details.get('shortDescription')
1328 if not smuggled_data.get('force_singlefeed', False):
1329 if not self._downloader.params.get('noplaylist'):
1330 multifeed_metadata_list = try_get(
1332 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1334 if multifeed_metadata_list:
1337 for feed in multifeed_metadata_list.split(','):
1338 # Unquote should take place before split on comma (,) since textual
1339 # fields may contain comma as well (see
1340 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1341 feed_data = compat_parse_qs(
1342 compat_urllib_parse_unquote_plus(feed))
1344 def feed_entry(name):
1346 feed_data, lambda x: x[name][0], compat_str)
1348 feed_id = feed_entry('id')
1351 feed_title = feed_entry('title')
1354 title += ' (%s)' % feed_title
1356 '_type': 'url_transparent',
1357 'ie_key': 'Youtube',
1359 base_url + 'watch?v=' + feed_data['id'][0],
1360 {'force_singlefeed': True}),
1363 feed_ids.append(feed_id)
1365 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1366 % (', '.join(feed_ids), video_id))
1367 return self.playlist_result(
1368 entries, video_id, video_title, video_description)
1370 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1375 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1376 streaming_data = player_response.get('streamingData') or {}
1377 streaming_formats = streaming_data.get('formats') or []
1378 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1379 for fmt in streaming_formats:
1380 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1383 fmt_url = fmt.get('url')
1385 sc = compat_parse_qs(fmt.get('signatureCipher'))
1386 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1387 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1388 if not (sc and fmt_url and encrypted_sig):
1393 player_url = self._search_regex(
1394 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1395 webpage, 'player URL', fatal=False)
1398 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1399 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1400 fmt_url += '&' + sp + '=' + signature
1402 itag = str_or_none(fmt.get('itag'))
1405 quality = fmt.get('quality')
1407 'asr': int_or_none(fmt.get('audioSampleRate')),
1408 'filesize': int_or_none(fmt.get('contentLength')),
1410 'format_note': fmt.get('qualityLabel') or quality,
1411 'fps': int_or_none(fmt.get('fps')),
1412 'height': int_or_none(fmt.get('height')),
1413 'quality': q(quality),
1414 'tbr': float_or_none(fmt.get(
1415 'averageBitrate') or fmt.get('bitrate'), 1000),
1417 'width': fmt.get('width'),
1419 mimetype = fmt.get('mimeType')
1422 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1424 dct['ext'] = mimetype2ext(mobj.group(1))
1425 dct.update(parse_codecs(mobj.group(2)))
1426 if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
1427 dct['downloader_options'] = {
1428 # Youtube throttles chunks >~10M
1429 'http_chunk_size': 10485760,
1433 hls_manifest_url = streaming_data.get('hlsManifestUrl')
1434 if hls_manifest_url:
1435 for f in self._extract_m3u8_formats(
1436 hls_manifest_url, video_id, 'mp4', fatal=False):
1437 itag = self._search_regex(
1438 r'/itag/(\d+)', f['url'], 'itag', default=None)
1440 f['format_id'] = itag
1443 if self._downloader.params.get('youtube_include_dash_manifest'):
1444 dash_manifest_url = streaming_data.get('dashManifestUrl')
1445 if dash_manifest_url:
1446 for f in self._extract_mpd_formats(
1447 dash_manifest_url, video_id, fatal=False):
1448 if f['format_id'] in itags:
1450 filesize = int_or_none(self._search_regex(
1451 r'/clen/(\d+)', f.get('fragment_base_url')
1452 or f['url'], 'file size', default=None))
1454 f['filesize'] = filesize
1458 if streaming_data.get('licenseInfos'):
1459 raise ExtractorError(
1460 'This video is DRM protected.', expected=True)
1463 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
1465 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
1466 subreason = pemr.get('subreason')
1468 subreason = clean_html(get_text(subreason))
1469 if subreason == 'The uploader has not made this video available in your country.':
1470 countries = microformat.get('availableCountries')
1472 regions_allowed = search_meta('regionsAllowed')
1473 countries = regions_allowed.split(',') if regions_allowed else None
1474 self.raise_geo_restricted(
1475 subreason, countries)
1476 reason += '\n' + subreason
1478 raise ExtractorError(reason, expected=True)
1480 self._sort_formats(formats)
1482 keywords = video_details.get('keywords') or []
1483 if not keywords and webpage:
1485 unescapeHTML(m.group('content'))
1486 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
1487 for keyword in keywords:
1488 if keyword.startswith('yt:stretch='):
1489 w, h = keyword.split('=')[1].split(':')
1490 w, h = int(w), int(h)
1494 if f.get('vcodec') != 'none':
1495 f['stretched_ratio'] = ratio
1498 for container in (video_details, microformat):
1499 for thumbnail in (try_get(
1501 lambda x: x['thumbnail']['thumbnails'], list) or []):
1502 thumbnail_url = thumbnail.get('url')
1503 if not thumbnail_url:
1506 'height': int_or_none(thumbnail.get('height')),
1507 'url': thumbnail_url,
1508 'width': int_or_none(thumbnail.get('width')),
1513 thumbnail = search_meta(['og:image', 'twitter:image'])
1515 thumbnails = [{'url': thumbnail}]
1517 category = microformat.get('category') or search_meta('genre')
1518 channel_id = video_details.get('channelId') \
1519 or microformat.get('externalChannelId') \
1520 or search_meta('channelId')
1521 duration = int_or_none(
1522 video_details.get('lengthSeconds')
1523 or microformat.get('lengthSeconds')) \
1524 or parse_duration(search_meta('duration'))
1525 is_live = video_details.get('isLive')
1526 owner_profile_url = microformat.get('ownerProfileUrl')
1530 'title': self._live_title(video_title) if is_live else video_title,
1532 'thumbnails': thumbnails,
1533 'description': video_description,
1534 'upload_date': unified_strdate(
1535 microformat.get('uploadDate')
1536 or search_meta('uploadDate')),
1537 'uploader': video_details['author'],
1538 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
1539 'uploader_url': owner_profile_url,
1540 'channel_id': channel_id,
1541 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
1542 'duration': duration,
1543 'view_count': int_or_none(
1544 video_details.get('viewCount')
1545 or microformat.get('viewCount')
1546 or search_meta('interactionCount')),
1547 'average_rating': float_or_none(video_details.get('averageRating')),
1548 'age_limit': 18 if (
1549 microformat.get('isFamilySafe') is False
1550 or search_meta('isFamilyFriendly') == 'false'
1551 or search_meta('og:restrictions:age') == '18+') else 0,
1552 'webpage_url': webpage_url,
1553 'categories': [category] if category else None,
1560 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
1562 def process_language(container, base_url, caption, query):
1564 for fmt in self._SUBTITLE_FORMATS:
1570 'url': update_url_query(base_url, query),
1572 subtitles[caption['languageCode']] = lang_subs
1575 for caption_track in pctr['captionTracks']:
1576 base_url = caption_track['baseUrl']
1577 if caption_track.get('kind') != 'asr':
1579 for fmt in self._SUBTITLE_FORMATS:
1582 'url': update_url_query(base_url, {
1586 subtitles[caption_track['languageCode']] = lang_subs
1588 automatic_captions = {}
1589 for translation_language in pctr['translationLanguages']:
1590 translation_language_code = translation_language['languageCode']
1592 for fmt in self._SUBTITLE_FORMATS:
1595 'url': update_url_query(base_url, {
1597 'tlang': translation_language_code,
1600 automatic_captions[translation_language_code] = lang_subs
1601 info['automatic_captions'] = automatic_captions
1602 info['subtitles'] = subtitles
1604 parsed_url = compat_urllib_parse_urlparse(url)
1605 for component in [parsed_url.fragment, parsed_url.query]:
1606 query = compat_parse_qs(component)
1607 for k, v in query.items():
1608 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
1610 if d_k not in info and k in s_ks:
1611 info[d_k] = parse_duration(query[k][0])
1613 if video_description:
1614 mobj = re.search(r'(?s)(?P<track>[^·\n]+)·(?P<artist>[^\n]+)\n+(?P<album>[^\n]+)(?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?(?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?(.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?.+\nAuto-generated by YouTube\.\s*$', video_description)
1616 release_year = mobj.group('release_year')
1617 release_date = mobj.group('release_date')
1619 release_date = release_date.replace('-', '')
1620 if not release_year:
1621 release_year = release_date[:4]
1623 'album': mobj.group('album'.strip()),
1624 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
1625 'track': mobj.group('track').strip(),
1626 'release_date': release_date,
1627 'release_year': int(release_year),
1632 initial_data = self._extract_yt_initial_variable(
1633 webpage, self._YT_INITIAL_DATA_RE, video_id,
1635 if not initial_data:
1636 initial_data = self._call_api(
1637 'next', {'videoId': video_id}, video_id, fatal=False)
1640 chapters = self._extract_chapters_from_json(
1641 initial_data, video_id, duration)
1643 for engagment_pannel in (initial_data.get('engagementPanels') or []):
1645 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
1650 def chapter_time(mmlir):
1651 return parse_duration(mmlir.get(
1652 get_text(mmlir.get('timeDescription'))))
1654 for next_num, content in enumerate(contents, start=1):
1655 mmlir = content.get('macroMarkersListItemRenderer') or {}
1656 start_time = chapter_time(mmlir)
1657 end_time = chapter_time(try_get(
1658 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
1659 if next_num < len(contents) else duration
1660 if not (start_time and end_time):
1663 'start_time': start_time,
1664 'end_time': end_time,
1665 'title': get_text(mmlir.get('title')),
1668 info['chapters'] = chapters
1672 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
1674 for content in contents:
1675 vpir = content.get('videoPrimaryInfoRenderer')
1677 stl = vpir.get('superTitleLink')
1682 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
1683 info['location'] = stl
1685 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
1688 'series': mobj.group(1),
1689 'season_number': int(mobj.group(2)),
1690 'episode_number': int(mobj.group(3)),
1692 for tlb in (try_get(
1694 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
1696 tbr = tlb.get('toggleButtonRenderer') or {}
1697 for getter, regex in [(
1698 lambda x: x['defaultText']['accessibility']['accessibilityData'],
1699 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
1700 lambda x: x['accessibility'],
1701 lambda x: x['accessibilityData']['accessibilityData'],
1702 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
1703 label = (try_get(tbr, getter, dict) or {}).get('label')
1705 mobj = re.match(regex, label)
1707 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
1709 sbr_tooltip = try_get(
1710 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
1712 like_count, dislike_count = sbr_tooltip.split(' / ')
1714 'like_count': str_to_int(like_count),
1715 'dislike_count': str_to_int(dislike_count),
1717 vsir = content.get('videoSecondaryInfoRenderer')
1719 info['channel'] = get_text(try_get(
1721 lambda x: x['owner']['videoOwnerRenderer']['title'],
1725 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
1727 multiple_songs = False
1729 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
1730 multiple_songs = True
1733 mrr = row.get('metadataRowRenderer') or {}
1734 mrr_title = mrr.get('title')
1737 mrr_title = get_text(mrr['title'])
1738 mrr_contents_text = get_text(mrr['contents'][0])
1739 if mrr_title == 'License':
1740 info['license'] = mrr_contents_text
1741 elif not multiple_songs:
1742 if mrr_title == 'Album':
1743 info['album'] = mrr_contents_text
1744 elif mrr_title == 'Artist':
1745 info['artist'] = mrr_contents_text
1746 elif mrr_title == 'Song':
1747 info['track'] = mrr_contents_text
1749 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
1754 self.mark_watched(video_id, player_response)
1759 class YoutubeTabIE(YoutubeBaseInfoExtractor):
1760 IE_DESC = 'YouTube.com tab'
1761 _VALID_URL = r'''(?x)
1765 youtube(?:kids)?\.com|
1769 (?:channel|c|user|feed)/|
1770 (?:playlist|watch)\?.*?\blist=|
1771 (?!(?:watch|embed|v|e)\b)
1775 IE_NAME = 'youtube:tab'
1778 # playlists, multipage
1779 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
1780 'playlist_mincount': 94,
1782 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
1783 'title': 'Игорь Клейнер - Playlists',
1784 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
1787 # playlists, multipage, different order
1788 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
1789 'playlist_mincount': 94,
1791 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
1792 'title': 'Игорь Клейнер - Playlists',
1793 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
1796 # playlists, singlepage
1797 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
1798 'playlist_mincount': 4,
1800 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
1801 'title': 'ThirstForScience - Playlists',
1802 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
1805 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
1806 'only_matching': True,
1808 # basic, single video playlist
1809 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
1811 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
1812 'uploader': 'Sergey M.',
1813 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
1814 'title': 'youtube-dl public playlist',
1816 'playlist_count': 1,
1819 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
1821 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
1822 'uploader': 'Sergey M.',
1823 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
1824 'title': 'youtube-dl empty playlist',
1826 'playlist_count': 0,
1829 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
1831 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1832 'title': 'lex will - Home',
1833 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1835 'playlist_mincount': 2,
1838 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
1840 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1841 'title': 'lex will - Videos',
1842 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1844 'playlist_mincount': 975,
1846 # Videos tab, sorted by popular
1847 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
1849 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1850 'title': 'lex will - Videos',
1851 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1853 'playlist_mincount': 199,
1856 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
1858 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1859 'title': 'lex will - Playlists',
1860 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1862 'playlist_mincount': 17,
1865 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
1867 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1868 'title': 'lex will - Community',
1869 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1871 'playlist_mincount': 18,
1874 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
1876 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
1877 'title': 'lex will - Channels',
1878 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
1880 'playlist_mincount': 138,
1882 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
1883 'only_matching': True,
1885 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
1886 'only_matching': True,
1888 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
1889 'only_matching': True,
1891 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
1892 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
1894 'title': '29C3: Not my department',
1895 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
1896 'uploader': 'Christiaan008',
1897 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
1899 'playlist_count': 96,
1901 'note': 'Large playlist',
1902 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
1904 'title': 'Uploads from Cauchemar',
1905 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
1906 'uploader': 'Cauchemar',
1907 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
1909 'playlist_mincount': 1123,
1911 # even larger playlist, 8832 videos
1912 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
1913 'only_matching': True,
1915 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
1916 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
1918 'title': 'Uploads from Interstellar Movie',
1919 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
1920 'uploader': 'Interstellar Movie',
1921 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
1923 'playlist_mincount': 21,
1925 # https://github.com/ytdl-org/youtube-dl/issues/21844
1926 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
1928 'title': 'Data Analysis with Dr Mike Pound',
1929 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
1930 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
1931 'uploader': 'Computerphile',
1933 'playlist_mincount': 11,
1935 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
1936 'only_matching': True,
1938 # Playlist URL that does not actually serve a playlist
1939 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
1941 'id': 'FqZTN594JQw',
1943 'title': "Smiley's People 01 detective, Adventure Series, Action",
1944 'uploader': 'STREEM',
1945 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
1946 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
1947 'upload_date': '20150526',
1948 'license': 'Standard YouTube License',
1949 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
1950 'categories': ['People & Blogs'],
1954 'dislike_count': int,
1957 'skip_download': True,
1959 'skip': 'This video is not available.',
1960 'add_ie': [YoutubeIE.ie_key()],
1962 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
1963 'only_matching': True,
1965 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
1966 'only_matching': True,
1968 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
1970 'id': '9Auq9mYxFEE',
1972 'title': 'Watch Sky News live',
1973 'uploader': 'Sky News',
1974 'uploader_id': 'skynews',
1975 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
1976 'upload_date': '20191102',
1977 'description': 'md5:78de4e1c2359d0ea3ed829678e38b662',
1978 'categories': ['News & Politics'],
1981 'dislike_count': int,
1984 'skip_download': True,
1987 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
1989 'id': 'a48o2S1cPoo',
1991 'title': 'The Young Turks - Live Main Show',
1992 'uploader': 'The Young Turks',
1993 'uploader_id': 'TheYoungTurks',
1994 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
1995 'upload_date': '20150715',
1996 'license': 'Standard YouTube License',
1997 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
1998 'categories': ['News & Politics'],
1999 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2001 'dislike_count': int,
2004 'skip_download': True,
2006 'only_matching': True,
2008 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2009 'only_matching': True,
2011 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2012 'only_matching': True,
2014 'url': 'https://www.youtube.com/feed/trending',
2015 'only_matching': True,
2018 'url': 'https://www.youtube.com/feed/library',
2019 'only_matching': True,
2022 'url': 'https://www.youtube.com/feed/history',
2023 'only_matching': True,
2026 'url': 'https://www.youtube.com/feed/subscriptions',
2027 'only_matching': True,
2030 'url': 'https://www.youtube.com/feed/watch_later',
2031 'only_matching': True,
2033 # no longer available?
2034 'url': 'https://www.youtube.com/feed/recommended',
2035 'only_matching': True,
2037 # inline playlist with not always working continuations
2038 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2039 'only_matching': True,
2041 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2042 'only_matching': True,
2044 'url': 'https://www.youtube.com/course',
2045 'only_matching': True,
2047 'url': 'https://www.youtube.com/zsecurity',
2048 'only_matching': True,
2050 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2051 'only_matching': True,
2053 'url': 'https://www.youtube.com/TheYoungTurks/live',
2054 'only_matching': True,
2058 def suitable(cls, url):
2059 return False if YoutubeIE.suitable(url) else super(
2060 YoutubeTabIE, cls).suitable(url)
2062 def _extract_channel_id(self, webpage):
2063 channel_id = self._html_search_meta(
2064 'channelId', webpage, 'channel id', default=None)
2067 channel_url = self._html_search_meta(
2068 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2069 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2070 'twitter:app:url:googleplay'), webpage, 'channel url')
2071 return self._search_regex(
2072 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2073 channel_url, 'channel id')
2076 def _extract_grid_item_renderer(item):
2077 for item_kind in ('Playlist', 'Video', 'Channel'):
2078 renderer = item.get('grid%sRenderer' % item_kind)
2082 def _grid_entries(self, grid_renderer):
2083 for item in grid_renderer['items']:
2084 if not isinstance(item, dict):
2086 renderer = self._extract_grid_item_renderer(item)
2087 if not isinstance(renderer, dict):
2090 renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2092 playlist_id = renderer.get('playlistId')
2094 yield self.url_result(
2095 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2096 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2099 video_id = renderer.get('videoId')
2101 yield self._extract_video(renderer)
2103 channel_id = renderer.get('channelId')
2106 renderer, lambda x: x['title']['simpleText'], compat_str)
2107 yield self.url_result(
2108 'https://www.youtube.com/channel/%s' % channel_id,
2109 ie=YoutubeTabIE.ie_key(), video_title=title)
2111 def _shelf_entries_from_content(self, shelf_renderer):
2112 content = shelf_renderer.get('content')
2113 if not isinstance(content, dict):
2115 renderer = content.get('gridRenderer')
2117 # TODO: add support for nested playlists so each shelf is processed
2118 # as separate playlist
2119 # TODO: this includes only first N items
2120 for entry in self._grid_entries(renderer):
2122 renderer = content.get('horizontalListRenderer')
2127 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2129 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2131 shelf_url = urljoin('https://www.youtube.com', ep)
2133 # Skipping links to another channels, note that checking for
2134 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2136 if skip_channels and '/channels?' in shelf_url:
2139 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2140 yield self.url_result(shelf_url, video_title=title)
2141 # Shelf may not contain shelf URL, fallback to extraction from content
2142 for entry in self._shelf_entries_from_content(shelf_renderer):
2145 def _playlist_entries(self, video_list_renderer):
2146 for content in video_list_renderer['contents']:
2147 if not isinstance(content, dict):
2149 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2150 if not isinstance(renderer, dict):
2152 video_id = renderer.get('videoId')
2155 yield self._extract_video(renderer)
2157 def _video_entry(self, video_renderer):
2158 video_id = video_renderer.get('videoId')
2160 return self._extract_video(video_renderer)
2162 def _post_thread_entries(self, post_thread_renderer):
2163 post_renderer = try_get(
2164 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2165 if not post_renderer:
2168 video_renderer = try_get(
2169 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2172 entry = self._video_entry(video_renderer)
2175 # inline video links
2176 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2178 if not isinstance(run, dict):
2181 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2184 if not YoutubeIE.suitable(ep_url):
2186 ep_video_id = YoutubeIE._match_id(ep_url)
2187 if video_id == ep_video_id:
2189 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2191 def _post_thread_continuation_entries(self, post_thread_continuation):
2192 contents = post_thread_continuation.get('contents')
2193 if not isinstance(contents, list):
2195 for content in contents:
2196 renderer = content.get('backstagePostThreadRenderer')
2197 if not isinstance(renderer, dict):
2199 for entry in self._post_thread_entries(renderer):
2203 def _build_continuation_query(continuation, ctp=None):
2205 'ctoken': continuation,
2206 'continuation': continuation,
2213 def _extract_next_continuation_data(renderer):
2214 next_continuation = try_get(
2215 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2216 if not next_continuation:
2218 continuation = next_continuation.get('continuation')
2219 if not continuation:
2221 ctp = next_continuation.get('clickTrackingParams')
2222 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2225 def _extract_continuation(cls, renderer):
2226 next_continuation = cls._extract_next_continuation_data(renderer)
2227 if next_continuation:
2228 return next_continuation
2229 contents = renderer.get('contents')
2230 if not isinstance(contents, list):
2232 for content in contents:
2233 if not isinstance(content, dict):
2235 continuation_ep = try_get(
2236 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2238 if not continuation_ep:
2240 continuation = try_get(
2241 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2242 if not continuation:
2244 ctp = continuation_ep.get('clickTrackingParams')
2245 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2247 def _entries(self, tab, identity_token):
2248 tab_content = try_get(tab, lambda x: x['content'], dict)
2251 slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
2252 if not slr_renderer:
2254 is_channels_tab = tab.get('title') == 'Channels'
2256 slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
2257 for slr_content in slr_contents:
2258 if not isinstance(slr_content, dict):
2260 is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
2263 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2264 for isr_content in isr_contents:
2265 if not isinstance(isr_content, dict):
2267 renderer = isr_content.get('playlistVideoListRenderer')
2269 for entry in self._playlist_entries(renderer):
2271 continuation = self._extract_continuation(renderer)
2273 renderer = isr_content.get('gridRenderer')
2275 for entry in self._grid_entries(renderer):
2277 continuation = self._extract_continuation(renderer)
2279 renderer = isr_content.get('shelfRenderer')
2281 for entry in self._shelf_entries(renderer, not is_channels_tab):
2284 renderer = isr_content.get('backstagePostThreadRenderer')
2286 for entry in self._post_thread_entries(renderer):
2288 continuation = self._extract_continuation(renderer)
2290 renderer = isr_content.get('videoRenderer')
2292 entry = self._video_entry(renderer)
2296 if not continuation:
2297 continuation = self._extract_continuation(is_renderer)
2299 if not continuation:
2300 continuation = self._extract_continuation(slr_renderer)
2303 'x-youtube-client-name': '1',
2304 'x-youtube-client-version': '2.20201112.04.01',
2307 headers['x-youtube-identity-token'] = identity_token
2309 for page_num in itertools.count(1):
2310 if not continuation:
2314 while count <= retries:
2316 # Downloading page may result in intermittent 5xx HTTP error
2317 # that is usually worked around with a retry
2318 browse = self._download_json(
2319 'https://www.youtube.com/browse_ajax', None,
2320 'Downloading page %d%s'
2321 % (page_num, ' (retry #%d)' % count if count else ''),
2322 headers=headers, query=continuation)
2324 except ExtractorError as e:
2325 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
2327 if count <= retries:
2332 response = try_get(browse, lambda x: x[1]['response'], dict)
2336 continuation_contents = try_get(
2337 response, lambda x: x['continuationContents'], dict)
2338 if continuation_contents:
2339 continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
2340 if continuation_renderer:
2341 for entry in self._playlist_entries(continuation_renderer):
2343 continuation = self._extract_continuation(continuation_renderer)
2345 continuation_renderer = continuation_contents.get('gridContinuation')
2346 if continuation_renderer:
2347 for entry in self._grid_entries(continuation_renderer):
2349 continuation = self._extract_continuation(continuation_renderer)
2351 continuation_renderer = continuation_contents.get('itemSectionContinuation')
2352 if continuation_renderer:
2353 for entry in self._post_thread_continuation_entries(continuation_renderer):
2355 continuation = self._extract_continuation(continuation_renderer)
2358 continuation_items = try_get(
2359 response, lambda x: x['onResponseReceivedActions'][0]['appendContinuationItemsAction']['continuationItems'], list)
2360 if continuation_items:
2361 continuation_item = continuation_items[0]
2362 if not isinstance(continuation_item, dict):
2364 renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
2366 video_list_renderer = {'contents': continuation_items}
2367 for entry in self._playlist_entries(video_list_renderer):
2369 continuation = self._extract_continuation(video_list_renderer)
2375 def _extract_selected_tab(tabs):
2377 if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
2378 return tab['tabRenderer']
2380 raise ExtractorError('Unable to find selected tab')
2383 def _extract_uploader(data):
2385 sidebar_renderer = try_get(
2386 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
2387 if sidebar_renderer:
2388 for item in sidebar_renderer:
2389 if not isinstance(item, dict):
2391 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
2392 if not isinstance(renderer, dict):
2395 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
2397 uploader['uploader'] = owner.get('text')
2398 uploader['uploader_id'] = try_get(
2399 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
2400 uploader['uploader_url'] = urljoin(
2401 'https://www.youtube.com/',
2402 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
2406 def _extract_alert(data):
2408 for alert in try_get(data, lambda x: x['alerts'], list) or []:
2409 if not isinstance(alert, dict):
2411 alert_text = try_get(
2412 alert, lambda x: x['alertRenderer']['text'], dict)
2417 (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
2421 return '\n'.join(alerts)
2423 def _extract_from_tabs(self, item_id, webpage, data, tabs, identity_token):
2424 selected_tab = self._extract_selected_tab(tabs)
2426 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
2427 playlist_id = title = description = None
2429 channel_title = renderer.get('title') or item_id
2430 tab_title = selected_tab.get('title')
2431 title = channel_title or item_id
2433 title += ' - %s' % tab_title
2434 description = renderer.get('description')
2435 playlist_id = renderer.get('externalId')
2437 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
2439 title = renderer.get('title')
2441 playlist_id = item_id
2442 playlist = self.playlist_result(
2443 self._entries(selected_tab, identity_token),
2444 playlist_id=playlist_id, playlist_title=title,
2445 playlist_description=description)
2446 playlist.update(self._extract_uploader(data))
2449 def _extract_from_playlist(self, item_id, url, data, playlist):
2450 title = playlist.get('title') or try_get(
2451 data, lambda x: x['titleText']['simpleText'], compat_str)
2452 playlist_id = playlist.get('playlistId') or item_id
2453 # Inline playlist rendition continuation does not always work
2454 # at Youtube side, so delegating regular tab-based playlist URL
2455 # processing whenever possible.
2456 playlist_url = urljoin(url, try_get(
2457 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2459 if playlist_url and playlist_url != url:
2460 return self.url_result(
2461 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2463 return self.playlist_result(
2464 self._playlist_entries(playlist), playlist_id=playlist_id,
2465 playlist_title=title)
2467 def _extract_identity_token(self, webpage, item_id):
2468 ytcfg = self._extract_ytcfg(item_id, webpage)
2470 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
2473 return self._search_regex(
2474 r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
2475 'identity token', default=None)
2477 def _real_extract(self, url):
2478 item_id = self._match_id(url)
2479 url = compat_urlparse.urlunparse(
2480 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
2481 # Handle both video/playlist URLs
2482 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
2483 video_id = qs.get('v', [None])[0]
2484 playlist_id = qs.get('list', [None])[0]
2485 if video_id and playlist_id:
2486 if self._downloader.params.get('noplaylist'):
2487 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
2488 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2489 self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
2490 webpage = self._download_webpage(url, item_id)
2491 identity_token = self._extract_identity_token(webpage, item_id)
2492 data = self._extract_yt_initial_data(item_id, webpage)
2494 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
2496 return self._extract_from_tabs(item_id, webpage, data, tabs, identity_token)
2498 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
2500 return self._extract_from_playlist(item_id, url, data, playlist)
2501 # Fallback to video extraction if no playlist alike page is recognized.
2502 # First check for the current video then try the v attribute of URL query.
2504 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
2505 compat_str) or video_id
2507 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2508 # Capture and output alerts
2509 alert = self._extract_alert(data)
2511 raise ExtractorError(alert, expected=True)
2512 # Failed to recognize
2513 raise ExtractorError('Unable to recognize tab page')
2516 class YoutubePlaylistIE(InfoExtractor):
2517 IE_DESC = 'YouTube.com playlists'
2518 _VALID_URL = r'''(?x)(?:
2523 youtube(?:kids)?\.com|
2528 (?P<id>%(playlist_id)s)
2529 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
2530 IE_NAME = 'youtube:playlist'
2532 'note': 'issue #673',
2533 'url': 'PLBB231211A4F62143',
2535 'title': '[OLD]Team Fortress 2 (Class-based LP)',
2536 'id': 'PLBB231211A4F62143',
2537 'uploader': 'Wickydoo',
2538 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
2540 'playlist_mincount': 29,
2542 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2544 'title': 'YDL_safe_search',
2545 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2547 'playlist_count': 2,
2548 'skip': 'This playlist is private',
2551 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2552 'playlist_count': 4,
2555 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2556 'uploader': 'milan',
2557 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
2560 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2561 'playlist_mincount': 982,
2563 'title': '2018 Chinese New Singles (11/6 updated)',
2564 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2566 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
2569 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
2570 'only_matching': True,
2572 # music album playlist
2573 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
2574 'only_matching': True,
2578 def suitable(cls, url):
2579 return False if YoutubeTabIE.suitable(url) else super(
2580 YoutubePlaylistIE, cls).suitable(url)
2582 def _real_extract(self, url):
2583 playlist_id = self._match_id(url)
2584 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
2586 qs = {'list': playlist_id}
2587 return self.url_result(
2588 update_url_query('https://www.youtube.com/playlist', qs),
2589 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2592 class YoutubeYtBeIE(InfoExtractor):
2593 _VALID_URL = r'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{11})/*?.*?\blist=(?P<playlist_id>%(playlist_id)s)' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
2595 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
2597 'id': 'yeWKywCrFtk',
2599 'title': 'Small Scale Baler and Braiding Rugs',
2600 'uploader': 'Backus-Page House Museum',
2601 'uploader_id': 'backuspagemuseum',
2602 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
2603 'upload_date': '20161008',
2604 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
2605 'categories': ['Nonprofits & Activism'],
2608 'dislike_count': int,
2612 'skip_download': True,
2615 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
2616 'only_matching': True,
2619 def _real_extract(self, url):
2620 mobj = re.match(self._VALID_URL, url)
2621 video_id = mobj.group('id')
2622 playlist_id = mobj.group('playlist_id')
2623 return self.url_result(
2624 update_url_query('https://www.youtube.com/watch', {
2626 'list': playlist_id,
2627 'feature': 'youtu.be',
2628 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2631 class YoutubeYtUserIE(InfoExtractor):
2632 _VALID_URL = r'ytuser:(?P<id>.+)'
2634 'url': 'ytuser:phihag',
2635 'only_matching': True,
2638 def _real_extract(self, url):
2639 user_id = self._match_id(url)
2640 return self.url_result(
2641 'https://www.youtube.com/user/%s' % user_id,
2642 ie=YoutubeTabIE.ie_key(), video_id=user_id)
2645 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
2646 IE_NAME = 'youtube:favorites'
2647 IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
2648 _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
2649 _LOGIN_REQUIRED = True
2652 'only_matching': True,
2654 'url': ':ytfavorites',
2655 'only_matching': True,
2658 def _real_extract(self, url):
2659 return self.url_result(
2660 'https://www.youtube.com/playlist?list=LL',
2661 ie=YoutubeTabIE.ie_key())
2664 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
2665 IE_DESC = 'YouTube.com searches'
2666 # there doesn't appear to be a real limit, for example if you search for
2667 # 'python' you get more than 8.000.000 results
2668 _MAX_RESULTS = float('inf')
2669 IE_NAME = 'youtube:search'
2670 _SEARCH_KEY = 'ytsearch'
2671 _SEARCH_PARAMS = None
2674 def _entries(self, query, n):
2678 'clientName': 'WEB',
2679 'clientVersion': '2.20201021.03.00',
2684 if self._SEARCH_PARAMS:
2685 data['params'] = self._SEARCH_PARAMS
2687 for page_num in itertools.count(1):
2688 search = self._download_json(
2689 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
2690 video_id='query "%s"' % query,
2691 note='Downloading page %s' % page_num,
2692 errnote='Unable to download API page', fatal=False,
2693 data=json.dumps(data).encode('utf8'),
2694 headers={'content-type': 'application/json'})
2697 slr_contents = try_get(
2699 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
2700 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
2702 if not slr_contents:
2704 for slr_content in slr_contents:
2705 isr_contents = try_get(
2707 lambda x: x['itemSectionRenderer']['contents'],
2709 if not isr_contents:
2711 for content in isr_contents:
2712 if not isinstance(content, dict):
2714 video = content.get('videoRenderer')
2715 if not isinstance(video, dict):
2717 video_id = video.get('videoId')
2720 yield self._extract_video(video)
2726 lambda x: x[-1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
2730 data['continuation'] = token
2732 def _get_n_results(self, query, n):
2733 """Get a specified number of results for a query"""
2734 return self.playlist_result(self._entries(query, n), query)
2737 class YoutubeSearchDateIE(YoutubeSearchIE):
2738 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
2739 _SEARCH_KEY = 'ytsearchdate'
2740 IE_DESC = 'YouTube.com searches, newest videos first'
2741 _SEARCH_PARAMS = 'CAI%3D'
2745 class YoutubeSearchURLIE(YoutubeSearchIE):
2746 IE_DESC = 'YouTube.com search URLs'
2747 IE_NAME = 'youtube:search_url'
2748 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
2750 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
2751 'playlist_mincount': 5,
2753 'title': 'youtube-dl test video',
2756 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
2757 'only_matching': True,
2760 def _real_extract(self, url):
2761 mobj = re.match(self._VALID_URL, url)
2762 query = compat_urllib_parse_unquote_plus(mobj.group('query'))
2763 webpage = self._download_webpage(url, query)
2764 return self.playlist_result(self._process_page(webpage), playlist_title=query)
2768 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
2770 Base class for feed extractors
2771 Subclasses must define the _FEED_NAME property.
2773 _LOGIN_REQUIRED = True
2777 return 'youtube:%s' % self._FEED_NAME
2779 def _real_initialize(self):
2782 def _real_extract(self, url):
2783 return self.url_result(
2784 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
2785 ie=YoutubeTabIE.ie_key())
2788 class YoutubeWatchLaterIE(InfoExtractor):
2789 IE_NAME = 'youtube:watchlater'
2790 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
2791 _VALID_URL = r':ytwatchlater'
2793 'url': ':ytwatchlater',
2794 'only_matching': True,
2797 def _real_extract(self, url):
2798 return self.url_result(
2799 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
2802 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
2803 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
2804 _VALID_URL = r':ytrec(?:ommended)?'
2805 _FEED_NAME = 'recommended'
2808 'only_matching': True,
2810 'url': ':ytrecommended',
2811 'only_matching': True,
2815 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
2816 IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
2817 _VALID_URL = r':ytsubs(?:criptions)?'
2818 _FEED_NAME = 'subscriptions'
2821 'only_matching': True,
2823 'url': ':ytsubscriptions',
2824 'only_matching': True,
2828 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
2829 IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
2830 _VALID_URL = r':ythistory'
2831 _FEED_NAME = 'history'
2833 'url': ':ythistory',
2834 'only_matching': True,
2838 class YoutubeTruncatedURLIE(InfoExtractor):
2839 IE_NAME = 'youtube:truncated_url'
2840 IE_DESC = False # Do not list
2841 _VALID_URL = r'''(?x)
2843 (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
2846 annotation_id=annotation_[^&]+|
2852 attribution_link\?a=[^&]+
2858 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
2859 'only_matching': True,
2861 'url': 'https://www.youtube.com/watch?',
2862 'only_matching': True,
2864 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
2865 'only_matching': True,
2867 'url': 'https://www.youtube.com/watch?feature=foo',
2868 'only_matching': True,
2870 'url': 'https://www.youtube.com/watch?hl=en-GB',
2871 'only_matching': True,
2873 'url': 'https://www.youtube.com/watch?t=2372',
2874 'only_matching': True,
2877 def _real_extract(self, url):
2878 raise ExtractorError(
2879 'Did you forget to quote the URL? Remember that & is a meta '
2880 'character in most shells, so you want to put the URL in quotes, '
2882 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
2883 ' or simply youtube-dl BaW_jenozKc .',
2887 class YoutubeTruncatedIDIE(InfoExtractor):
2888 IE_NAME = 'youtube:truncated_id'
2889 IE_DESC = False # Do not list
2890 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
2893 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
2894 'only_matching': True,
2897 def _real_extract(self, url):
2898 video_id = self._match_id(url)
2899 raise ExtractorError(
2900 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),