3 from __future__
import unicode_literals
15 from .common
import InfoExtractor
, SearchInfoExtractor
16 from ..compat
import (
21 compat_urllib_parse_unquote_plus
,
22 compat_urllib_parse_urlencode
,
23 compat_urllib_parse_urlparse
,
26 from ..jsinterp
import JSInterpreter
55 class YoutubeBaseInfoExtractor(InfoExtractor
):
56 """Provide base functions for Youtube extractors"""
57 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
58 _TWOFACTOR_URL
= 'https://accounts.google.com/signin/challenge'
60 _LOOKUP_URL
= 'https://accounts.google.com/_/signin/sl/lookup'
61 _CHALLENGE_URL
= 'https://accounts.google.com/_/signin/sl/challenge'
62 _TFA_URL
= 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
65 r
'channel|c|user|playlist|watch|w|v|embed|e|watch_popup|'
66 r
'movies|results|shared|hashtag|trending|feed|feeds|'
67 r
'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout')
69 _NETRC_MACHINE
= 'youtube'
70 # If True it will raise an error if no login info is provided
71 _LOGIN_REQUIRED
= False
73 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
75 def _ids_to_results(self
, ids
):
77 self
.url_result(vid_id
, 'Youtube', video_id
=vid_id
)
82 Attempt to log in to YouTube.
83 True is returned if successful or skipped.
84 False is returned if login failed.
86 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
88 username
, password
= self
._get
_login
_info
()
89 # No authentication to be performed
91 if self
._LOGIN
_REQUIRED
and self
._downloader
.params
.get('cookiefile') is None:
92 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
93 # if self._downloader.params.get('cookiefile'): # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
94 # self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
97 login_page
= self
._download
_webpage
(
98 self
._LOGIN
_URL
, None,
99 note
='Downloading login page',
100 errnote
='unable to fetch login page', fatal
=False)
101 if login_page
is False:
104 login_form
= self
._hidden
_inputs
(login_page
)
106 def req(url
, f_req
, note
, errnote
):
107 data
= login_form
.copy()
110 'checkConnection': 'youtube',
111 'checkedDomains': 'youtube',
113 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
114 'f.req': json
.dumps(f_req
),
115 'flowName': 'GlifWebSignIn',
116 'flowEntry': 'ServiceLogin',
117 # TODO: reverse actual botguard identifier generation algo
118 'bgRequest': '["identifier",""]',
120 return self
._download
_json
(
121 url
, None, note
=note
, errnote
=errnote
,
122 transform_source
=lambda s
: re
.sub(r
'^[^[]*', '', s
),
124 data
=urlencode_postdata(data
), headers
={
125 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
126 'Google-Accounts-XSRF': 1,
130 self
._downloader
.report_warning(message
)
134 None, [], None, 'US', None, None, 2, False, True,
138 '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',
140 1, [None, None, []], None, None, None, True
145 lookup_results
= req(
146 self
._LOOKUP
_URL
, lookup_req
,
147 'Looking up account info', 'Unable to look up account info')
149 if lookup_results
is False:
152 user_hash
= try_get(lookup_results
, lambda x
: x
[0][2], compat_str
)
154 warn('Unable to extract user hash')
159 None, 1, None, [1, None, None, None, [password
, None, True]],
161 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],
162 1, [None, None, []], None, None, None, True
165 challenge_results
= req(
166 self
._CHALLENGE
_URL
, challenge_req
,
167 'Logging in', 'Unable to log in')
169 if challenge_results
is False:
172 login_res
= try_get(challenge_results
, lambda x
: x
[0][5], list)
174 login_msg
= try_get(login_res
, lambda x
: x
[5], compat_str
)
176 'Unable to login: %s' % 'Invalid password'
177 if login_msg
== 'INCORRECT_ANSWER_ENTERED' else login_msg
)
180 res
= try_get(challenge_results
, lambda x
: x
[0][-1], list)
182 warn('Unable to extract result entry')
185 login_challenge
= try_get(res
, lambda x
: x
[0][0], list)
187 challenge_str
= try_get(login_challenge
, lambda x
: x
[2], compat_str
)
188 if challenge_str
== 'TWO_STEP_VERIFICATION':
189 # SEND_SUCCESS - TFA code has been successfully sent to phone
190 # QUOTA_EXCEEDED - reached the limit of TFA codes
191 status
= try_get(login_challenge
, lambda x
: x
[5], compat_str
)
192 if status
== 'QUOTA_EXCEEDED':
193 warn('Exceeded the limit of TFA codes, try later')
196 tl
= try_get(challenge_results
, lambda x
: x
[1][2], compat_str
)
198 warn('Unable to extract TL')
201 tfa_code
= self
._get
_tfa
_info
('2-step verification code')
205 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
206 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
209 tfa_code
= remove_start(tfa_code
, 'G-')
212 user_hash
, None, 2, None,
214 9, None, None, None, None, None, None, None,
215 [None, tfa_code
, True, 2]
219 self
._TFA
_URL
.format(tl
), tfa_req
,
220 'Submitting TFA code', 'Unable to submit TFA code')
222 if tfa_results
is False:
225 tfa_res
= try_get(tfa_results
, lambda x
: x
[0][5], list)
227 tfa_msg
= try_get(tfa_res
, lambda x
: x
[5], compat_str
)
229 'Unable to finish TFA: %s' % 'Invalid TFA code'
230 if tfa_msg
== 'INCORRECT_ANSWER_ENTERED' else tfa_msg
)
233 check_cookie_url
= try_get(
234 tfa_results
, lambda x
: x
[0][-1][2], compat_str
)
237 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
238 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
239 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
241 challenge
= CHALLENGES
.get(
243 '%s returned error %s.' % (self
.IE_NAME
, challenge_str
))
244 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge
)
247 check_cookie_url
= try_get(res
, lambda x
: x
[2], compat_str
)
249 if not check_cookie_url
:
250 warn('Unable to extract CheckCookie URL')
253 check_cookie_results
= self
._download
_webpage
(
254 check_cookie_url
, None, 'Checking cookie', fatal
=False)
256 if check_cookie_results
is False:
259 if 'https://myaccount.google.com/' not in check_cookie_results
:
260 warn('Unable to log in')
265 def _initialize_consent(self
):
266 cookies
= self
._get
_cookies
('https://www.youtube.com/')
267 if cookies
.get('__Secure-3PSID'):
270 consent
= cookies
.get('CONSENT')
272 if 'YES' in consent
.value
:
274 consent_id
= self
._search
_regex
(
275 r
'PENDING\+(\d+)', consent
.value
, 'consent', default
=None)
277 consent_id
= random
.randint(100, 999)
278 self
._set
_cookie
('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id
)
280 def _real_initialize(self
):
281 self
._initialize
_consent
()
282 if self
._downloader
is None:
284 if not self
._login
():
287 _YT_WEB_CLIENT_VERSION
= '2.20210407.08.00'
288 _YT_INNERTUBE_API_KEY
= 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
289 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
290 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
291 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
293 def _generate_sapisidhash_header(self):
294 sapisid_cookie = self._get_cookies('https://www.youtube.com').get('SAPISID')
295 if sapisid_cookie is None:
297 time_now = round(time.time())
298 sapisidhash = hashlib.sha1((str(time_now) + " " + sapisid_cookie.value + " " + "https
://www
.youtube
.com
").encode("utf
-8")).hexdigest()
299 return "SAPISIDHASH
%s_%s" % (time_now, sapisidhash)
301 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
302 note='Downloading API JSON', errnote='Unable to download API page',
303 context=None, api_key=None):
305 data = {'context': context} if context else {'context': self._extract_context()}
307 real_headers = self._generate_api_headers()
308 real_headers.update({'content-type': 'application/json'})
310 real_headers.update(headers)
311 return self._download_json(
312 'https://www.youtube.com/youtubei/v1/%s' % ep,
313 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
314 data=json.dumps(data).encode('utf8'), headers=real_headers,
315 query={'key': api_key or self._extract_api_key()})
317 def _extract_api_key(self, ytcfg=None):
318 return try_get(ytcfg, lambda x: x['INNERTUBE_API_KEY'], compat_str) or self._YT_INNERTUBE_API_KEY
320 def _extract_yt_initial_data(self, video_id, webpage):
321 return self._parse_json(
323 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
324 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
327 def _extract_identity_token(self, webpage, item_id):
328 ytcfg = self._extract_ytcfg(item_id, webpage)
330 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
333 return self._search_regex(
334 r'\bID_TOKEN["\']\s
*:\s
*["\'](.+?)["\']', webpage,
335 'identity token
', default=None)
338 def _extract_account_syncid(data):
339 """Extract syncId required to download private playlists of secondary channels"""
341 try_get(data, lambda x: x['responseContext
']['mainAppWebResponseContext
']['datasyncId
'], compat_str)
343 if len(sync_ids) >= 2 and sync_ids[1]:
344 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
345 # and just "user_syncid||" for primary channel. We only want the channel_syncid
348 def _extract_ytcfg(self, video_id, webpage):
349 return self._parse_json(
351 r'ytcfg\
.set\s
*\
(\s
*({.+?}
)\s
*\
)\s
*;', webpage, 'ytcfg
',
352 default='{}'), video_id, fatal=False) or {}
354 def __extract_client_version(self
, ytcfg
):
355 return try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_VERSION'], compat_str
) or self
._YT
_WEB
_CLIENT
_VERSION
357 def _extract_context(self
, ytcfg
=None):
358 context
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CONTEXT'], dict)
362 # Recreate the client context (required)
363 client_version
= self
.__extract
_client
_version
(ytcfg
)
364 client_name
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_NAME'], compat_str
) or 'WEB'
367 'clientName': client_name
,
368 'clientVersion': client_version
,
371 visitor_data
= try_get(ytcfg
, lambda x
: x
['VISITOR_DATA'], compat_str
)
373 context
['client']['visitorData'] = visitor_data
376 def _generate_api_headers(self
, ytcfg
=None, identity_token
=None, account_syncid
=None, visitor_data
=None):
378 'X-YouTube-Client-Name': '1',
379 'X-YouTube-Client-Version': self
.__extract
_client
_version
(ytcfg
),
382 headers
['x-youtube-identity-token'] = identity_token
384 headers
['X-Goog-PageId'] = account_syncid
385 headers
['X-Goog-AuthUser'] = 0
387 headers
['x-goog-visitor-id'] = visitor_data
388 auth
= self
._generate
_sapisidhash
_header
()
390 headers
['Authorization'] = auth
391 headers
['X-Origin'] = 'https://www.youtube.com'
394 def _extract_video(self
, renderer
):
395 video_id
= renderer
.get('videoId')
398 (lambda x
: x
['title']['runs'][0]['text'],
399 lambda x
: x
['title']['simpleText']), compat_str
)
400 description
= try_get(
401 renderer
, lambda x
: x
['descriptionSnippet']['runs'][0]['text'],
403 duration
= parse_duration(try_get(
404 renderer
, lambda x
: x
['lengthText']['simpleText'], compat_str
))
405 view_count_text
= try_get(
406 renderer
, lambda x
: x
['viewCountText']['simpleText'], compat_str
) or ''
407 view_count
= str_to_int(self
._search
_regex
(
408 r
'^([\d,]+)', re
.sub(r
'\s', '', view_count_text
),
409 'view count', default
=None))
412 (lambda x
: x
['ownerText']['runs'][0]['text'],
413 lambda x
: x
['shortBylineText']['runs'][0]['text']), compat_str
)
416 'ie_key': YoutubeIE
.ie_key(),
420 'description': description
,
421 'duration': duration
,
422 'view_count': view_count
,
423 'uploader': uploader
,
427 class YoutubeIE(YoutubeBaseInfoExtractor
):
428 IE_DESC
= 'YouTube.com'
430 # invidious-redirect websites
431 r
'(?:www\.)?redirect\.invidious\.io',
432 r
'(?:(?:www|dev)\.)?invidio\.us',
433 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
434 r
'(?:www\.)?invidious\.pussthecat\.org',
435 r
'(?:www\.)?invidious\.048596\.xyz',
436 r
'(?:www\.)?invidious\.zee\.li',
437 r
'(?:www\.)?vid\.puffyan\.us',
438 r
'(?:(?:www|au)\.)?ytprivate\.com',
439 r
'(?:www\.)?invidious\.namazso\.eu',
440 r
'(?:www\.)?invidious\.ethibox\.fr',
441 r
'(?:www\.)?inv\.skyn3t\.in',
442 r
'(?:www\.)?invidious\.himiko\.cloud',
443 r
'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
444 r
'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
445 r
'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
446 r
'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
447 # youtube-dl invidious instances list
448 r
'(?:(?:www|no)\.)?invidiou\.sh',
449 r
'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
450 r
'(?:www\.)?invidious\.kabi\.tk',
451 r
'(?:www\.)?invidious\.13ad\.de',
452 r
'(?:www\.)?invidious\.mastodon\.host',
453 r
'(?:www\.)?invidious\.zapashcanon\.fr',
454 r
'(?:www\.)?invidious\.kavin\.rocks',
455 r
'(?:www\.)?invidious\.tube',
456 r
'(?:www\.)?invidiou\.site',
457 r
'(?:www\.)?invidious\.site',
458 r
'(?:www\.)?invidious\.xyz',
459 r
'(?:www\.)?invidious\.nixnet\.xyz',
460 r
'(?:www\.)?invidious\.drycat\.fr',
461 r
'(?:www\.)?tube\.poal\.co',
462 r
'(?:www\.)?tube\.connect\.cafe',
463 r
'(?:www\.)?vid\.wxzm\.sx',
464 r
'(?:www\.)?vid\.mint\.lgbt',
465 r
'(?:www\.)?yewtu\.be',
466 r
'(?:www\.)?yt\.elukerio\.org',
467 r
'(?:www\.)?yt\.lelux\.fi',
468 r
'(?:www\.)?invidious\.ggc-project\.de',
469 r
'(?:www\.)?yt\.maisputain\.ovh',
470 r
'(?:www\.)?invidious\.toot\.koeln',
471 r
'(?:www\.)?invidious\.fdn\.fr',
472 r
'(?:www\.)?watch\.nettohikari\.com',
473 r
'(?:www\.)?kgg2m7yk5aybusll\.onion',
474 r
'(?:www\.)?qklhadlycap4cnod\.onion',
475 r
'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
476 r
'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
477 r
'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
478 r
'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
479 r
'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
480 r
'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
482 _VALID_URL
= r
"""(?x)^
484 (?:https?://|//) # http(s):// or protocol-independent URL
485 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
486 (?:www\.)?deturl\.com/www\.youtube\.com|
487 (?:www\.)?pwnyoutube\.com|
488 (?:www\.)?hooktube\.com|
489 (?:www\.)?yourepeat\.com|
492 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
493 (?:.*?\#/)? # handle anchor (#/) redirect urls
494 (?: # the various things that can precede the ID:
495 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
496 |(?: # or the v= param in all its forms
497 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
498 (?:\?|\#!?) # the params delimiter ? or # or #!
499 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
504 youtu\.be| # just youtu.be/xxxx
505 vid\.plus| # or vid.plus/xxxx
506 zwearz\.com/watch| # or zwearz.com/watch/xxxx
509 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
511 )? # all until now is optional -> you can pass the naked ID
512 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
515 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
516 WL # WL are handled by the watch later IE
519 (?(1).+)? # if we found the ID, everything can follow
521 'playlist_id': YoutubeBaseInfoExtractor
._PLAYLIST
_ID
_RE
,
522 'invidious': '|'.join(_INVIDIOUS_SITES
),
525 r
'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
526 r
'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
527 r
'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
530 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
531 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
532 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'}
,
533 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'}
,
534 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'}
,
535 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
536 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
537 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
538 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
539 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'}
,
540 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
541 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
542 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
543 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
544 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
545 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
546 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
547 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
551 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
552 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
553 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
554 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
555 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20}
,
556 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
557 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
559 # Apple HTTP Live Streaming
560 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
561 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
562 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
563 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
564 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
565 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
566 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
567 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10}
,
570 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
571 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
572 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
573 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
574 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
575 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}
, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
576 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
577 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
578 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
579 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
580 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
581 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
584 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'}
,
585 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'}
,
586 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'}
,
587 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
588 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
589 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'}
,
590 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'}
,
593 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
594 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
595 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
596 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
597 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
598 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
599 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'}
,
600 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
601 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
602 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
603 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
604 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
605 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
606 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
607 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
608 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
609 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
610 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
611 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
612 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
613 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
614 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
617 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128}
,
618 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256}
,
620 # Dash webm audio with opus inside
621 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50}
,
622 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70}
,
623 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160}
,
626 '_rtmp': {'protocol': 'rtmp'}
,
628 # av01 video only formats sometimes served with "unknown" codecs
629 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
630 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
631 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
632 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
634 _SUBTITLE_FORMATS
= ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
641 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
645 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
646 'uploader': 'Philipp Hagemeister',
647 'uploader_id': 'phihag',
648 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
649 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
650 'channel_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
651 'upload_date': '20121002',
652 '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 .',
653 'categories': ['Science & Technology'],
654 'tags': ['youtube-dl'],
658 'dislike_count': int,
664 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
665 'note': 'Embed-only video (#1746)',
669 'upload_date': '20120608',
670 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
671 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
672 'uploader': 'SET India',
673 'uploader_id': 'setindia',
674 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/setindia',
677 'skip': 'Private video',
680 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
681 'note': 'Use the first video ID in the URL',
685 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
686 'uploader': 'Philipp Hagemeister',
687 'uploader_id': 'phihag',
688 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
689 'upload_date': '20121002',
690 '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 .',
691 'categories': ['Science & Technology'],
692 'tags': ['youtube-dl'],
696 'dislike_count': int,
699 'skip_download': True,
703 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
704 'note': '256k DASH audio (format 141) via DASH manifest',
708 'upload_date': '20121002',
709 'uploader_id': '8KVIDEO',
710 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
712 'uploader': '8KVIDEO',
713 'title': 'UHDTV TEST 8K VIDEO.mp4'
716 'youtube_include_dash_manifest': True,
719 'skip': 'format 141 not served anymore',
721 # DASH manifest with encrypted signature
723 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
727 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
728 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
730 'uploader': 'AfrojackVEVO',
731 'uploader_id': 'AfrojackVEVO',
732 'upload_date': '20131011',
736 'youtube_include_dash_manifest': True,
737 'format': '141/bestaudio[ext=m4a]',
742 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
747 'upload_date': '20100909',
748 'uploader': 'Amazing Atheist',
749 'uploader_id': 'TheAmazingAtheist',
750 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
751 'title': 'Burning Everyone\'s Koran',
752 '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',
755 # Normal age-gate video (embed allowed)
757 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
761 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
762 'description': r
're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
764 'uploader': 'The Witcher',
765 'uploader_id': 'WitcherGame',
766 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
767 'upload_date': '20140605',
771 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
772 # YouTube Red ad is not captured for creator
774 'url': '__2ABJjxzNo',
779 'upload_date': '20100430',
780 'uploader_id': 'deadmau5',
781 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/deadmau5',
782 'creator': 'deadmau5',
783 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
784 'uploader': 'deadmau5',
785 'title': 'Deadmau5 - Some Chords (HD)',
786 'alt_title': 'Some Chords',
788 'expected_warnings': [
789 'DASH manifest missing',
792 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
794 'url': 'lqQg6PlCWgI',
799 'upload_date': '20150827',
800 'uploader_id': 'olympic',
801 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/olympic',
802 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
803 'uploader': 'Olympic',
804 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
807 'skip_download': 'requires avconv',
812 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
816 'stretched_ratio': 16 / 9.,
818 'upload_date': '20110310',
819 'uploader_id': 'AllenMeow',
820 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
821 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
823 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
826 # url_encoded_fmt_stream_map is empty string
828 'url': 'qEJwOuvDf7I',
832 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
834 'upload_date': '20150404',
835 'uploader_id': 'spbelect',
836 'uploader': 'Наблюдатели Петербурга',
839 'skip_download': 'requires avconv',
841 'skip': 'This live event has ended.',
843 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
845 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
849 'title': 'md5:7b81415841e02ecd4313668cde88737a',
850 'description': 'md5:116377fd2963b81ec4ce64b542173306',
852 'upload_date': '20150625',
853 'uploader_id': 'dorappi2000',
854 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
855 'uploader': 'dorappi2000',
856 'formats': 'mincount:31',
858 'skip': 'not actual anymore',
860 # DASH manifest with segment_list
862 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
863 'md5': '8ce563a1d667b599d21064e982ab9e31',
867 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
868 'uploader': 'Airtek',
869 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
870 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
871 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
874 'youtube_include_dash_manifest': True,
875 'format': '135', # bestvideo
877 'skip': 'This live event has ended.',
880 # Multifeed videos (multiple cameras), URL is for Main Camera
881 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
884 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
885 'description': 'md5:e03b909557865076822aa169218d6a5d',
891 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
892 'description': 'md5:e03b909557865076822aa169218d6a5d',
894 'upload_date': '20161111',
895 'uploader': 'Team PGP',
896 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
897 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
903 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
904 'description': 'md5:e03b909557865076822aa169218d6a5d',
906 'upload_date': '20161111',
907 'uploader': 'Team PGP',
908 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
909 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
915 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
916 'description': 'md5:e03b909557865076822aa169218d6a5d',
918 'upload_date': '20161111',
919 'uploader': 'Team PGP',
920 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
921 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
927 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
928 'description': 'md5:e03b909557865076822aa169218d6a5d',
930 'upload_date': '20161111',
931 'uploader': 'Team PGP',
932 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
933 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
937 'skip_download': True,
941 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
942 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
945 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
948 'skip': 'Not multifeed anymore',
951 'url': 'https://vid.plus/FlRa-iH7PGw',
952 'only_matching': True,
955 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
956 'only_matching': True,
959 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
960 # Also tests cut-off URL expansion in video description (see
961 # https://github.com/ytdl-org/youtube-dl/issues/1892,
962 # https://github.com/ytdl-org/youtube-dl/issues/8164)
963 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
967 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
968 'alt_title': 'Dark Walk - Position Music',
969 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
971 'upload_date': '20151119',
972 'uploader_id': 'IronSoulElf',
973 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
974 'uploader': 'IronSoulElf',
975 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
976 'track': 'Dark Walk - Position Music',
977 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
978 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
981 'skip_download': True,
985 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
986 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
987 'only_matching': True,
990 # Video with yt:stretch=17:0
991 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
995 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
996 'description': 'md5:ee18a25c350637c8faff806845bddee9',
997 'upload_date': '20151107',
998 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
999 'uploader': 'CH GAMER DROID',
1002 'skip_download': True,
1004 'skip': 'This video does not exist.',
1007 # Video licensed under Creative Commons
1008 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1010 'id': 'M4gD1WSo5mA',
1012 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1013 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
1015 'upload_date': '20150127',
1016 'uploader_id': 'BerkmanCenter',
1017 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
1018 'uploader': 'The Berkman Klein Center for Internet & Society',
1019 'license': 'Creative Commons Attribution license (reuse allowed)',
1022 'skip_download': True,
1026 # Channel-like uploader_url
1027 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1029 'id': 'eQcmzGIKrzg',
1031 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1032 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1034 'upload_date': '20151119',
1035 'uploader': 'Bernie Sanders',
1036 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1037 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
1038 'license': 'Creative Commons Attribution license (reuse allowed)',
1041 'skip_download': True,
1045 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
1046 'only_matching': True,
1049 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
1050 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1051 'only_matching': True,
1054 # Rental video preview
1055 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1057 'id': 'uGpuVWrhIzE',
1059 'title': 'Piku - Trailer',
1060 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1061 'upload_date': '20150811',
1062 'uploader': 'FlixMatrix',
1063 'uploader_id': 'FlixMatrixKaravan',
1064 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
1065 'license': 'Standard YouTube License',
1068 'skip_download': True,
1070 'skip': 'This video is not available.',
1073 # YouTube Red video with episode data
1074 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1076 'id': 'iqKdEhx-dD4',
1078 'title': 'Isolation - Mind Field (Ep 1)',
1079 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1081 'upload_date': '20170118',
1082 'uploader': 'Vsauce',
1083 'uploader_id': 'Vsauce',
1084 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1085 'series': 'Mind Field',
1087 'episode_number': 1,
1090 'skip_download': True,
1092 'expected_warnings': [
1093 'Skipping DASH manifest',
1097 # The following content has been identified by the YouTube community
1098 # as inappropriate or offensive to some audiences.
1099 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1101 'id': '6SJNVb0GnPI',
1103 'title': 'Race Differences in Intelligence',
1104 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1106 'upload_date': '20140124',
1107 'uploader': 'New Century Foundation',
1108 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1109 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1112 'skip_download': True,
1114 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1118 'url': '1t24XAntNCY',
1119 'only_matching': True,
1122 # geo restricted to JP
1123 'url': 'sJL6WA-aGkQ',
1124 'only_matching': True,
1127 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1128 'only_matching': True,
1131 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1132 'only_matching': True,
1135 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1136 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1137 'only_matching': True,
1141 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1142 'only_matching': True,
1145 # Video with unsupported adaptive stream type formats
1146 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1148 'id': 'Z4Vy8R84T1U',
1150 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1151 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1153 'upload_date': '20130923',
1154 'uploader': 'Amelia Putri Harwita',
1155 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1156 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1157 'formats': 'maxcount:10',
1160 'skip_download': True,
1161 'youtube_include_dash_manifest': False,
1163 'skip': 'not actual anymore',
1166 # Youtube Music Auto-generated description
1167 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1169 'id': 'MgNrAu2pzNs',
1171 'title': 'Voyeur Girl',
1172 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1173 'upload_date': '20190312',
1174 'uploader': 'Stephen - Topic',
1175 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1176 'artist': 'Stephen',
1177 'track': 'Voyeur Girl',
1178 'album': 'it\'s too much love to know my dear',
1179 'release_date': '20190313',
1180 'release_year': 2019,
1183 'skip_download': True,
1187 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1188 'only_matching': True,
1191 # invalid -> valid video id redirection
1192 'url': 'DJztXj2GPfl',
1194 'id': 'DJztXj2GPfk',
1196 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1197 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1198 'upload_date': '20090125',
1199 'uploader': 'Prochorowka',
1200 'uploader_id': 'Prochorowka',
1201 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1202 'artist': 'Panjabi MC',
1203 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1204 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1207 'skip_download': True,
1209 'skip': 'Video unavailable',
1212 # empty description results in an empty string
1213 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1215 'id': 'x41yOUIvK2k',
1217 'title': 'IMG 3456',
1219 'upload_date': '20170613',
1220 'uploader_id': 'ElevageOrVert',
1221 'uploader': 'ElevageOrVert',
1224 'skip_download': True,
1228 # with '};' inside yt initial data (see [1])
1229 # see [2] for an example with '};' inside ytInitialPlayerResponse
1230 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1231 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1232 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1234 'id': 'CHqg6qOn4no',
1236 'title': 'Part 77 Sort a list of simple types in c#',
1237 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1238 'upload_date': '20130831',
1239 'uploader_id': 'kudvenkat',
1240 'uploader': 'kudvenkat',
1243 'skip_download': True,
1247 # another example of '};' in ytInitialData
1248 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1249 'only_matching': True,
1252 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1253 'only_matching': True,
1256 # https://github.com/ytdl-org/youtube-dl/pull/28094
1257 'url': 'OtqTfy26tG0',
1259 'id': 'OtqTfy26tG0',
1261 'title': 'Burn Out',
1262 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1263 'upload_date': '20141120',
1264 'uploader': 'The Cinematic Orchestra - Topic',
1265 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1266 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1267 'artist': 'The Cinematic Orchestra',
1268 'track': 'Burn Out',
1269 'album': 'Every Day',
1270 'release_data': None,
1271 'release_year': None,
1274 'skip_download': True,
1278 # controversial video, only works with bpctr when authenticated with cookies
1279 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1280 'only_matching': True,
1283 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1284 'url': 'cBvYw8_A0vQ',
1286 'id': 'cBvYw8_A0vQ',
1288 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
1289 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1290 'upload_date': '20201120',
1291 'uploader': 'Walk around Japan',
1292 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1293 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1296 'skip_download': True,
1301 def __init__(self
, *args
, **kwargs
):
1302 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
1303 self
._code
_cache
= {}
1304 self
._player
_cache
= {}
1306 def _signature_cache_id(self
, example_sig
):
1307 """ Return a string representation of a signature """
1308 return '.'.join(compat_str(len(part
)) for part
in example_sig
.split('.'))
1311 def _extract_player_info(cls
, player_url
):
1312 for player_re
in cls
._PLAYER
_INFO
_RE
:
1313 id_m
= re
.search(player_re
, player_url
)
1317 raise ExtractorError('Cannot identify player %r' % player_url
)
1318 return id_m
.group('id')
1320 def _extract_signature_function(self
, video_id
, player_url
, example_sig
):
1321 player_id
= self
._extract
_player
_info
(player_url
)
1323 # Read from filesystem cache
1324 func_id
= 'js_%s_%s' % (
1325 player_id
, self
._signature
_cache
_id
(example_sig
))
1326 assert os
.path
.basename(func_id
) == func_id
1328 cache_spec
= self
._downloader
.cache
.load('youtube-sigfuncs', func_id
)
1329 if cache_spec
is not None:
1330 return lambda s
: ''.join(s
[i
] for i
in cache_spec
)
1332 if player_id
not in self
._code
_cache
:
1333 self
._code
_cache
[player_id
] = self
._download
_webpage
(
1334 player_url
, video_id
,
1335 note
='Downloading player ' + player_id
,
1336 errnote
='Download of %s failed' % player_url
)
1337 code
= self
._code
_cache
[player_id
]
1338 res
= self
._parse
_sig
_js
(code
)
1340 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1341 cache_res
= res(test_string
)
1342 cache_spec
= [ord(c
) for c
in cache_res
]
1344 self
._downloader
.cache
.store('youtube-sigfuncs', func_id
, cache_spec
)
1347 def _print_sig_code(self
, func
, example_sig
):
1348 def gen_sig_code(idxs
):
1349 def _genslice(start
, end
, step
):
1350 starts
= '' if start
== 0 else str(start
)
1351 ends
= (':%d' % (end
+ step
)) if end
+ step
>= 0 else ':'
1352 steps
= '' if step
== 1 else (':%d' % step
)
1353 return 's[%s%s%s]' % (starts
, ends
, steps
)
1356 # Quelch pyflakes warnings - start will be set when step is set
1357 start
= '(Never used)'
1358 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
1359 if step
is not None:
1360 if i
- prev
== step
:
1362 yield _genslice(start
, prev
, step
)
1365 if i
- prev
in [-1, 1]:
1370 yield 's[%d]' % prev
1374 yield _genslice(start
, i
, step
)
1376 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1377 cache_res
= func(test_string
)
1378 cache_spec
= [ord(c
) for c
in cache_res
]
1379 expr_code
= ' + '.join(gen_sig_code(cache_spec
))
1380 signature_id_tuple
= '(%s)' % (
1381 ', '.join(compat_str(len(p
)) for p
in example_sig
.split('.')))
1382 code
= ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1383 ' return %s\n') % (signature_id_tuple
, expr_code
)
1384 self
.to_screen('Extracted signature function:\n' + code
)
1386 def _parse_sig_js(self
, jscode
):
1387 funcname
= self
._search
_regex
(
1388 (r
'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1389 r
'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1390 r
'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1391 r
'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1392 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*\);[a-zA-Z0-9$]{2}\.[a-zA-Z0-9$]{2}\(a,\d+\)',
1393 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*\)',
1394 r
'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1396 r
'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1397 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1398 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1399 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1400 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1401 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1402 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1403 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1404 jscode, 'Initial JS player signature function name
', group='sig
')
1406 jsi = JSInterpreter(jscode)
1407 initial_function = jsi.extract_function(funcname)
1408 return lambda s: initial_function([s])
1410 def _decrypt_signature(self, s, video_id, player_url):
1411 """Turn the encrypted s field into a working signature"""
1413 if player_url is None:
1414 raise ExtractorError('Cannot decrypt signature without player_url
')
1416 if player_url.startswith('//'):
1417 player_url = 'https
:' + player_url
1418 elif not re.match(r'https?
://', player_url):
1419 player_url = compat_urlparse.urljoin(
1420 'https
://www
.youtube
.com
', player_url)
1422 player_id = (player_url, self._signature_cache_id(s))
1423 if player_id not in self._player_cache:
1424 func = self._extract_signature_function(
1425 video_id, player_url, s
1427 self._player_cache[player_id] = func
1428 func = self._player_cache[player_id]
1429 if self._downloader.params.get('youtube_print_sig_code
'):
1430 self._print_sig_code(func, s)
1432 except Exception as e:
1433 tb = traceback.format_exc()
1434 raise ExtractorError(
1435 'Signature extraction failed
: ' + tb, cause=e)
1437 def _mark_watched(self, video_id, player_response):
1438 playback_url = url_or_none(try_get(
1440 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1441 if not playback_url:
1443 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1444 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1446 # cpn generation algorithm is reverse engineered from base.js.
1447 # In fact it works even with dummy cpn.
1448 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1449 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1455 playback_url = compat_urlparse.urlunparse(
1456 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1458 self._download_webpage(
1459 playback_url, video_id, 'Marking watched
',
1460 'Unable to mark watched
', fatal=False)
1463 def _extract_urls(webpage):
1464 # Embedded YouTube player
1466 unescapeHTML(mobj.group('url
'))
1467 for mobj in re.finditer(r'''(?x)
1477 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1478 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1481 # lazyYT YouTube embed
1482 entries.extend(list(map(
1484 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1486 # Wordpress "YouTube Video Importer
" plugin
1487 matches = re.findall(r'''(?x)<div[^>]+
1488 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1489 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1490 entries.extend(m[-1] for m in matches)
1495 def _extract_url(webpage):
1496 urls = YoutubeIE._extract_urls(webpage)
1497 return urls[0] if urls else None
1500 def extract_id(cls, url):
1501 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1503 raise ExtractorError('Invalid URL: %s' % url)
1504 video_id = mobj.group(2)
1507 def _extract_chapters_from_json(self, data, video_id, duration):
1508 chapters_list = try_get(
1510 lambda x: x['playerOverlays']
1511 ['playerOverlayRenderer']
1512 ['decoratedPlayerBarRenderer']
1513 ['decoratedPlayerBarRenderer']
1515 ['chapteredPlayerBarRenderer']
1518 if not chapters_list:
1521 def chapter_time(chapter):
1522 return float_or_none(
1525 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1529 for next_num, chapter in enumerate(chapters_list, start=1):
1530 start_time = chapter_time(chapter)
1531 if start_time is None:
1533 end_time = (chapter_time(chapters_list[next_num])
1534 if next_num < len(chapters_list) else duration)
1535 if end_time is None:
1538 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1541 'start_time': start_time,
1542 'end_time': end_time,
1547 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1548 return self._parse_json(self._search_regex(
1549 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1550 regex), webpage, name, default='{}'), video_id, fatal=False)
1553 def parse_time_text(time_text):
1555 Parse the comment time text
1556 time_text is in the format 'X units ago (edited)'
1558 time_text_split = time_text.split(' ')
1559 if len(time_text_split) >= 3:
1560 return datetime_from_str('now-%s%s' % (time_text_split[0], time_text_split[1]), precision='auto')
1563 def _join_text_entries(runs):
1566 if not isinstance(run, dict):
1568 sub_text = try_get(run, lambda x: x['text'], compat_str)
1576 def _extract_comment(self, comment_renderer, parent=None):
1577 comment_id = comment_renderer.get('commentId')
1580 comment_text_runs = try_get(comment_renderer, lambda x: x['contentText']['runs']) or []
1581 text = self._join_text_entries(comment_text_runs) or ''
1582 comment_time_text = try_get(comment_renderer, lambda x: x['publishedTimeText']['runs']) or []
1583 time_text = self._join_text_entries(comment_time_text)
1584 timestamp = calendar.timegm(self.parse_time_text(time_text).timetuple())
1585 author = try_get(comment_renderer, lambda x: x['authorText']['simpleText'], compat_str)
1586 author_id = try_get(comment_renderer,
1587 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], compat_str)
1588 votes = str_to_int(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
1589 lambda x: x['likeCount']), compat_str)) or 0
1590 author_thumbnail = try_get(comment_renderer,
1591 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], compat_str)
1593 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
1594 is_liked = try_get(comment_renderer, lambda x: x['isLiked'], bool)
1598 'timestamp': timestamp,
1599 'time_text': time_text,
1600 'like_count': votes,
1601 'is_favorited': is_liked,
1603 'author_id': author_id,
1604 'author_thumbnail': author_thumbnail,
1605 'author_is_uploader': author_is_uploader,
1606 'parent': parent or 'root'
1609 def _comment_entries(self, root_continuation_data, identity_token, account_syncid,
1610 ytcfg, session_token_list, parent=None, comment_counts=None):
1612 def extract_thread(parent_renderer):
1613 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
1615 comment_counts[2] = 0
1616 for content in contents:
1617 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
1618 comment_renderer = try_get(
1619 comment_thread_renderer, (lambda x: x['comment']['commentRenderer'], dict)) or try_get(
1620 content, (lambda x: x['commentRenderer'], dict))
1622 if not comment_renderer:
1624 comment = self._extract_comment(comment_renderer, parent)
1627 comment_counts[0] += 1
1629 # Attempt to get the replies
1630 comment_replies_renderer = try_get(
1631 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
1633 if comment_replies_renderer:
1634 comment_counts[2] += 1
1635 comment_entries_iter = self._comment_entries(
1636 comment_replies_renderer, identity_token, account_syncid, ytcfg,
1637 parent=comment.get('id'), session_token_list=session_token_list,
1638 comment_counts=comment_counts)
1640 for reply_comment in comment_entries_iter:
1643 if not comment_counts:
1644 # comment so far, est. total comments, current comment thread #
1645 comment_counts = [0, 0, 0]
1647 # TODO: Generalize the download code with TabIE
1648 context = self._extract_context(ytcfg)
1649 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
1650 continuation = YoutubeTabIE._extract_continuation(root_continuation_data) # TODO
1651 first_continuation = False
1653 first_continuation = True
1655 for page_num in itertools.count(0):
1656 if not continuation:
1658 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
1659 retries = self._downloader.params.get('extractor_retries', 3)
1663 while count < retries:
1666 self.report_warning('%s. Retrying ...' % last_error)
1669 'ctoken': continuation['ctoken'],
1674 query['action_get_comment_replies'] = 1
1676 query['action_get_comments'] = 1
1678 comment_prog_str = '(%d/%d)' % (comment_counts[0], comment_counts[1])
1680 if first_continuation:
1681 note_prefix = 'Downloading initial comment continuation page'
1683 note_prefix = ' Downloading comment reply thread %d %s' % (comment_counts[2], comment_prog_str)
1685 note_prefix = '%sDownloading comment%s page %d %s' % (
1686 ' ' if parent else '',
1687 ' replies' if parent else '',
1691 browse = self._download_json(
1692 'https://www.youtube.com/comment_service_ajax', None,
1693 '%s %s' % (note_prefix, '(retry #%d)' % count if count else ''),
1694 headers=headers, query=query,
1695 data=urlencode_postdata({
1696 'session_token': session_token_list[0]
1698 except ExtractorError as e:
1699 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404, 413):
1700 if e.cause.code == 413:
1701 self.report_warning('Assumed end of comments (received HTTP Error 413)')
1703 # Downloading page may result in intermittent 5xx HTTP error
1704 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1705 last_error = 'HTTP Error %s' % e.cause.code
1706 if e.cause.code == 404:
1707 last_error = last_error + ' (this API is probably deprecated)'
1712 session_token = try_get(browse, lambda x: x['xsrf_token'], compat_str)
1714 session_token_list[0] = session_token
1716 response = try_get(browse,
1717 (lambda x: x['response'],
1718 lambda x: x[1]['response'])) or {}
1720 if response.get('continuationContents'):
1723 # YouTube sometimes gives reload: now json if something went wrong (e.g. bad auth)
1724 if browse.get('reload'):
1725 raise ExtractorError('Invalid or missing params in continuation request', expected=False)
1727 # TODO: not tested, merged from old extractor
1728 err_msg = browse.get('externalErrorMessage')
1730 raise ExtractorError('YouTube said: %s' % err_msg, expected=False)
1732 # Youtube sometimes sends incomplete data
1733 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1734 last_error = 'Incomplete data received'
1735 if count >= retries:
1736 self._downloader.report_error(last_error)
1740 visitor_data = try_get(
1742 lambda x: x['responseContext']['webResponseContextExtensionData']['ytConfigData']['visitorData'],
1743 compat_str) or visitor_data
1745 known_continuation_renderers = {
1746 'itemSectionContinuation': extract_thread,
1747 'commentRepliesContinuation': extract_thread
1750 # extract next root continuation from the results
1751 continuation_contents = try_get(
1752 response, lambda x: x['continuationContents'], dict) or {}
1754 for key, value in continuation_contents.items():
1755 if key not in known_continuation_renderers:
1757 continuation_renderer = value
1759 if first_continuation:
1760 first_continuation = False
1761 expected_comment_count = try_get(
1762 continuation_renderer,
1763 (lambda x: x['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'],
1764 lambda x: x['header']['commentsHeaderRenderer']['commentsCount']['runs'][0]['text']),
1767 if expected_comment_count:
1768 comment_counts[1] = str_to_int(expected_comment_count)
1769 self.to_screen('Downloading ~%d comments' % str_to_int(expected_comment_count))
1770 yield comment_counts[1]
1773 # 1/True for newest, 0/False for popular (default)
1774 comment_sort_index = int(True)
1775 sort_continuation_renderer = try_get(
1776 continuation_renderer,
1777 lambda x: x['header']['commentsHeaderRenderer']['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems']
1778 [comment_sort_index]['continuation']['reloadContinuationData'], dict)
1779 # If this fails, the initial continuation page
1780 # starts off with popular anyways.
1781 if sort_continuation_renderer:
1782 continuation = YoutubeTabIE._build_continuation_query(
1783 continuation=sort_continuation_renderer.get('continuation'),
1784 ctp=sort_continuation_renderer.get('clickTrackingParams'))
1785 self.to_screen('Sorting comments by %s' % ('popular' if comment_sort_index == 0 else 'newest'))
1788 for entry in known_continuation_renderers[key](continuation_renderer):
1791 continuation = YoutubeTabIE._extract_continuation(continuation_renderer) # TODO
1794 def _extract_comments(self, ytcfg, video_id, contents, webpage, xsrf_token):
1795 """Entry for comment extraction"""
1797 known_entry_comment_renderers = (
1798 'itemSectionRenderer',
1801 for entry in contents:
1802 for key, renderer in entry.items():
1803 if key not in known_entry_comment_renderers:
1806 comment_iter = self._comment_entries(
1808 identity_token=self._extract_identity_token(webpage, item_id=video_id),
1809 account_syncid=self._extract_account_syncid(ytcfg),
1811 session_token_list=[xsrf_token])
1813 for comment in comment_iter:
1814 if isinstance(comment, int):
1815 estimated_total = comment
1817 comments.append(comment)
1819 self.to_screen('Downloaded %d/%d comments' % (len(comments), estimated_total))
1821 'comments': comments,
1822 'comment_count': len(comments),
1825 def _real_extract(self, url):
1826 url, smuggled_data = unsmuggle_url(url, {})
1827 video_id = self._match_id(url)
1828 base_url = self.http_scheme() + '//www.youtube.com/'
1829 webpage_url = base_url + 'watch?v=' + video_id
1830 webpage = self._download_webpage(
1831 webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1833 player_response = None
1835 player_response = self._extract_yt_initial_variable(
1836 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1837 video_id, 'initial player response')
1839 ytcfg = self._extract_ytcfg(video_id, webpage)
1840 if not player_response:
1841 player_response = self._call_api(
1842 'player', {'videoId': video_id}, video_id, api_key=self._extract_api_key(ytcfg))
1844 playability_status = player_response.get('playabilityStatus') or {}
1845 if playability_status.get('reason') == 'Sign in to confirm your age':
1846 pr = self._parse_json(try_get(compat_parse_qs(
1847 self._download_webpage(
1848 base_url + 'get_video_info', video_id,
1849 'Refetching age-gated info webpage',
1850 'unable to download video info webpage', query={
1851 'video_id': video_id,
1852 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1854 lambda x: x['player_response'][0],
1855 compat_str) or '{}', video_id)
1857 player_response = pr
1859 trailer_video_id = try_get(
1861 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1863 if trailer_video_id:
1864 return self.url_result(
1865 trailer_video_id, self.ie_key(), trailer_video_id)
1870 text = x.get('simpleText')
1871 if text and isinstance(text, compat_str):
1873 runs = x.get('runs')
1874 if not isinstance(runs, list):
1876 return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1879 lambda x: self._html_search_meta(x, webpage, default=None)) \
1880 if webpage else lambda x: None
1882 video_details = player_response.get('videoDetails') or {}
1883 microformat = try_get(
1885 lambda x: x['microformat']['playerMicroformatRenderer'],
1887 video_title = video_details.get('title') \
1888 or get_text(microformat.get('title')) \
1889 or search_meta(['og:title', 'twitter:title', 'title'])
1890 video_description = video_details.get('shortDescription')
1892 if not smuggled_data.get('force_singlefeed', False):
1893 if not self._downloader.params.get('noplaylist'):
1894 multifeed_metadata_list = try_get(
1896 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1898 if multifeed_metadata_list:
1901 for feed in multifeed_metadata_list.split(','):
1902 # Unquote should take place before split on comma (,) since textual
1903 # fields may contain comma as well (see
1904 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1905 feed_data = compat_parse_qs(
1906 compat_urllib_parse_unquote_plus(feed))
1908 def feed_entry(name):
1910 feed_data, lambda x: x[name][0], compat_str)
1912 feed_id = feed_entry('id')
1915 feed_title = feed_entry('title')
1918 title += ' (%s)' % feed_title
1920 '_type': 'url_transparent',
1921 'ie_key': 'Youtube',
1923 base_url + 'watch?v=' + feed_data['id'][0],
1924 {'force_singlefeed': True}),
1927 feed_ids.append(feed_id)
1929 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1930 % (', '.join(feed_ids), video_id))
1931 return self.playlist_result(
1932 entries, video_id, video_title, video_description)
1934 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1940 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1941 streaming_data = player_response.get('streamingData') or {}
1942 streaming_formats = streaming_data.get('formats') or []
1943 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1944 for fmt in streaming_formats:
1945 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1948 itag = str_or_none(fmt.get('itag'))
1949 quality = fmt.get('quality')
1950 if itag and quality:
1951 itag_qualities[itag] = quality
1952 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1953 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1954 # number of fragment that would subsequently requested with (`&sq=N`)
1955 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1958 fmt_url = fmt.get('url')
1960 sc = compat_parse_qs(fmt.get('signatureCipher'))
1961 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1962 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1963 if not (sc and fmt_url and encrypted_sig):
1968 player_url = self._search_regex(
1969 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1970 webpage, 'player URL', fatal=False)
1973 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1974 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1975 fmt_url += '&' + sp + '=' + signature
1979 tbr = float_or_none(
1980 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1982 'asr': int_or_none(fmt.get('audioSampleRate')),
1983 'filesize': int_or_none(fmt.get('contentLength')),
1985 'format_note': fmt.get('qualityLabel') or quality,
1986 'fps': int_or_none(fmt.get('fps')),
1987 'height': int_or_none(fmt.get('height')),
1988 'quality': q(quality),
1991 'width': fmt.get('width'),
1993 mimetype = fmt.get('mimeType')
1996 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1998 dct['ext'] = mimetype2ext(mobj.group(1))
1999 dct.update(parse_codecs(mobj.group(2)))
2000 no_audio = dct.get('acodec') == 'none'
2001 no_video = dct.get('vcodec') == 'none'
2006 if no_audio or no_video:
2007 dct['downloader_options'] = {
2008 # Youtube throttles chunks >~10M
2009 'http_chunk_size': 10485760,
2012 dct['container'] = dct['ext'] + '_dash'
2015 hls_manifest_url = streaming_data.get('hlsManifestUrl')
2016 if hls_manifest_url:
2017 for f in self._extract_m3u8_formats(
2018 hls_manifest_url, video_id, 'mp4', fatal=False):
2019 itag = self._search_regex(
2020 r'/itag/(\d+)', f['url'], 'itag', default=None)
2022 f['format_id'] = itag
2025 if self._downloader.params.get('youtube_include_dash_manifest', True):
2026 dash_manifest_url = streaming_data.get('dashManifestUrl')
2027 if dash_manifest_url:
2028 for f in self._extract_mpd_formats(
2029 dash_manifest_url, video_id, fatal=False):
2030 itag = f['format_id']
2033 if itag in itag_qualities:
2034 # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
2035 # but kept to maintain feature parity (and code similarity) with youtube-dl
2036 # Remove if this causes any issues with sorting in future
2037 f['quality'] = q(itag_qualities[itag])
2038 filesize = int_or_none(self._search_regex(
2039 r'/clen/(\d+)', f.get('fragment_base_url')
2040 or f['url'], 'file size', default=None))
2042 f['filesize'] = filesize
2046 if not self._downloader.params.get('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
2047 raise ExtractorError(
2048 'This video is DRM protected.', expected=True)
2051 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
2053 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
2054 subreason = pemr.get('subreason')
2056 subreason = clean_html(get_text(subreason))
2057 if subreason == 'The uploader has not made this video available in your country.':
2058 countries = microformat.get('availableCountries')
2060 regions_allowed = search_meta('regionsAllowed')
2061 countries = regions_allowed.split(',') if regions_allowed else None
2062 self.raise_geo_restricted(
2063 subreason, countries)
2064 reason += '\n' + subreason
2066 raise ExtractorError(reason, expected=True)
2068 self._sort_formats(formats)
2070 keywords = video_details.get('keywords') or []
2071 if not keywords and webpage:
2073 unescapeHTML(m.group('content'))
2074 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
2075 for keyword in keywords:
2076 if keyword.startswith('yt:stretch='):
2077 w, h = keyword.split('=')[1].split(':')
2078 w, h = int(w), int(h)
2082 if f.get('vcodec') != 'none':
2083 f['stretched_ratio'] = ratio
2086 for container in (video_details, microformat):
2087 for thumbnail in (try_get(
2089 lambda x: x['thumbnail']['thumbnails'], list) or []):
2090 thumbnail_url = thumbnail.get('url')
2091 if not thumbnail_url:
2093 # Sometimes youtube gives a wrong thumbnail URL. See:
2094 # https://github.com/yt-dlp/yt-dlp/issues/233
2095 # https://github.com/ytdl-org/youtube-dl/issues/28023
2096 if 'maxresdefault' in thumbnail_url:
2097 thumbnail_url = thumbnail_url.split('?')[0]
2099 'height': int_or_none(thumbnail.get('height')),
2100 'url': thumbnail_url,
2101 'width': int_or_none(thumbnail.get('width')),
2106 thumbnail = search_meta(['og:image', 'twitter:image'])
2108 thumbnails = [{'url': thumbnail}]
2110 category = microformat.get('category') or search_meta('genre')
2111 channel_id = video_details.get('channelId') \
2112 or microformat.get('externalChannelId') \
2113 or search_meta('channelId')
2114 duration = int_or_none(
2115 video_details.get('lengthSeconds')
2116 or microformat.get('lengthSeconds')) \
2117 or parse_duration(search_meta('duration'))
2118 is_live = video_details.get('isLive')
2119 owner_profile_url = microformat.get('ownerProfileUrl')
2123 'title': self._live_title(video_title) if is_live else video_title,
2125 'thumbnails': thumbnails,
2126 'description': video_description,
2127 'upload_date': unified_strdate(
2128 microformat.get('uploadDate')
2129 or search_meta('uploadDate')),
2130 'uploader': video_details['author'],
2131 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
2132 'uploader_url': owner_profile_url,
2133 'channel_id': channel_id,
2134 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
2135 'duration': duration,
2136 'view_count': int_or_none(
2137 video_details.get('viewCount')
2138 or microformat.get('viewCount')
2139 or search_meta('interactionCount')),
2140 'average_rating': float_or_none(video_details.get('averageRating')),
2141 'age_limit': 18 if (
2142 microformat.get('isFamilySafe') is False
2143 or search_meta('isFamilyFriendly') == 'false'
2144 or search_meta('og:restrictions:age') == '18+') else 0,
2145 'webpage_url': webpage_url,
2146 'categories': [category] if category else None,
2149 'playable_in_embed': playability_status.get('playableInEmbed'),
2150 'was_live': video_details.get('isLiveContent'),
2155 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
2158 def process_language(container, base_url, lang_code, query):
2160 for fmt in self._SUBTITLE_FORMATS:
2166 'url': update_url_query(base_url, query),
2168 container[lang_code] = lang_subs
2170 for caption_track in (pctr.get('captionTracks') or []):
2171 base_url = caption_track.get('baseUrl')
2174 if caption_track.get('kind') != 'asr':
2175 lang_code = caption_track.get('languageCode')
2179 subtitles, base_url, lang_code, {})
2181 automatic_captions = {}
2182 for translation_language in (pctr.get('translationLanguages') or []):
2183 translation_language_code = translation_language.get('languageCode')
2184 if not translation_language_code:
2187 automatic_captions, base_url, translation_language_code,
2188 {'tlang': translation_language_code})
2189 info['automatic_captions'] = automatic_captions
2190 info['subtitles'] = subtitles
2192 parsed_url = compat_urllib_parse_urlparse(url)
2193 for component in [parsed_url.fragment, parsed_url.query]:
2194 query = compat_parse_qs(component)
2195 for k, v in query.items():
2196 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
2198 if d_k not in info and k in s_ks:
2199 info[d_k] = parse_duration(query[k][0])
2201 # Youtube Music Auto-generated description
2202 if video_description:
2203 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)
2205 release_year = mobj.group('release_year')
2206 release_date = mobj.group('release_date')
2208 release_date = release_date.replace('-', '')
2209 if not release_year:
2210 release_year = release_date[:4]
2212 'album': mobj.group('album'.strip()),
2213 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
2214 'track': mobj.group('track').strip(),
2215 'release_date': release_date,
2216 'release_year': int_or_none(release_year),
2221 initial_data = self._extract_yt_initial_variable(
2222 webpage, self._YT_INITIAL_DATA_RE, video_id,
2224 if not initial_data:
2225 initial_data = self._call_api(
2226 'next', {'videoId': video_id}, video_id, fatal=False, api_key=self._extract_api_key(ytcfg))
2230 # This will error if there is no livechat
2231 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
2232 info['subtitles']['live_chat'] = [{
2233 'url': 'https://www.youtube.com/watch?v=%s' % video_id, # url is needed to set cookies
2234 'video_id': video_id,
2236 'protocol': 'youtube_live_chat_replay',
2238 except (KeyError, IndexError, TypeError):
2242 chapters = self._extract_chapters_from_json(
2243 initial_data, video_id, duration)
2245 for engagment_pannel in (initial_data.get('engagementPanels') or []):
2247 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
2252 def chapter_time(mmlir):
2253 return parse_duration(
2254 get_text(mmlir.get('timeDescription')))
2257 for next_num, content in enumerate(contents, start=1):
2258 mmlir = content.get('macroMarkersListItemRenderer') or {}
2259 start_time = chapter_time(mmlir)
2260 end_time = chapter_time(try_get(
2261 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
2262 if next_num < len(contents) else duration
2263 if start_time is None or end_time is None:
2266 'start_time': start_time,
2267 'end_time': end_time,
2268 'title': get_text(mmlir.get('title')),
2273 info['chapters'] = chapters
2277 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
2279 for content in contents:
2280 vpir = content.get('videoPrimaryInfoRenderer')
2282 stl = vpir.get('superTitleLink')
2287 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
2288 info['location'] = stl
2290 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
2293 'series': mobj.group(1),
2294 'season_number': int(mobj.group(2)),
2295 'episode_number': int(mobj.group(3)),
2297 for tlb in (try_get(
2299 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
2301 tbr = tlb.get('toggleButtonRenderer') or {}
2302 for getter, regex in [(
2303 lambda x: x['defaultText']['accessibility']['accessibilityData'],
2304 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
2305 lambda x: x['accessibility'],
2306 lambda x: x['accessibilityData']['accessibilityData'],
2307 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
2308 label = (try_get(tbr, getter, dict) or {}).get('label')
2310 mobj = re.match(regex, label)
2312 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
2314 sbr_tooltip = try_get(
2315 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
2317 like_count, dislike_count = sbr_tooltip.split(' / ')
2319 'like_count': str_to_int(like_count),
2320 'dislike_count': str_to_int(dislike_count),
2322 vsir = content.get('videoSecondaryInfoRenderer')
2324 info['channel'] = get_text(try_get(
2326 lambda x: x['owner']['videoOwnerRenderer']['title'],
2330 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
2332 multiple_songs = False
2334 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
2335 multiple_songs = True
2338 mrr = row.get('metadataRowRenderer') or {}
2339 mrr_title = mrr.get('title')
2342 mrr_title = get_text(mrr['title'])
2343 mrr_contents_text = get_text(mrr['contents'][0])
2344 if mrr_title == 'License':
2345 info['license'] = mrr_contents_text
2346 elif not multiple_songs:
2347 if mrr_title == 'Album':
2348 info['album'] = mrr_contents_text
2349 elif mrr_title == 'Artist':
2350 info['artist'] = mrr_contents_text
2351 elif mrr_title == 'Song':
2352 info['track'] = mrr_contents_text
2355 'channel': 'uploader',
2356 'channel_id': 'uploader_id',
2357 'channel_url': 'uploader_url',
2359 for to, frm in fallbacks.items():
2360 if not info.get(to):
2361 info[to] = info.get(frm)
2363 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
2368 is_private = bool_or_none(video_details.get('isPrivate'))
2369 is_unlisted = bool_or_none(microformat.get('isUnlisted'))
2370 is_membersonly = None
2372 if initial_data and is_private is not None:
2373 is_membersonly = False
2375 contents = try_get(initial_data, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'], list)
2376 for content in contents or []:
2377 badges = try_get(content, lambda x: x['videoPrimaryInfoRenderer']['badges'], list)
2378 for badge in badges or []:
2379 label = try_get(badge, lambda x: x['metadataBadgeRenderer']['label']) or ''
2380 if label.lower() == 'members only':
2381 is_membersonly = True
2383 elif label.lower() == 'premium':
2386 if is_membersonly or is_premium:
2389 # TODO: Add this for playlists
2390 info['availability'] = self._availability(
2391 is_private=is_private,
2392 needs_premium=is_premium,
2393 needs_subscription=is_membersonly,
2394 needs_auth=info['age_limit'] >= 18,
2395 is_unlisted=None if is_private is None else is_unlisted)
2397 # get xsrf for annotations or comments
2398 get_annotations = self._downloader.params.get('writeannotations', False)
2399 get_comments = self._downloader.params.get('getcomments', False)
2400 if get_annotations or get_comments:
2402 ytcfg = self._extract_ytcfg(video_id, webpage)
2404 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2406 xsrf_token = self._search_regex(
2407 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2408 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2412 invideo_url = try_get(
2413 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2414 if xsrf_token and invideo_url:
2415 xsrf_field_name = None
2417 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2418 if not xsrf_field_name:
2419 xsrf_field_name = self._search_regex(
2420 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2421 webpage, 'xsrf field name',
2422 group='xsrf_field_name', default='session_token')
2423 info['annotations'] = self._download_webpage(
2424 self._proto_relative_url(invideo_url),
2425 video_id, note='Downloading annotations',
2426 errnote='Unable to download video annotations', fatal=False,
2427 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2430 info['__post_extractor'] = lambda: self._extract_comments(ytcfg, video_id, contents, webpage, xsrf_token)
2432 self.mark_watched(video_id, player_response)
2437 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2438 IE_DESC = 'YouTube.com tab'
2439 _VALID_URL = r'''(?x
)
2443 youtube(?
:kids
)?\
.com|
2447 (?
:channel|c|user
)/|
2450 (?
:playlist|watch
)\?.*?
\blist
=
2452 (?
!(?
:%s)\b) # Direct URLs
2455 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2456 IE_NAME = 'youtube:tab'
2459 # playlists, multipage
2460 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2461 'playlist_mincount': 94,
2463 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2464 'title': 'Игорь Клейнер - Playlists',
2465 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2466 'uploader': 'Игорь Клейнер',
2467 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2470 # playlists, multipage, different order
2471 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2472 'playlist_mincount': 94,
2474 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2475 'title': 'Игорь Клейнер - Playlists',
2476 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2477 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2478 'uploader': 'Игорь Клейнер',
2481 # playlists, singlepage
2482 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2483 'playlist_mincount': 4,
2485 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2486 'title': 'ThirstForScience - Playlists',
2487 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2488 'uploader': 'ThirstForScience',
2489 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2492 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2493 'only_matching': True,
2495 # basic, single video playlist
2496 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2498 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2499 'uploader': 'Sergey M.',
2500 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2501 'title': 'youtube-dl public playlist',
2503 'playlist_count': 1,
2506 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2508 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2509 'uploader': 'Sergey M.',
2510 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2511 'title': 'youtube-dl empty playlist',
2513 'playlist_count': 0,
2516 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2518 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2519 'title': 'lex will - Home',
2520 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2521 'uploader': 'lex will',
2522 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2524 'playlist_mincount': 2,
2527 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2529 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2530 'title': 'lex will - Videos',
2531 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2532 'uploader': 'lex will',
2533 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2535 'playlist_mincount': 975,
2537 # Videos tab, sorted by popular
2538 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2540 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2541 'title': 'lex will - Videos',
2542 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2543 'uploader': 'lex will',
2544 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2546 'playlist_mincount': 199,
2549 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2551 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2552 'title': 'lex will - Playlists',
2553 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2554 'uploader': 'lex will',
2555 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2557 'playlist_mincount': 17,
2560 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2562 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2563 'title': 'lex will - Community',
2564 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2565 'uploader': 'lex will',
2566 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2568 'playlist_mincount': 18,
2571 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2573 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2574 'title': 'lex will - Channels',
2575 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2576 'uploader': 'lex will',
2577 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2579 'playlist_mincount': 12,
2581 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2582 'only_matching': True,
2584 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2585 'only_matching': True,
2587 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2588 'only_matching': True,
2590 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2591 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2593 'title': '29C3: Not my department',
2594 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2595 'uploader': 'Christiaan008',
2596 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2597 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2599 'playlist_count': 96,
2601 'note': 'Large playlist',
2602 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2604 'title': 'Uploads from Cauchemar',
2605 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2606 'uploader': 'Cauchemar',
2607 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2609 'playlist_mincount': 1123,
2611 # even larger playlist, 8832 videos
2612 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2613 'only_matching': True,
2615 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2616 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2618 'title': 'Uploads from Interstellar Movie',
2619 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2620 'uploader': 'Interstellar Movie',
2621 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2623 'playlist_mincount': 21,
2625 # https://github.com/ytdl-org/youtube-dl/issues/21844
2626 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2628 'title': 'Data Analysis with Dr Mike Pound',
2629 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2630 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2631 'uploader': 'Computerphile',
2632 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2634 'playlist_mincount': 11,
2636 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2637 'only_matching': True,
2639 # Playlist URL that does not actually serve a playlist
2640 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2642 'id': 'FqZTN594JQw',
2644 'title': "Smiley's People 01 detective, Adventure Series, Action",
2645 'uploader': 'STREEM',
2646 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2647 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2648 'upload_date': '20150526',
2649 'license': 'Standard YouTube License',
2650 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2651 'categories': ['People & Blogs'],
2655 'dislike_count': int,
2658 'skip_download': True,
2660 'skip': 'This video is not available.',
2661 'add_ie': [YoutubeIE.ie_key()],
2663 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2664 'only_matching': True,
2666 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2667 'only_matching': True,
2669 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2671 'id': '9Auq9mYxFEE',
2673 'title': compat_str,
2674 'uploader': 'Sky News',
2675 'uploader_id': 'skynews',
2676 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2677 'upload_date': '20191102',
2678 'description': 'md5:85ddd75d888674631aaf9599a9a0b0ae',
2679 'categories': ['News & Politics'],
2682 'dislike_count': int,
2685 'skip_download': True,
2688 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2690 'id': 'a48o2S1cPoo',
2692 'title': 'The Young Turks - Live Main Show',
2693 'uploader': 'The Young Turks',
2694 'uploader_id': 'TheYoungTurks',
2695 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2696 'upload_date': '20150715',
2697 'license': 'Standard YouTube License',
2698 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2699 'categories': ['News & Politics'],
2700 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2702 'dislike_count': int,
2705 'skip_download': True,
2707 'only_matching': True,
2709 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2710 'only_matching': True,
2712 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2713 'only_matching': True,
2715 'url': 'https://www.youtube.com/feed/trending',
2716 'only_matching': True,
2719 'url': 'https://www.youtube.com/feed/library',
2720 'only_matching': True,
2723 'url': 'https://www.youtube.com/feed/history',
2724 'only_matching': True,
2727 'url': 'https://www.youtube.com/feed/subscriptions',
2728 'only_matching': True,
2731 'url': 'https://www.youtube.com/feed/watch_later',
2732 'only_matching': True,
2734 # no longer available?
2735 'url': 'https://www.youtube.com/feed/recommended',
2736 'only_matching': True,
2738 # inline playlist with not always working continuations
2739 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2740 'only_matching': True,
2742 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2743 'only_matching': True,
2745 'url': 'https://www.youtube.com/course',
2746 'only_matching': True,
2748 'url': 'https://www.youtube.com/zsecurity',
2749 'only_matching': True,
2751 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2752 'only_matching': True,
2754 'url': 'https://www.youtube.com/TheYoungTurks/live',
2755 'only_matching': True,
2757 'url': 'https://www.youtube.com/hashtag/cctv9',
2762 'playlist_mincount': 350,
2766 def suitable(cls, url):
2767 return False if YoutubeIE.suitable(url) else super(
2768 YoutubeTabIE, cls).suitable(url)
2770 def _extract_channel_id(self, webpage):
2771 channel_id = self._html_search_meta(
2772 'channelId', webpage, 'channel id', default=None)
2775 channel_url = self._html_search_meta(
2776 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2777 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2778 'twitter:app:url:googleplay'), webpage, 'channel url')
2779 return self._search_regex(
2780 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2781 channel_url, 'channel id')
2784 def _extract_basic_item_renderer(item):
2785 # Modified from _extract_grid_item_renderer
2787 'playlistRenderer', 'videoRenderer', 'channelRenderer',
2788 'gridPlaylistRenderer', 'gridVideoRenderer', 'gridChannelRenderer'
2790 for key, renderer in item.items():
2791 if key not in known_renderers:
2795 def _grid_entries(self, grid_renderer):
2796 for item in grid_renderer['items']:
2797 if not isinstance(item, dict):
2799 renderer = self._extract_basic_item_renderer(item)
2800 if not isinstance(renderer, dict):
2803 renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2805 playlist_id = renderer.get('playlistId')
2807 yield self.url_result(
2808 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2809 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2812 video_id = renderer.get('videoId')
2814 yield self._extract_video(renderer)
2816 channel_id = renderer.get('channelId')
2819 renderer, lambda x: x['title']['simpleText'], compat_str)
2820 yield self.url_result(
2821 'https://www.youtube.com/channel/%s' % channel_id,
2822 ie=YoutubeTabIE.ie_key(), video_title=title)
2824 def _shelf_entries_from_content(self, shelf_renderer):
2825 content = shelf_renderer.get('content')
2826 if not isinstance(content, dict):
2828 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
2830 # TODO: add support for nested playlists so each shelf is processed
2831 # as separate playlist
2832 # TODO: this includes only first N items
2833 for entry in self._grid_entries(renderer):
2835 renderer = content.get('horizontalListRenderer')
2840 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2842 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2844 shelf_url = urljoin('https://www.youtube.com', ep)
2846 # Skipping links to another channels, note that checking for
2847 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2849 if skip_channels and '/channels?' in shelf_url:
2852 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2853 yield self.url_result(shelf_url, video_title=title)
2854 # Shelf may not contain shelf URL, fallback to extraction from content
2855 for entry in self._shelf_entries_from_content(shelf_renderer):
2858 def _playlist_entries(self, video_list_renderer):
2859 for content in video_list_renderer['contents']:
2860 if not isinstance(content, dict):
2862 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2863 if not isinstance(renderer, dict):
2865 video_id = renderer.get('videoId')
2868 yield self._extract_video(renderer)
2870 def _rich_entries(self, rich_grid_renderer):
2872 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
2873 video_id = renderer.get('videoId')
2876 yield self._extract_video(renderer)
2878 def _video_entry(self, video_renderer):
2879 video_id = video_renderer.get('videoId')
2881 return self._extract_video(video_renderer)
2883 def _post_thread_entries(self, post_thread_renderer):
2884 post_renderer = try_get(
2885 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2886 if not post_renderer:
2889 video_renderer = try_get(
2890 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2893 entry = self._video_entry(video_renderer)
2896 # inline video links
2897 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2899 if not isinstance(run, dict):
2902 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2905 if not YoutubeIE.suitable(ep_url):
2907 ep_video_id = YoutubeIE._match_id(ep_url)
2908 if video_id == ep_video_id:
2910 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2912 def _post_thread_continuation_entries(self, post_thread_continuation):
2913 contents = post_thread_continuation.get('contents')
2914 if not isinstance(contents, list):
2916 for content in contents:
2917 renderer = content.get('backstagePostThreadRenderer')
2918 if not isinstance(renderer, dict):
2920 for entry in self._post_thread_entries(renderer):
2924 def _rich_grid_entries(self
, contents
):
2925 for content
in contents
:
2926 video_renderer
= try_get(content
, lambda x
: x
['richItemRenderer']['content']['videoRenderer'], dict)
2928 entry
= self
._video
_entry
(video_renderer
)
2934 def _build_continuation_query(continuation, ctp=None):
2936 'ctoken': continuation,
2937 'continuation': continuation,
2944 def _extract_next_continuation_data(renderer):
2945 next_continuation = try_get(
2946 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2947 if not next_continuation:
2949 continuation = next_continuation.get('continuation')
2950 if not continuation:
2952 ctp = next_continuation.get('clickTrackingParams')
2953 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2956 def _extract_continuation(cls, renderer):
2957 next_continuation = cls._extract_next_continuation_data(renderer)
2958 if next_continuation:
2959 return next_continuation
2961 for key in ('contents', 'items'):
2962 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2963 for content in contents:
2964 if not isinstance(content, dict):
2966 continuation_ep = try_get(
2967 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2969 if not continuation_ep:
2971 continuation = try_get(
2972 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2973 if not continuation:
2975 ctp = continuation_ep.get('clickTrackingParams')
2976 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2978 def _entries(self, tab, item_id, identity_token, account_syncid, ytcfg):
2980 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
2981 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
2982 for content in contents:
2983 if not isinstance(content, dict):
2985 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
2987 renderer = content.get('richItemRenderer')
2989 for entry in self._rich_entries(renderer):
2991 continuation_list[0] = self._extract_continuation(parent_renderer)
2993 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2994 for isr_content in isr_contents:
2995 if not isinstance(isr_content, dict):
2999 'playlistVideoListRenderer': self._playlist_entries,
3000 'gridRenderer': self._grid_entries,
3001 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
3002 'backstagePostThreadRenderer': self._post_thread_entries,
3003 'videoRenderer': lambda x: [self._video_entry(x)],
3005 for key, renderer in isr_content.items():
3006 if key not in known_renderers:
3008 for entry in known_renderers[key](renderer):
3011 continuation_list[0] = self._extract_continuation(renderer)
3014 if not continuation_list[0]:
3015 continuation_list[0] = self._extract_continuation(is_renderer)
3017 if not continuation_list[0]:
3018 continuation_list[0] = self._extract_continuation(parent_renderer)
3020 continuation_list = [None] # Python 2 doesnot support nonlocal
3021 tab_content = try_get(tab, lambda x: x['content'], dict)
3025 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
3026 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
3027 for entry in extract_entries(parent_renderer):
3029 continuation = continuation_list[0]
3030 context = self._extract_context(ytcfg)
3031 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
3033 for page_num in itertools.count(1):
3034 if not continuation:
3036 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
3037 retries = self._downloader.params.get('extractor_retries', 3)
3040 while count < retries:
3043 self.report_warning('%s. Retrying ...' % last_error)
3045 response = self._call_api(
3046 ep='browse', fatal=True, headers=headers,
3047 video_id='%s page %s' % (item_id, page_num),
3049 'continuation': continuation['continuation'],
3050 'clickTracking': {'clickTrackingParams': continuation['itct']},
3053 api_key=self._extract_api_key(ytcfg),
3054 note='Downloading API JSON%s' % (' (retry #%d)' % count if count else ''))
3055 except ExtractorError as e:
3056 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
3057 # Downloading page may result in intermittent 5xx HTTP error
3058 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
3059 last_error = 'HTTP Error %s' % e.cause.code
3064 # Youtube sometimes sends incomplete data
3065 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
3066 if dict_get(response,
3067 ('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints')):
3070 # Youtube may send alerts if there was an issue with the continuation page
3071 self._extract_alerts(response, expected=False)
3073 last_error = 'Incomplete data received'
3074 if count >= retries:
3075 self._downloader.report_error(last_error)
3079 visitor_data = try_get(
3080 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
3082 known_continuation_renderers = {
3083 'playlistVideoListContinuation': self._playlist_entries,
3084 'gridContinuation': self._grid_entries,
3085 'itemSectionContinuation': self._post_thread_continuation_entries,
3086 'sectionListContinuation': extract_entries, # for feeds
3088 continuation_contents = try_get(
3089 response, lambda x: x['continuationContents'], dict) or {}
3090 continuation_renderer = None
3091 for key, value in continuation_contents.items():
3092 if key not in known_continuation_renderers:
3094 continuation_renderer = value
3095 continuation_list = [None]
3096 for entry in known_continuation_renderers[key](continuation_renderer):
3098 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
3100 if continuation_renderer:
3104 'gridPlaylistRenderer': (self._grid_entries, 'items'),
3105 'gridVideoRenderer': (self._grid_entries, 'items'),
3106 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
3107 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
3108 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
3109 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents')
3111 on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3112 continuation_items = try_get(
3113 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
3114 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
3115 video_items_renderer = None
3116 for key, value in continuation_item.items():
3117 if key not in known_renderers:
3119 video_items_renderer = {known_renderers[key][1]: continuation_items}
3120 continuation_list = [None]
3121 for entry in known_renderers[key][0](video_items_renderer):
3123 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
3125 if video_items_renderer:
3130 def _extract_selected_tab(tabs):
3132 if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
3133 return tab['tabRenderer']
3135 raise ExtractorError('Unable to find selected tab')
3138 def _extract_uploader(data):
3140 sidebar_renderer = try_get(
3141 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3142 if sidebar_renderer:
3143 for item in sidebar_renderer:
3144 if not isinstance(item, dict):
3146 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
3147 if not isinstance(renderer, dict):
3150 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
3152 uploader['uploader'] = owner.get('text')
3153 uploader['uploader_id'] = try_get(
3154 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
3155 uploader['uploader_url'] = urljoin(
3156 'https://www.youtube.com/',
3157 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
3158 return {k: v for k, v in uploader.items() if v is not None}
3160 def _extract_from_tabs(self, item_id, webpage, data, tabs):
3161 playlist_id = title = description = channel_url = channel_name = channel_id = None
3162 thumbnails_list = tags = []
3164 selected_tab = self._extract_selected_tab(tabs)
3166 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
3168 channel_name = renderer.get('title')
3169 channel_url = renderer.get('channelUrl')
3170 channel_id = renderer.get('externalId')
3173 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
3176 title = renderer.get('title')
3177 description = renderer.get('description', '')
3178 playlist_id = channel_id
3179 tags = renderer.get('keywords', '').split()
3181 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
3184 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
3189 for t in thumbnails_list:
3190 if not isinstance(t, dict):
3192 thumbnail_url = url_or_none(t.get('url'))
3193 if not thumbnail_url:
3196 'url': thumbnail_url,
3197 'width': int_or_none(t.get('width')),
3198 'height': int_or_none(t.get('height')),
3200 if playlist_id is None:
3201 playlist_id = item_id
3204 try_get(data, lambda x: x['header']['hashtagHeaderRenderer']['hashtag']['simpleText'])
3206 title += format_field(selected_tab, 'title', ' - %s')
3209 'playlist_id': playlist_id,
3210 'playlist_title': title,
3211 'playlist_description': description,
3212 'uploader': channel_name,
3213 'uploader_id': channel_id,
3214 'uploader_url': channel_url,
3215 'thumbnails': thumbnails,
3219 metadata.update(self._extract_uploader(data))
3221 'channel': metadata['uploader'],
3222 'channel_id': metadata['uploader_id'],
3223 'channel_url': metadata['uploader_url']})
3224 return self.playlist_result(
3226 selected_tab, playlist_id,
3227 self._extract_identity_token(webpage, item_id),
3228 self._extract_account_syncid(data),
3229 self._extract_ytcfg(item_id, webpage)),
3232 def _extract_mix_playlist(self, playlist, playlist_id):
3233 first_id = last_id = None
3234 for page_num in itertools.count(1):
3235 videos = list(self._playlist_entries(playlist))
3238 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
3239 if start >= len(videos):
3241 for video in videos[start:]:
3242 if video['id'] == first_id:
3243 self.to_screen('First video %s found again; Assuming end of Mix' % first_id)
3246 first_id = first_id or videos[0]['id']
3247 last_id = videos[-1]['id']
3249 _, data = self._extract_webpage(
3250 'https://www.youtube.com/watch?list=%s&v=%s' % (playlist_id, last_id),
3251 '%s page %d' % (playlist_id, page_num))
3253 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3255 def _extract_from_playlist(self, item_id, url, data, playlist):
3256 title = playlist.get('title') or try_get(
3257 data, lambda x: x['titleText']['simpleText'], compat_str)
3258 playlist_id = playlist.get('playlistId') or item_id
3260 # Delegating everything except mix playlists to regular tab-based playlist URL
3261 playlist_url = urljoin(url, try_get(
3262 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3264 if playlist_url and playlist_url != url:
3265 return self.url_result(
3266 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3269 return self.playlist_result(
3270 self._extract_mix_playlist(playlist, playlist_id),
3271 playlist_id=playlist_id, playlist_title=title)
3273 def _extract_alerts(self, data, expected=False):
3275 def _real_extract_alerts():
3276 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
3277 if not isinstance(alert_dict, dict):
3279 for alert in alert_dict.values():
3280 alert_type = alert.get('type')
3283 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str) or ''
3285 yield alert_type, message
3286 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
3287 message += try_get(run, lambda x: x['text'], compat_str)
3289 yield alert_type, message
3293 for alert_type, alert_message in _real_extract_alerts():
3294 if alert_type.lower() == 'error':
3295 errors.append([alert_type, alert_message])
3297 warnings.append([alert_type, alert_message])
3299 for alert_type, alert_message in (warnings + errors[:-1]):
3300 self._downloader.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3302 raise ExtractorError('YouTube said: %s' % errors[-1][1], expected=expected)
3304 def _extract_webpage(self, url, item_id):
3305 retries = self._downloader.params.get('extractor_retries', 3)
3307 last_error = 'Incomplete yt initial data recieved'
3308 while count < retries:
3310 # Sometimes youtube returns a webpage with incomplete ytInitialData
3311 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3313 self.report_warning('%s. Retrying ...' % last_error)
3314 webpage = self._download_webpage(
3316 'Downloading webpage%s' % (' (retry #%d)' % count if count else ''))
3317 data = self._extract_yt_initial_data(item_id, webpage)
3318 self._extract_alerts(data, expected=True)
3319 if data.get('contents') or data.get('currentVideoEndpoint'):
3321 if count >= retries:
3322 self._downloader.report_error(last_error)
3323 return webpage, data
3325 def _real_extract(self, url):
3326 item_id = self._match_id(url)
3327 url = compat_urlparse.urlunparse(
3328 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3330 # This is not matched in a channel page with a tab selected
3331 mobj = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
3332 mobj = mobj.groupdict() if mobj else {}
3333 if mobj and not mobj.get('not_channel'):
3334 self._downloader.report_warning(
3335 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3336 'To download only the videos in the home page, add a "/featured" to the URL')
3337 url = '%s/videos%s' % (mobj.get('pre'), mobj.get('post') or '')
3339 # Handle both video/playlist URLs
3340 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3341 video_id = qs.get('v', [None])[0]
3342 playlist_id = qs.get('list', [None])[0]
3344 if not video_id and (mobj.get('not_channel') or '').startswith('watch'):
3346 # If there is neither video or playlist ids,
3347 # youtube redirects to home page, which is undesirable
3348 raise ExtractorError('Unable to recognize tab page')
3349 self._downloader.report_warning('A video URL was given without video ID. Trying to download playlist %s' % playlist_id)
3350 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3352 if video_id and playlist_id:
3353 if self._downloader.params.get('noplaylist'):
3354 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3355 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3356 self.to_screen('Downloading playlist %s; add --no-playlist to just download video %s' % (playlist_id, video_id))
3358 webpage, data = self._extract_webpage(url, item_id)
3361 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3363 return self._extract_from_tabs(item_id, webpage, data, tabs)
3366 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3368 return self._extract_from_playlist(item_id, url, data, playlist)
3371 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3372 compat_str) or video_id
3374 self._downloader.report_warning('Unable to recognize playlist. Downloading just video %s' % video_id)
3375 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3377 raise ExtractorError('Unable to recognize tab page')
3380 class YoutubePlaylistIE(InfoExtractor):
3381 IE_DESC = 'YouTube.com playlists'
3382 _VALID_URL = r'''(?x
)(?
:
3387 youtube(?
:kids
)?\
.com|
3392 (?P
<id>%(playlist_id)s)
3393 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3394 IE_NAME = 'youtube:playlist'
3396 'note': 'issue #673',
3397 'url': 'PLBB231211A4F62143',
3399 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3400 'id': 'PLBB231211A4F62143',
3401 'uploader': 'Wickydoo',
3402 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3404 'playlist_mincount': 29,
3406 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3408 'title': 'YDL_safe_search',
3409 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3411 'playlist_count': 2,
3412 'skip': 'This playlist is private',
3415 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3416 'playlist_count': 4,
3419 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3420 'uploader': 'milan',
3421 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3424 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3425 'playlist_mincount': 982,
3427 'title': '2018 Chinese New Singles (11/6 updated)',
3428 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3430 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3433 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3434 'only_matching': True,
3436 # music album playlist
3437 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3438 'only_matching': True,
3442 def suitable(cls, url):
3443 return False if YoutubeTabIE.suitable(url) else super(
3444 YoutubePlaylistIE, cls).suitable(url)
3446 def _real_extract(self, url):
3447 playlist_id = self._match_id(url)
3448 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3450 qs = {'list': playlist_id}
3451 return self.url_result(
3452 update_url_query('https://www.youtube.com/playlist', qs),
3453 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3456 class YoutubeYtBeIE(InfoExtractor):
3457 IE_DESC = 'youtu.be'
3458 _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}
3460 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3462 'id': 'yeWKywCrFtk',
3464 'title': 'Small Scale Baler and Braiding Rugs',
3465 'uploader': 'Backus-Page House Museum',
3466 'uploader_id': 'backuspagemuseum',
3467 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3468 'upload_date': '20161008',
3469 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3470 'categories': ['Nonprofits & Activism'],
3473 'dislike_count': int,
3477 'skip_download': True,
3480 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3481 'only_matching': True,
3484 def _real_extract(self, url):
3485 mobj = re.match(self._VALID_URL, url)
3486 video_id = mobj.group('id')
3487 playlist_id = mobj.group('playlist_id')
3488 return self.url_result(
3489 update_url_query('https://www.youtube.com/watch', {
3491 'list': playlist_id,
3492 'feature': 'youtu.be',
3493 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3496 class YoutubeYtUserIE(InfoExtractor):
3497 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3498 _VALID_URL = r'ytuser:(?P<id>.+)'
3500 'url': 'ytuser:phihag',
3501 'only_matching': True,
3504 def _real_extract(self, url):
3505 user_id = self._match_id(url)
3506 return self.url_result(
3507 'https://www.youtube.com/user/%s' % user_id,
3508 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3511 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3512 IE_NAME = 'youtube:favorites'
3513 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3514 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3515 _LOGIN_REQUIRED = True
3518 'only_matching': True,
3520 'url': ':ytfavorites',
3521 'only_matching': True,
3524 def _real_extract(self, url):
3525 return self.url_result(
3526 'https://www.youtube.com/playlist?list=LL',
3527 ie=YoutubeTabIE.ie_key())
3530 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
3531 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3532 # there doesn't appear to be a real limit, for example if you search for
3533 # 'python' you get more than 8.000.000 results
3534 _MAX_RESULTS = float('inf')
3535 IE_NAME = 'youtube:search'
3536 _SEARCH_KEY = 'ytsearch'
3537 _SEARCH_PARAMS = None
3540 def _entries(self, query, n):
3541 data = {'query': query}
3542 if self._SEARCH_PARAMS:
3543 data['params'] = self._SEARCH_PARAMS
3545 for page_num in itertools.count(1):
3546 search = self._call_api(
3547 ep='search', video_id='query "%s"' % query, fatal=False,
3548 note='Downloading page %s' % page_num, query=data)
3551 slr_contents = try_get(
3553 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3554 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3556 if not slr_contents:
3559 # Youtube sometimes adds promoted content to searches,
3560 # changing the index location of videos and token.
3561 # So we search through all entries till we find them.
3562 continuation_token = None
3563 for slr_content in slr_contents:
3564 if continuation_token is None:
3565 continuation_token = try_get(
3567 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3570 isr_contents = try_get(
3572 lambda x: x['itemSectionRenderer']['contents'],
3574 if not isr_contents:
3576 for content in isr_contents:
3577 if not isinstance(content, dict):
3579 video = content.get('videoRenderer')
3580 if not isinstance(video, dict):
3582 video_id = video.get('videoId')
3586 yield self._extract_video(video)
3591 if not continuation_token:
3593 data['continuation'] = continuation_token
3595 def _get_n_results(self, query, n):
3596 """Get a specified number of results for a query"""
3597 return self.playlist_result(self._entries(query, n), query)
3600 class YoutubeSearchDateIE(YoutubeSearchIE):
3601 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3602 _SEARCH_KEY = 'ytsearchdate'
3603 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3604 _SEARCH_PARAMS = 'CAI%3D'
3607 class YoutubeSearchURLIE(YoutubeSearchIE):
3608 IE_DESC = 'YouTube.com search URLs'
3609 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
3610 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
3611 # _MAX_RESULTS = 100
3613 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3614 'playlist_mincount': 5,
3616 'title': 'youtube-dl test video',
3619 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3620 'only_matching': True,
3624 def _make_valid_url(cls):
3625 return cls._VALID_URL
3627 def _real_extract(self, url):
3628 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
3629 query = (qs.get('search_query') or qs.get('q'))[0]
3630 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
3631 return self._get_n_results(query, self._MAX_RESULTS)
3634 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3636 Base class for feed extractors
3637 Subclasses must define the _FEED_NAME property.
3639 _LOGIN_REQUIRED = True
3644 return 'youtube:%s' % self._FEED_NAME
3646 def _real_initialize(self):
3649 def _real_extract(self, url):
3650 return self.url_result(
3651 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3652 ie=YoutubeTabIE.ie_key())
3655 class YoutubeWatchLaterIE(InfoExtractor):
3656 IE_NAME = 'youtube:watchlater'
3657 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3658 _VALID_URL = r':ytwatchlater'
3660 'url': ':ytwatchlater',
3661 'only_matching': True,
3664 def _real_extract(self, url):
3665 return self.url_result(
3666 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3669 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3670 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3671 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
3672 _FEED_NAME = 'recommended'
3675 'only_matching': True,
3677 'url': ':ytrecommended',
3678 'only_matching': True,
3680 'url': 'https://youtube.com',
3681 'only_matching': True,
3685 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3686 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
3687 _VALID_URL = r':ytsub(?:scription)?s?'
3688 _FEED_NAME = 'subscriptions'
3691 'only_matching': True,
3693 'url': ':ytsubscriptions',
3694 'only_matching': True,
3698 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3699 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
3700 _VALID_URL = r':ythis(?:tory)?'
3701 _FEED_NAME = 'history'
3703 'url': ':ythistory',
3704 'only_matching': True,
3708 class YoutubeTruncatedURLIE(InfoExtractor):
3709 IE_NAME = 'youtube:truncated_url'
3710 IE_DESC = False # Do not list
3711 _VALID_URL = r'''(?x
)
3713 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
3716 annotation_id
=annotation_
[^
&]+|
3722 attribution_link
\?a
=[^
&]+
3728 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3729 'only_matching': True,
3731 'url': 'https://www.youtube.com/watch?',
3732 'only_matching': True,
3734 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3735 'only_matching': True,
3737 'url': 'https://www.youtube.com/watch?feature=foo',
3738 'only_matching': True,
3740 'url': 'https://www.youtube.com/watch?hl=en-GB',
3741 'only_matching': True,
3743 'url': 'https://www.youtube.com/watch?t=2372',
3744 'only_matching': True,
3747 def _real_extract(self, url):
3748 raise ExtractorError(
3749 'Did you forget to quote the URL? Remember that & is a meta '
3750 'character in most shells, so you want to put the URL in quotes, '
3752 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3753 ' or simply youtube-dl BaW_jenozKc .',
3757 class YoutubeTruncatedIDIE(InfoExtractor):
3758 IE_NAME = 'youtube:truncated_id'
3759 IE_DESC = False # Do not list
3760 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
3763 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
3764 'only_matching': True,
3767 def _real_extract(self, url):
3768 video_id = self._match_id(url)
3769 raise ExtractorError(
3770 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),