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
57 return compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
60 class YoutubeBaseInfoExtractor(InfoExtractor
):
61 """Provide base functions for Youtube extractors"""
62 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
63 _TWOFACTOR_URL
= 'https://accounts.google.com/signin/challenge'
65 _LOOKUP_URL
= 'https://accounts.google.com/_/signin/sl/lookup'
66 _CHALLENGE_URL
= 'https://accounts.google.com/_/signin/sl/challenge'
67 _TFA_URL
= 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
70 r
'channel|c|user|playlist|watch|w|v|embed|e|watch_popup|'
71 r
'movies|results|shared|hashtag|trending|feed|feeds|oembed|'
72 r
'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout')
74 _NETRC_MACHINE
= 'youtube'
75 # If True it will raise an error if no login info is provided
76 _LOGIN_REQUIRED
= False
78 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
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
.get_param('cookiefile') is None:
92 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
93 # if self.get_param('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
.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):
340 Extract syncId required to download private playlists of secondary channels
341 @param data Either response or ytcfg
344 data, (lambda x: x['responseContext
']['mainAppWebResponseContext
']['datasyncId
'],
345 lambda x: x['DATASYNC_ID
']), compat_str) or '').split("||")
346 if len(sync_ids) >= 2 and sync_ids[1]:
347 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
348 # and just "user_syncid||" for primary channel. We only want the channel_syncid
350 # ytcfg includes channel_syncid if on secondary channel
351 return data.get('DELEGATED_SESSION_ID
')
353 def _extract_ytcfg(self, video_id, webpage):
356 return self._parse_json(
358 r'ytcfg\
.set\s
*\
(\s
*({.+?}
)\s
*\
)\s
*;', webpage, 'ytcfg
',
359 default='{}'), video_id, fatal=False) or {}
361 def __extract_client_version(self
, ytcfg
):
362 return try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_VERSION'], compat_str
) or self
._YT
_WEB
_CLIENT
_VERSION
364 def _extract_context(self
, ytcfg
=None):
365 context
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CONTEXT'], dict)
369 # Recreate the client context (required)
370 client_version
= self
.__extract
_client
_version
(ytcfg
)
371 client_name
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_NAME'], compat_str
) or 'WEB'
374 'clientName': client_name
,
375 'clientVersion': client_version
,
378 visitor_data
= try_get(ytcfg
, lambda x
: x
['VISITOR_DATA'], compat_str
)
380 context
['client']['visitorData'] = visitor_data
383 def _generate_api_headers(self
, ytcfg
=None, identity_token
=None, account_syncid
=None, visitor_data
=None):
385 'X-YouTube-Client-Name': '1',
386 'X-YouTube-Client-Version': self
.__extract
_client
_version
(ytcfg
),
389 headers
['x-youtube-identity-token'] = identity_token
391 headers
['X-Goog-PageId'] = account_syncid
392 headers
['X-Goog-AuthUser'] = 0
394 headers
['x-goog-visitor-id'] = visitor_data
395 auth
= self
._generate
_sapisidhash
_header
()
397 headers
['Authorization'] = auth
398 headers
['X-Origin'] = 'https://www.youtube.com'
402 def is_music_url(url
):
403 return re
.match(r
'https?://music\.youtube\.com/', url
) is not None
405 def _extract_video(self
, renderer
):
406 video_id
= renderer
.get('videoId')
409 (lambda x
: x
['title']['runs'][0]['text'],
410 lambda x
: x
['title']['simpleText']), compat_str
)
411 description
= try_get(
412 renderer
, lambda x
: x
['descriptionSnippet']['runs'][0]['text'],
414 duration
= parse_duration(try_get(
415 renderer
, lambda x
: x
['lengthText']['simpleText'], compat_str
))
416 view_count_text
= try_get(
417 renderer
, lambda x
: x
['viewCountText']['simpleText'], compat_str
) or ''
418 view_count
= str_to_int(self
._search
_regex
(
419 r
'^([\d,]+)', re
.sub(r
'\s', '', view_count_text
),
420 'view count', default
=None))
423 (lambda x
: x
['ownerText']['runs'][0]['text'],
424 lambda x
: x
['shortBylineText']['runs'][0]['text']), compat_str
)
427 'ie_key': YoutubeIE
.ie_key(),
431 'description': description
,
432 'duration': duration
,
433 'view_count': view_count
,
434 'uploader': uploader
,
438 class YoutubeIE(YoutubeBaseInfoExtractor
):
439 IE_DESC
= 'YouTube.com'
441 # invidious-redirect websites
442 r
'(?:www\.)?redirect\.invidious\.io',
443 r
'(?:(?:www|dev)\.)?invidio\.us',
444 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
445 r
'(?:www\.)?invidious\.pussthecat\.org',
446 r
'(?:www\.)?invidious\.zee\.li',
447 r
'(?:(?:www|au)\.)?ytprivate\.com',
448 r
'(?:www\.)?invidious\.namazso\.eu',
449 r
'(?:www\.)?invidious\.ethibox\.fr',
450 r
'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
451 r
'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
452 r
'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
453 r
'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
454 # youtube-dl invidious instances list
455 r
'(?:(?:www|no)\.)?invidiou\.sh',
456 r
'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
457 r
'(?:www\.)?invidious\.kabi\.tk',
458 r
'(?:www\.)?invidious\.mastodon\.host',
459 r
'(?:www\.)?invidious\.zapashcanon\.fr',
460 r
'(?:www\.)?invidious\.kavin\.rocks',
461 r
'(?:www\.)?invidious\.tinfoil-hat\.net',
462 r
'(?:www\.)?invidious\.himiko\.cloud',
463 r
'(?:www\.)?invidious\.reallyancient\.tech',
464 r
'(?:www\.)?invidious\.tube',
465 r
'(?:www\.)?invidiou\.site',
466 r
'(?:www\.)?invidious\.site',
467 r
'(?:www\.)?invidious\.xyz',
468 r
'(?:www\.)?invidious\.nixnet\.xyz',
469 r
'(?:www\.)?invidious\.048596\.xyz',
470 r
'(?:www\.)?invidious\.drycat\.fr',
471 r
'(?:www\.)?inv\.skyn3t\.in',
472 r
'(?:www\.)?tube\.poal\.co',
473 r
'(?:www\.)?tube\.connect\.cafe',
474 r
'(?:www\.)?vid\.wxzm\.sx',
475 r
'(?:www\.)?vid\.mint\.lgbt',
476 r
'(?:www\.)?vid\.puffyan\.us',
477 r
'(?:www\.)?yewtu\.be',
478 r
'(?:www\.)?yt\.elukerio\.org',
479 r
'(?:www\.)?yt\.lelux\.fi',
480 r
'(?:www\.)?invidious\.ggc-project\.de',
481 r
'(?:www\.)?yt\.maisputain\.ovh',
482 r
'(?:www\.)?ytprivate\.com',
483 r
'(?:www\.)?invidious\.13ad\.de',
484 r
'(?:www\.)?invidious\.toot\.koeln',
485 r
'(?:www\.)?invidious\.fdn\.fr',
486 r
'(?:www\.)?watch\.nettohikari\.com',
487 r
'(?:www\.)?kgg2m7yk5aybusll\.onion',
488 r
'(?:www\.)?qklhadlycap4cnod\.onion',
489 r
'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
490 r
'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
491 r
'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
492 r
'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
493 r
'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
494 r
'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
496 _VALID_URL
= r
"""(?x)^
498 (?:https?://|//) # http(s):// or protocol-independent URL
499 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
500 (?:www\.)?deturl\.com/www\.youtube\.com|
501 (?:www\.)?pwnyoutube\.com|
502 (?:www\.)?hooktube\.com|
503 (?:www\.)?yourepeat\.com|
506 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
507 (?:.*?\#/)? # handle anchor (#/) redirect urls
508 (?: # the various things that can precede the ID:
509 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
510 |(?: # or the v= param in all its forms
511 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
512 (?:\?|\#!?) # the params delimiter ? or # or #!
513 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
518 youtu\.be| # just youtu.be/xxxx
519 vid\.plus| # or vid.plus/xxxx
520 zwearz\.com/watch| # or zwearz.com/watch/xxxx
523 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
525 )? # all until now is optional -> you can pass the naked ID
526 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
527 (?(1).+)? # if we found the ID, everything can follow
529 'invidious': '|'.join(_INVIDIOUS_SITES
),
532 r
'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
533 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$',
534 r
'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
537 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
538 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
539 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'}
,
540 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'}
,
541 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'}
,
542 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
543 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
544 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
545 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
546 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'}
,
547 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
548 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
549 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
550 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
551 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
552 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
553 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
554 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
558 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
559 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
560 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
561 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
562 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20}
,
563 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
564 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
566 # Apple HTTP Live Streaming
567 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
568 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
569 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
570 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
571 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
572 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
573 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
574 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10}
,
577 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
578 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
579 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
580 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
581 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
582 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}
, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
583 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
584 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
585 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
586 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
587 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
588 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
591 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'}
,
592 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'}
,
593 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'}
,
594 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
595 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
596 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'}
,
597 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'}
,
600 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
601 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
602 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
603 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
604 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
605 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
606 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'}
,
607 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
608 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
609 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
610 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
611 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
612 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
613 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
614 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
615 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
616 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
617 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
618 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
619 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
620 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
621 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
624 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128}
,
625 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256}
,
627 # Dash webm audio with opus inside
628 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50}
,
629 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70}
,
630 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160}
,
633 '_rtmp': {'protocol': 'rtmp'}
,
635 # av01 video only formats sometimes served with "unknown" codecs
636 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
637 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
638 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
639 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
641 _SUBTITLE_FORMATS
= ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
648 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
652 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
653 'uploader': 'Philipp Hagemeister',
654 'uploader_id': 'phihag',
655 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
656 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
657 'channel_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
658 'upload_date': '20121002',
659 '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 .',
660 'categories': ['Science & Technology'],
661 'tags': ['youtube-dl'],
665 'dislike_count': int,
671 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
672 'note': 'Embed-only video (#1746)',
676 'upload_date': '20120608',
677 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
678 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
679 'uploader': 'SET India',
680 'uploader_id': 'setindia',
681 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/setindia',
684 'skip': 'Private video',
687 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
688 'note': 'Use the first video ID in the URL',
692 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
693 'uploader': 'Philipp Hagemeister',
694 'uploader_id': 'phihag',
695 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
696 'upload_date': '20121002',
697 '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 .',
698 'categories': ['Science & Technology'],
699 'tags': ['youtube-dl'],
703 'dislike_count': int,
706 'skip_download': True,
710 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
711 'note': '256k DASH audio (format 141) via DASH manifest',
715 'upload_date': '20121002',
716 'uploader_id': '8KVIDEO',
717 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
719 'uploader': '8KVIDEO',
720 'title': 'UHDTV TEST 8K VIDEO.mp4'
723 'youtube_include_dash_manifest': True,
726 'skip': 'format 141 not served anymore',
728 # DASH manifest with encrypted signature
730 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
734 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
735 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
737 'uploader': 'AfrojackVEVO',
738 'uploader_id': 'AfrojackVEVO',
739 'upload_date': '20131011',
743 'youtube_include_dash_manifest': True,
744 'format': '141/bestaudio[ext=m4a]',
749 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
754 'upload_date': '20100909',
755 'uploader': 'Amazing Atheist',
756 'uploader_id': 'TheAmazingAtheist',
757 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
758 'title': 'Burning Everyone\'s Koran',
759 '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',
762 # Normal age-gate video (embed allowed)
764 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
768 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
769 'description': r
're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
771 'uploader': 'The Witcher',
772 'uploader_id': 'WitcherGame',
773 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
774 'upload_date': '20140605',
778 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
779 # YouTube Red ad is not captured for creator
781 'url': '__2ABJjxzNo',
786 'upload_date': '20100430',
787 'uploader_id': 'deadmau5',
788 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/deadmau5',
789 'creator': 'deadmau5',
790 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
791 'uploader': 'deadmau5',
792 'title': 'Deadmau5 - Some Chords (HD)',
793 'alt_title': 'Some Chords',
795 'expected_warnings': [
796 'DASH manifest missing',
799 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
801 'url': 'lqQg6PlCWgI',
806 'upload_date': '20150827',
807 'uploader_id': 'olympic',
808 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/olympic',
809 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
810 'uploader': 'Olympic',
811 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
814 'skip_download': 'requires avconv',
819 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
823 'stretched_ratio': 16 / 9.,
825 'upload_date': '20110310',
826 'uploader_id': 'AllenMeow',
827 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
828 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
830 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
833 # url_encoded_fmt_stream_map is empty string
835 'url': 'qEJwOuvDf7I',
839 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
841 'upload_date': '20150404',
842 'uploader_id': 'spbelect',
843 'uploader': 'Наблюдатели Петербурга',
846 'skip_download': 'requires avconv',
848 'skip': 'This live event has ended.',
850 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
852 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
856 'title': 'md5:7b81415841e02ecd4313668cde88737a',
857 'description': 'md5:116377fd2963b81ec4ce64b542173306',
859 'upload_date': '20150625',
860 'uploader_id': 'dorappi2000',
861 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
862 'uploader': 'dorappi2000',
863 'formats': 'mincount:31',
865 'skip': 'not actual anymore',
867 # DASH manifest with segment_list
869 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
870 'md5': '8ce563a1d667b599d21064e982ab9e31',
874 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
875 'uploader': 'Airtek',
876 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
877 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
878 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
881 'youtube_include_dash_manifest': True,
882 'format': '135', # bestvideo
884 'skip': 'This live event has ended.',
887 # Multifeed videos (multiple cameras), URL is for Main Camera
888 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
891 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
892 'description': 'md5:e03b909557865076822aa169218d6a5d',
898 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
899 'description': 'md5:e03b909557865076822aa169218d6a5d',
901 'upload_date': '20161111',
902 'uploader': 'Team PGP',
903 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
904 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
910 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
911 'description': 'md5:e03b909557865076822aa169218d6a5d',
913 'upload_date': '20161111',
914 'uploader': 'Team PGP',
915 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
916 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
922 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
923 'description': 'md5:e03b909557865076822aa169218d6a5d',
925 'upload_date': '20161111',
926 'uploader': 'Team PGP',
927 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
928 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
934 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
935 'description': 'md5:e03b909557865076822aa169218d6a5d',
937 'upload_date': '20161111',
938 'uploader': 'Team PGP',
939 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
940 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
944 'skip_download': True,
948 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
949 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
952 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
955 'skip': 'Not multifeed anymore',
958 'url': 'https://vid.plus/FlRa-iH7PGw',
959 'only_matching': True,
962 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
963 'only_matching': True,
966 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
967 # Also tests cut-off URL expansion in video description (see
968 # https://github.com/ytdl-org/youtube-dl/issues/1892,
969 # https://github.com/ytdl-org/youtube-dl/issues/8164)
970 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
974 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
975 'alt_title': 'Dark Walk - Position Music',
976 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
978 'upload_date': '20151119',
979 'uploader_id': 'IronSoulElf',
980 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
981 'uploader': 'IronSoulElf',
982 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
983 'track': 'Dark Walk - Position Music',
984 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
985 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
988 'skip_download': True,
992 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
993 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
994 'only_matching': True,
997 # Video with yt:stretch=17:0
998 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
1000 'id': 'Q39EVAstoRM',
1002 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
1003 'description': 'md5:ee18a25c350637c8faff806845bddee9',
1004 'upload_date': '20151107',
1005 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
1006 'uploader': 'CH GAMER DROID',
1009 'skip_download': True,
1011 'skip': 'This video does not exist.',
1014 # Video with incomplete 'yt:stretch=16:'
1015 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
1016 'only_matching': True,
1019 # Video licensed under Creative Commons
1020 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1022 'id': 'M4gD1WSo5mA',
1024 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1025 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
1027 'upload_date': '20150127',
1028 'uploader_id': 'BerkmanCenter',
1029 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
1030 'uploader': 'The Berkman Klein Center for Internet & Society',
1031 'license': 'Creative Commons Attribution license (reuse allowed)',
1034 'skip_download': True,
1038 # Channel-like uploader_url
1039 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1041 'id': 'eQcmzGIKrzg',
1043 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1044 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1046 'upload_date': '20151119',
1047 'uploader': 'Bernie Sanders',
1048 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1049 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
1050 'license': 'Creative Commons Attribution license (reuse allowed)',
1053 'skip_download': True,
1057 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
1058 'only_matching': True,
1061 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
1062 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1063 'only_matching': True,
1066 # Rental video preview
1067 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1069 'id': 'uGpuVWrhIzE',
1071 'title': 'Piku - Trailer',
1072 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1073 'upload_date': '20150811',
1074 'uploader': 'FlixMatrix',
1075 'uploader_id': 'FlixMatrixKaravan',
1076 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
1077 'license': 'Standard YouTube License',
1080 'skip_download': True,
1082 'skip': 'This video is not available.',
1085 # YouTube Red video with episode data
1086 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1088 'id': 'iqKdEhx-dD4',
1090 'title': 'Isolation - Mind Field (Ep 1)',
1091 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1093 'upload_date': '20170118',
1094 'uploader': 'Vsauce',
1095 'uploader_id': 'Vsauce',
1096 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1097 'series': 'Mind Field',
1099 'episode_number': 1,
1102 'skip_download': True,
1104 'expected_warnings': [
1105 'Skipping DASH manifest',
1109 # The following content has been identified by the YouTube community
1110 # as inappropriate or offensive to some audiences.
1111 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1113 'id': '6SJNVb0GnPI',
1115 'title': 'Race Differences in Intelligence',
1116 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1118 'upload_date': '20140124',
1119 'uploader': 'New Century Foundation',
1120 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1121 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1124 'skip_download': True,
1126 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1130 'url': '1t24XAntNCY',
1131 'only_matching': True,
1134 # geo restricted to JP
1135 'url': 'sJL6WA-aGkQ',
1136 'only_matching': True,
1139 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1140 'only_matching': True,
1143 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1144 'only_matching': True,
1147 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1148 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1149 'only_matching': True,
1153 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1154 'only_matching': True,
1157 # Video with unsupported adaptive stream type formats
1158 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1160 'id': 'Z4Vy8R84T1U',
1162 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1163 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1165 'upload_date': '20130923',
1166 'uploader': 'Amelia Putri Harwita',
1167 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1168 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1169 'formats': 'maxcount:10',
1172 'skip_download': True,
1173 'youtube_include_dash_manifest': False,
1175 'skip': 'not actual anymore',
1178 # Youtube Music Auto-generated description
1179 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1181 'id': 'MgNrAu2pzNs',
1183 'title': 'Voyeur Girl',
1184 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1185 'upload_date': '20190312',
1186 'uploader': 'Stephen - Topic',
1187 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1188 'artist': 'Stephen',
1189 'track': 'Voyeur Girl',
1190 'album': 'it\'s too much love to know my dear',
1191 'release_date': '20190313',
1192 'release_year': 2019,
1195 'skip_download': True,
1199 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1200 'only_matching': True,
1203 # invalid -> valid video id redirection
1204 'url': 'DJztXj2GPfl',
1206 'id': 'DJztXj2GPfk',
1208 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1209 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1210 'upload_date': '20090125',
1211 'uploader': 'Prochorowka',
1212 'uploader_id': 'Prochorowka',
1213 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1214 'artist': 'Panjabi MC',
1215 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1216 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1219 'skip_download': True,
1221 'skip': 'Video unavailable',
1224 # empty description results in an empty string
1225 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1227 'id': 'x41yOUIvK2k',
1229 'title': 'IMG 3456',
1231 'upload_date': '20170613',
1232 'uploader_id': 'ElevageOrVert',
1233 'uploader': 'ElevageOrVert',
1236 'skip_download': True,
1240 # with '};' inside yt initial data (see [1])
1241 # see [2] for an example with '};' inside ytInitialPlayerResponse
1242 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1243 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1244 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1246 'id': 'CHqg6qOn4no',
1248 'title': 'Part 77 Sort a list of simple types in c#',
1249 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1250 'upload_date': '20130831',
1251 'uploader_id': 'kudvenkat',
1252 'uploader': 'kudvenkat',
1255 'skip_download': True,
1259 # another example of '};' in ytInitialData
1260 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1261 'only_matching': True,
1264 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1265 'only_matching': True,
1268 # https://github.com/ytdl-org/youtube-dl/pull/28094
1269 'url': 'OtqTfy26tG0',
1271 'id': 'OtqTfy26tG0',
1273 'title': 'Burn Out',
1274 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1275 'upload_date': '20141120',
1276 'uploader': 'The Cinematic Orchestra - Topic',
1277 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1278 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1279 'artist': 'The Cinematic Orchestra',
1280 'track': 'Burn Out',
1281 'album': 'Every Day',
1282 'release_data': None,
1283 'release_year': None,
1286 'skip_download': True,
1290 # controversial video, only works with bpctr when authenticated with cookies
1291 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1292 'only_matching': True,
1295 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1296 'url': 'cBvYw8_A0vQ',
1298 'id': 'cBvYw8_A0vQ',
1300 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
1301 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1302 'upload_date': '20201120',
1303 'uploader': 'Walk around Japan',
1304 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1305 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1308 'skip_download': True,
1311 # Has multiple audio streams
1312 'url': 'WaOKSUlf4TM',
1313 'only_matching': True
1315 # Requires Premium: has format 141 when requested using YTM url
1316 'url': 'https://music.youtube.com/watch?v=XclachpHxis',
1317 'only_matching': True
1319 # multiple subtitles with same lang_code
1320 'url': 'https://www.youtube.com/watch?v=wsQiKKfKxug',
1321 'only_matching': True,
1326 def suitable(cls
, url
):
1327 # Hack for lazy extractors until more generic solution is implemented
1329 from .youtube
import parse_qs
1331 if qs
.get('list', [None])[0]:
1333 return super(YoutubeIE
, cls
).suitable(url
)
1335 def __init__(self
, *args
, **kwargs
):
1336 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
1337 self
._code
_cache
= {}
1338 self
._player
_cache
= {}
1340 def _signature_cache_id(self
, example_sig
):
1341 """ Return a string representation of a signature """
1342 return '.'.join(compat_str(len(part
)) for part
in example_sig
.split('.'))
1345 def _extract_player_info(cls
, player_url
):
1346 for player_re
in cls
._PLAYER
_INFO
_RE
:
1347 id_m
= re
.search(player_re
, player_url
)
1351 raise ExtractorError('Cannot identify player %r' % player_url
)
1352 return id_m
.group('id')
1354 def _extract_signature_function(self
, video_id
, player_url
, example_sig
):
1355 player_id
= self
._extract
_player
_info
(player_url
)
1357 # Read from filesystem cache
1358 func_id
= 'js_%s_%s' % (
1359 player_id
, self
._signature
_cache
_id
(example_sig
))
1360 assert os
.path
.basename(func_id
) == func_id
1362 cache_spec
= self
._downloader
.cache
.load('youtube-sigfuncs', func_id
)
1363 if cache_spec
is not None:
1364 return lambda s
: ''.join(s
[i
] for i
in cache_spec
)
1366 if player_id
not in self
._code
_cache
:
1367 self
._code
_cache
[player_id
] = self
._download
_webpage
(
1368 player_url
, video_id
,
1369 note
='Downloading player ' + player_id
,
1370 errnote
='Download of %s failed' % player_url
)
1371 code
= self
._code
_cache
[player_id
]
1372 res
= self
._parse
_sig
_js
(code
)
1374 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1375 cache_res
= res(test_string
)
1376 cache_spec
= [ord(c
) for c
in cache_res
]
1378 self
._downloader
.cache
.store('youtube-sigfuncs', func_id
, cache_spec
)
1381 def _print_sig_code(self
, func
, example_sig
):
1382 def gen_sig_code(idxs
):
1383 def _genslice(start
, end
, step
):
1384 starts
= '' if start
== 0 else str(start
)
1385 ends
= (':%d' % (end
+ step
)) if end
+ step
>= 0 else ':'
1386 steps
= '' if step
== 1 else (':%d' % step
)
1387 return 's[%s%s%s]' % (starts
, ends
, steps
)
1390 # Quelch pyflakes warnings - start will be set when step is set
1391 start
= '(Never used)'
1392 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
1393 if step
is not None:
1394 if i
- prev
== step
:
1396 yield _genslice(start
, prev
, step
)
1399 if i
- prev
in [-1, 1]:
1404 yield 's[%d]' % prev
1408 yield _genslice(start
, i
, step
)
1410 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1411 cache_res
= func(test_string
)
1412 cache_spec
= [ord(c
) for c
in cache_res
]
1413 expr_code
= ' + '.join(gen_sig_code(cache_spec
))
1414 signature_id_tuple
= '(%s)' % (
1415 ', '.join(compat_str(len(p
)) for p
in example_sig
.split('.')))
1416 code
= ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1417 ' return %s\n') % (signature_id_tuple
, expr_code
)
1418 self
.to_screen('Extracted signature function:\n' + code
)
1420 def _parse_sig_js(self
, jscode
):
1421 funcname
= self
._search
_regex
(
1422 (r
'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1423 r
'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1424 r
'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1425 r
'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1426 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+\)',
1427 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*\)',
1428 r
'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1430 r
'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1431 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1432 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1433 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1434 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1435 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1436 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1437 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1438 jscode, 'Initial JS player signature function name
', group='sig
')
1440 jsi = JSInterpreter(jscode)
1441 initial_function = jsi.extract_function(funcname)
1442 return lambda s: initial_function([s])
1444 def _decrypt_signature(self, s, video_id, player_url):
1445 """Turn the encrypted s field into a working signature"""
1447 if player_url is None:
1448 raise ExtractorError('Cannot decrypt signature without player_url
')
1450 if player_url.startswith('//'):
1451 player_url = 'https
:' + player_url
1452 elif not re.match(r'https?
://', player_url):
1453 player_url = compat_urlparse.urljoin(
1454 'https
://www
.youtube
.com
', player_url)
1456 player_id = (player_url, self._signature_cache_id(s))
1457 if player_id not in self._player_cache:
1458 func = self._extract_signature_function(
1459 video_id, player_url, s
1461 self._player_cache[player_id] = func
1462 func = self._player_cache[player_id]
1463 if self.get_param('youtube_print_sig_code
'):
1464 self._print_sig_code(func, s)
1466 except Exception as e:
1467 tb = traceback.format_exc()
1468 raise ExtractorError(
1469 'Signature extraction failed
: ' + tb, cause=e)
1471 def _mark_watched(self, video_id, player_response):
1472 playback_url = url_or_none(try_get(
1474 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1475 if not playback_url:
1477 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1478 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1480 # cpn generation algorithm is reverse engineered from base.js.
1481 # In fact it works even with dummy cpn.
1482 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1483 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1489 playback_url = compat_urlparse.urlunparse(
1490 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1492 self._download_webpage(
1493 playback_url, video_id, 'Marking watched
',
1494 'Unable to mark watched
', fatal=False)
1497 def _extract_urls(webpage):
1498 # Embedded YouTube player
1500 unescapeHTML(mobj.group('url
'))
1501 for mobj in re.finditer(r'''(?x)
1511 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1512 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1515 # lazyYT YouTube embed
1516 entries.extend(list(map(
1518 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1520 # Wordpress "YouTube Video Importer
" plugin
1521 matches = re.findall(r'''(?x)<div[^>]+
1522 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1523 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1524 entries.extend(m[-1] for m in matches)
1529 def _extract_url(webpage):
1530 urls = YoutubeIE._extract_urls(webpage)
1531 return urls[0] if urls else None
1534 def extract_id(cls, url):
1535 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1537 raise ExtractorError('Invalid URL: %s' % url)
1538 video_id = mobj.group(2)
1541 def _extract_chapters_from_json(self, data, video_id, duration):
1542 chapters_list = try_get(
1544 lambda x: x['playerOverlays']
1545 ['playerOverlayRenderer']
1546 ['decoratedPlayerBarRenderer']
1547 ['decoratedPlayerBarRenderer']
1549 ['chapteredPlayerBarRenderer']
1552 if not chapters_list:
1555 def chapter_time(chapter):
1556 return float_or_none(
1559 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1563 for next_num, chapter in enumerate(chapters_list, start=1):
1564 start_time = chapter_time(chapter)
1565 if start_time is None:
1567 end_time = (chapter_time(chapters_list[next_num])
1568 if next_num < len(chapters_list) else duration)
1569 if end_time is None:
1572 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1575 'start_time': start_time,
1576 'end_time': end_time,
1581 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1582 return self._parse_json(self._search_regex(
1583 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1584 regex), webpage, name, default='{}'), video_id, fatal=False)
1587 def parse_time_text(time_text):
1589 Parse the comment time text
1590 time_text is in the format 'X units ago (edited)'
1592 time_text_split = time_text.split(' ')
1593 if len(time_text_split) >= 3:
1594 return datetime_from_str('now-%s%s' % (time_text_split[0], time_text_split[1]), precision='auto')
1597 def _join_text_entries(runs):
1600 if not isinstance(run, dict):
1602 sub_text = try_get(run, lambda x: x['text'], compat_str)
1610 def _extract_comment(self, comment_renderer, parent=None):
1611 comment_id = comment_renderer.get('commentId')
1614 comment_text_runs = try_get(comment_renderer, lambda x: x['contentText']['runs']) or []
1615 text = self._join_text_entries(comment_text_runs) or ''
1616 comment_time_text = try_get(comment_renderer, lambda x: x['publishedTimeText']['runs']) or []
1617 time_text = self._join_text_entries(comment_time_text)
1618 timestamp = calendar.timegm(self.parse_time_text(time_text).timetuple())
1619 author = try_get(comment_renderer, lambda x: x['authorText']['simpleText'], compat_str)
1620 author_id = try_get(comment_renderer,
1621 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], compat_str)
1622 votes = str_to_int(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
1623 lambda x: x['likeCount']), compat_str)) or 0
1624 author_thumbnail = try_get(comment_renderer,
1625 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], compat_str)
1627 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
1628 is_liked = try_get(comment_renderer, lambda x: x['isLiked'], bool)
1632 'timestamp': timestamp,
1633 'time_text': time_text,
1634 'like_count': votes,
1635 'is_favorited': is_liked,
1637 'author_id': author_id,
1638 'author_thumbnail': author_thumbnail,
1639 'author_is_uploader': author_is_uploader,
1640 'parent': parent or 'root'
1643 def _comment_entries(self, root_continuation_data, identity_token, account_syncid,
1644 ytcfg, session_token_list, parent=None, comment_counts=None):
1646 def extract_thread(parent_renderer):
1647 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
1649 comment_counts[2] = 0
1650 for content in contents:
1651 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
1652 comment_renderer = try_get(
1653 comment_thread_renderer, (lambda x: x['comment']['commentRenderer'], dict)) or try_get(
1654 content, (lambda x: x['commentRenderer'], dict))
1656 if not comment_renderer:
1658 comment = self._extract_comment(comment_renderer, parent)
1661 comment_counts[0] += 1
1663 # Attempt to get the replies
1664 comment_replies_renderer = try_get(
1665 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
1667 if comment_replies_renderer:
1668 comment_counts[2] += 1
1669 comment_entries_iter = self._comment_entries(
1670 comment_replies_renderer, identity_token, account_syncid, ytcfg,
1671 parent=comment.get('id'), session_token_list=session_token_list,
1672 comment_counts=comment_counts)
1674 for reply_comment in comment_entries_iter:
1677 if not comment_counts:
1678 # comment so far, est. total comments, current comment thread #
1679 comment_counts = [0, 0, 0]
1681 # TODO: Generalize the download code with TabIE
1682 context = self._extract_context(ytcfg)
1683 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
1684 continuation = YoutubeTabIE._extract_continuation(root_continuation_data) # TODO
1685 first_continuation = False
1687 first_continuation = True
1689 for page_num in itertools.count(0):
1690 if not continuation:
1692 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
1693 retries = self.get_param('extractor_retries', 3)
1697 while count < retries:
1700 self.report_warning('%s. Retrying ...' % last_error)
1703 'ctoken': continuation['ctoken'],
1708 query['action_get_comment_replies'] = 1
1710 query['action_get_comments'] = 1
1712 comment_prog_str = '(%d/%d)' % (comment_counts[0], comment_counts[1])
1714 if first_continuation:
1715 note_prefix = 'Downloading initial comment continuation page'
1717 note_prefix = ' Downloading comment reply thread %d %s' % (comment_counts[2], comment_prog_str)
1719 note_prefix = '%sDownloading comment%s page %d %s' % (
1720 ' ' if parent else '',
1721 ' replies' if parent else '',
1725 browse = self._download_json(
1726 'https://www.youtube.com/comment_service_ajax', None,
1727 '%s %s' % (note_prefix, '(retry #%d)' % count if count else ''),
1728 headers=headers, query=query,
1729 data=urlencode_postdata({
1730 'session_token': session_token_list[0]
1732 except ExtractorError as e:
1733 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404, 413):
1734 if e.cause.code == 413:
1735 self.report_warning('Assumed end of comments (received HTTP Error 413)')
1737 # Downloading page may result in intermittent 5xx HTTP error
1738 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1739 last_error = 'HTTP Error %s' % e.cause.code
1740 if e.cause.code == 404:
1741 last_error = last_error + ' (this API is probably deprecated)'
1746 session_token = try_get(browse, lambda x: x['xsrf_token'], compat_str)
1748 session_token_list[0] = session_token
1750 response = try_get(browse,
1751 (lambda x: x['response'],
1752 lambda x: x[1]['response'])) or {}
1754 if response.get('continuationContents'):
1757 # YouTube sometimes gives reload: now json if something went wrong (e.g. bad auth)
1758 if browse.get('reload'):
1759 raise ExtractorError('Invalid or missing params in continuation request', expected=False)
1761 # TODO: not tested, merged from old extractor
1762 err_msg = browse.get('externalErrorMessage')
1764 raise ExtractorError('YouTube said: %s' % err_msg, expected=False)
1766 # Youtube sometimes sends incomplete data
1767 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1768 last_error = 'Incomplete data received'
1769 if count >= retries:
1770 raise ExtractorError(last_error)
1774 visitor_data = try_get(
1776 lambda x: x['responseContext']['webResponseContextExtensionData']['ytConfigData']['visitorData'],
1777 compat_str) or visitor_data
1779 known_continuation_renderers = {
1780 'itemSectionContinuation': extract_thread,
1781 'commentRepliesContinuation': extract_thread
1784 # extract next root continuation from the results
1785 continuation_contents = try_get(
1786 response, lambda x: x['continuationContents'], dict) or {}
1788 for key, value in continuation_contents.items():
1789 if key not in known_continuation_renderers:
1791 continuation_renderer = value
1793 if first_continuation:
1794 first_continuation = False
1795 expected_comment_count = try_get(
1796 continuation_renderer,
1797 (lambda x: x['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'],
1798 lambda x: x['header']['commentsHeaderRenderer']['commentsCount']['runs'][0]['text']),
1801 if expected_comment_count:
1802 comment_counts[1] = str_to_int(expected_comment_count)
1803 self.to_screen('Downloading ~%d comments' % str_to_int(expected_comment_count))
1804 yield comment_counts[1]
1807 # 1/True for newest, 0/False for popular (default)
1808 comment_sort_index = int(True)
1809 sort_continuation_renderer = try_get(
1810 continuation_renderer,
1811 lambda x: x['header']['commentsHeaderRenderer']['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems']
1812 [comment_sort_index]['continuation']['reloadContinuationData'], dict)
1813 # If this fails, the initial continuation page
1814 # starts off with popular anyways.
1815 if sort_continuation_renderer:
1816 continuation = YoutubeTabIE._build_continuation_query(
1817 continuation=sort_continuation_renderer.get('continuation'),
1818 ctp=sort_continuation_renderer.get('clickTrackingParams'))
1819 self.to_screen('Sorting comments by %s' % ('popular' if comment_sort_index == 0 else 'newest'))
1822 for entry in known_continuation_renderers[key](continuation_renderer):
1825 continuation = YoutubeTabIE._extract_continuation(continuation_renderer) # TODO
1828 def _extract_comments(self, ytcfg, video_id, contents, webpage, xsrf_token):
1829 """Entry for comment extraction"""
1831 known_entry_comment_renderers = (
1832 'itemSectionRenderer',
1835 for entry in contents:
1836 for key, renderer in entry.items():
1837 if key not in known_entry_comment_renderers:
1840 comment_iter = self._comment_entries(
1842 identity_token=self._extract_identity_token(webpage, item_id=video_id),
1843 account_syncid=self._extract_account_syncid(ytcfg),
1845 session_token_list=[xsrf_token])
1847 for comment in comment_iter:
1848 if isinstance(comment, int):
1849 estimated_total = comment
1851 comments.append(comment)
1853 self.to_screen('Downloaded %d/%d comments' % (len(comments), estimated_total))
1855 'comments': comments,
1856 'comment_count': len(comments),
1859 def _real_extract(self, url):
1860 url, smuggled_data = unsmuggle_url(url, {})
1861 video_id = self._match_id(url)
1863 is_music_url = smuggled_data.get('is_music_url') or self.is_music_url(url)
1865 base_url = self.http_scheme() + '//www.youtube.com/'
1866 webpage_url = base_url + 'watch?v=' + video_id
1867 webpage = self._download_webpage(
1868 webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1873 text = x.get('simpleText')
1874 if text and isinstance(text, compat_str):
1876 runs = x.get('runs')
1877 if not isinstance(runs, list):
1879 return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1881 ytm_streaming_data = {}
1883 # we are forcing to use parse_json because 141 only appeared in get_video_info.
1884 # el, c, cver, cplayer field required for 141(aac 256kbps) codec
1885 # maybe paramter of youtube music player?
1886 ytm_player_response = self._parse_json(try_get(compat_parse_qs(
1887 self._download_webpage(
1888 base_url + 'get_video_info', video_id,
1889 'Fetching youtube-music info webpage',
1890 'unable to download youtube-music info webpage', query={
1891 'video_id': video_id,
1892 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1896 'cplayer': 'UNIPLAYER'
1898 lambda x: x['player_response'][0],
1899 compat_str) or '{}', video_id)
1900 ytm_streaming_data = ytm_player_response.get('streamingData') or {}
1902 player_response = None
1904 player_response = self._extract_yt_initial_variable(
1905 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1906 video_id, 'initial player response')
1908 ytcfg = self._extract_ytcfg(video_id, webpage)
1909 if not player_response:
1910 player_response = self._call_api(
1911 'player', {'videoId': video_id}, video_id, api_key=self._extract_api_key(ytcfg))
1913 playability_status = player_response.get('playabilityStatus') or {}
1914 if playability_status.get('reason') == 'Sign in to confirm your age':
1915 pr = self._parse_json(try_get(compat_parse_qs(
1916 self._download_webpage(
1917 base_url + 'get_video_info', video_id,
1918 'Refetching age-gated info webpage',
1919 'unable to download video info webpage', query={
1920 'video_id': video_id,
1921 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1923 lambda x: x['player_response'][0],
1924 compat_str) or '{}', video_id)
1926 player_response = pr
1928 trailer_video_id = try_get(
1930 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1932 if trailer_video_id:
1933 return self.url_result(
1934 trailer_video_id, self.ie_key(), trailer_video_id)
1937 lambda x: self._html_search_meta(x, webpage, default=None)) \
1938 if webpage else lambda x: None
1940 video_details = player_response.get('videoDetails') or {}
1941 microformat = try_get(
1943 lambda x: x['microformat']['playerMicroformatRenderer'],
1945 video_title = video_details.get('title') \
1946 or get_text(microformat.get('title')) \
1947 or search_meta(['og:title', 'twitter:title', 'title'])
1948 video_description = video_details.get('shortDescription')
1950 if not smuggled_data.get('force_singlefeed', False):
1951 if not self.get_param('noplaylist'):
1952 multifeed_metadata_list = try_get(
1954 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1956 if multifeed_metadata_list:
1959 for feed in multifeed_metadata_list.split(','):
1960 # Unquote should take place before split on comma (,) since textual
1961 # fields may contain comma as well (see
1962 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1963 feed_data = compat_parse_qs(
1964 compat_urllib_parse_unquote_plus(feed))
1966 def feed_entry(name):
1968 feed_data, lambda x: x[name][0], compat_str)
1970 feed_id = feed_entry('id')
1973 feed_title = feed_entry('title')
1976 title += ' (%s)' % feed_title
1978 '_type': 'url_transparent',
1979 'ie_key': 'Youtube',
1981 base_url + 'watch?v=' + feed_data['id'][0],
1982 {'force_singlefeed': True}),
1985 feed_ids.append(feed_id)
1987 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1988 % (', '.join(feed_ids), video_id))
1989 return self.playlist_result(
1990 entries, video_id, video_title, video_description)
1992 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1994 formats, itags, stream_ids = [], [], []
1997 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1999 streaming_data = player_response.get('streamingData') or {}
2000 streaming_formats = streaming_data.get('formats') or []
2001 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
2002 streaming_formats.extend(ytm_streaming_data.get('formats') or [])
2003 streaming_formats.extend(ytm_streaming_data.get('adaptiveFormats') or [])
2005 for fmt in streaming_formats:
2006 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
2009 itag = str_or_none(fmt.get('itag'))
2010 audio_track = fmt.get('audioTrack') or {}
2011 stream_id = '%s.%s' % (itag or '', audio_track.get('id', ''))
2012 if stream_id in stream_ids:
2015 quality = fmt.get('quality')
2016 if itag and quality:
2017 itag_qualities[itag] = quality
2018 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
2019 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
2020 # number of fragment that would subsequently requested with (`&sq=N`)
2021 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
2024 fmt_url = fmt.get('url')
2026 sc = compat_parse_qs(fmt.get('signatureCipher'))
2027 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
2028 encrypted_sig = try_get(sc, lambda x: x['s'][0])
2029 if not (sc and fmt_url and encrypted_sig):
2034 player_url = self._search_regex(
2035 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
2036 webpage, 'player URL', fatal=False)
2039 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
2040 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
2041 fmt_url += '&' + sp + '=' + signature
2045 stream_ids.append(stream_id)
2047 tbr = float_or_none(
2048 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
2050 'asr': int_or_none(fmt.get('audioSampleRate')),
2051 'filesize': int_or_none(fmt.get('contentLength')),
2053 'format_note': audio_track.get('displayName') or fmt.get('qualityLabel') or quality,
2054 'fps': int_or_none(fmt.get('fps')),
2055 'height': int_or_none(fmt.get('height')),
2056 'quality': q(quality),
2059 'width': fmt.get('width'),
2060 'language': audio_track.get('id', '').split('.')[0],
2062 mimetype = fmt.get('mimeType')
2065 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
2067 dct['ext'] = mimetype2ext(mobj.group(1))
2068 dct.update(parse_codecs(mobj.group(2)))
2069 no_audio = dct.get('acodec') == 'none'
2070 no_video = dct.get('vcodec') == 'none'
2075 if no_audio or no_video:
2076 dct['downloader_options'] = {
2077 # Youtube throttles chunks >~10M
2078 'http_chunk_size': 10485760,
2081 dct['container'] = dct['ext'] + '_dash'
2084 for sd in (streaming_data, ytm_streaming_data):
2085 hls_manifest_url = sd.get('hlsManifestUrl')
2086 if hls_manifest_url:
2087 for f in self._extract_m3u8_formats(
2088 hls_manifest_url, video_id, 'mp4', fatal=False):
2089 itag = self._search_regex(
2090 r'/itag/(\d+)', f['url'], 'itag', default=None)
2092 f['format_id'] = itag
2095 if self.get_param('youtube_include_dash_manifest', True):
2096 for sd in (streaming_data, ytm_streaming_data):
2097 dash_manifest_url = sd.get('dashManifestUrl')
2098 if dash_manifest_url:
2099 for f in self._extract_mpd_formats(
2100 dash_manifest_url, video_id, fatal=False):
2101 itag = f['format_id']
2104 if itag in itag_qualities:
2105 # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
2106 # but kept to maintain feature parity (and code similarity) with youtube-dl
2107 # Remove if this causes any issues with sorting in future
2108 f['quality'] = q(itag_qualities[itag])
2109 filesize = int_or_none(self._search_regex(
2110 r'/clen/(\d+)', f.get('fragment_base_url')
2111 or f['url'], 'file size', default=None))
2113 f['filesize'] = filesize
2117 if not self.get_param('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
2118 self.raise_no_formats(
2119 'This video is DRM protected.', expected=True)
2122 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
2124 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
2125 subreason = pemr.get('subreason')
2127 subreason = clean_html(get_text(subreason))
2128 if subreason == 'The uploader has not made this video available in your country.':
2129 countries = microformat.get('availableCountries')
2131 regions_allowed = search_meta('regionsAllowed')
2132 countries = regions_allowed.split(',') if regions_allowed else None
2133 self.raise_geo_restricted(subreason, countries, metadata_available=True)
2134 reason += '\n' + subreason
2136 self.raise_no_formats(reason, expected=True)
2138 self._sort_formats(formats)
2140 keywords = video_details.get('keywords') or []
2141 if not keywords and webpage:
2143 unescapeHTML(m.group('content'))
2144 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
2145 for keyword in keywords:
2146 if keyword.startswith('yt:stretch='):
2147 mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
2149 # NB: float is intentional for forcing float division
2150 w, h = (float(v) for v in mobj.groups())
2154 if f.get('vcodec') != 'none':
2155 f['stretched_ratio'] = ratio
2159 for container in (video_details, microformat):
2160 for thumbnail in (try_get(
2162 lambda x: x['thumbnail']['thumbnails'], list) or []):
2163 thumbnail_url = thumbnail.get('url')
2164 if not thumbnail_url:
2166 # Sometimes youtube gives a wrong thumbnail URL. See:
2167 # https://github.com/yt-dlp/yt-dlp/issues/233
2168 # https://github.com/ytdl-org/youtube-dl/issues/28023
2169 if 'maxresdefault' in thumbnail_url:
2170 thumbnail_url = thumbnail_url.split('?')[0]
2172 'height': int_or_none(thumbnail.get('height')),
2173 'url': thumbnail_url,
2174 'width': int_or_none(thumbnail.get('width')),
2179 thumbnail = search_meta(['og:image', 'twitter:image'])
2181 thumbnails = [{'url': thumbnail}]
2183 category = microformat.get('category') or search_meta('genre')
2184 channel_id = video_details.get('channelId') \
2185 or microformat.get('externalChannelId') \
2186 or search_meta('channelId')
2187 duration = int_or_none(
2188 video_details.get('lengthSeconds')
2189 or microformat.get('lengthSeconds')) \
2190 or parse_duration(search_meta('duration'))
2191 is_live = video_details.get('isLive')
2192 owner_profile_url = microformat.get('ownerProfileUrl')
2196 'title': self._live_title(video_title) if is_live else video_title,
2198 'thumbnails': thumbnails,
2199 'description': video_description,
2200 'upload_date': unified_strdate(
2201 microformat.get('uploadDate')
2202 or search_meta('uploadDate')),
2203 'uploader': video_details['author'],
2204 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
2205 'uploader_url': owner_profile_url,
2206 'channel_id': channel_id,
2207 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
2208 'duration': duration,
2209 'view_count': int_or_none(
2210 video_details.get('viewCount')
2211 or microformat.get('viewCount')
2212 or search_meta('interactionCount')),
2213 'average_rating': float_or_none(video_details.get('averageRating')),
2214 'age_limit': 18 if (
2215 microformat.get('isFamilySafe') is False
2216 or search_meta('isFamilyFriendly') == 'false'
2217 or search_meta('og:restrictions:age') == '18+') else 0,
2218 'webpage_url': webpage_url,
2219 'categories': [category] if category else None,
2222 'playable_in_embed': playability_status.get('playableInEmbed'),
2223 'was_live': video_details.get('isLiveContent'),
2228 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
2231 def process_language(container, base_url, lang_code, sub_name, query):
2232 lang_subs = container.setdefault(lang_code, [])
2233 for fmt in self._SUBTITLE_FORMATS:
2239 'url': update_url_query(base_url, query),
2243 for caption_track in (pctr.get('captionTracks') or []):
2244 base_url = caption_track.get('baseUrl')
2247 if caption_track.get('kind') != 'asr':
2249 remove_start(caption_track.get('vssId') or '', '.').replace('.', '-')
2250 or caption_track.get('languageCode'))
2254 subtitles, base_url, lang_code,
2255 try_get(caption_track, lambda x: x.get('name').get('simpleText')),
2258 automatic_captions = {}
2259 for translation_language in (pctr.get('translationLanguages') or []):
2260 translation_language_code = translation_language.get('languageCode')
2261 if not translation_language_code:
2264 automatic_captions, base_url, translation_language_code,
2265 try_get(translation_language, lambda x: x['languageName']['simpleText']),
2266 {'tlang': translation_language_code})
2267 info['automatic_captions'] = automatic_captions
2268 info['subtitles'] = subtitles
2270 parsed_url = compat_urllib_parse_urlparse(url)
2271 for component in [parsed_url.fragment, parsed_url.query]:
2272 query = compat_parse_qs(component)
2273 for k, v in query.items():
2274 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
2276 if d_k not in info and k in s_ks:
2277 info[d_k] = parse_duration(query[k][0])
2279 # Youtube Music Auto-generated description
2280 if video_description:
2281 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)
2283 release_year = mobj.group('release_year')
2284 release_date = mobj.group('release_date')
2286 release_date = release_date.replace('-', '')
2287 if not release_year:
2288 release_year = release_date[:4]
2290 'album': mobj.group('album'.strip()),
2291 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
2292 'track': mobj.group('track').strip(),
2293 'release_date': release_date,
2294 'release_year': int_or_none(release_year),
2299 initial_data = self._extract_yt_initial_variable(
2300 webpage, self._YT_INITIAL_DATA_RE, video_id,
2302 if not initial_data:
2303 initial_data = self._call_api(
2304 'next', {'videoId': video_id}, video_id, fatal=False, api_key=self._extract_api_key(ytcfg))
2308 # This will error if there is no livechat
2309 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
2310 info['subtitles']['live_chat'] = [{
2311 'url': 'https://www.youtube.com/watch?v=%s' % video_id, # url is needed to set cookies
2312 'video_id': video_id,
2314 'protocol': 'youtube_live_chat_replay',
2316 except (KeyError, IndexError, TypeError):
2320 chapters = self._extract_chapters_from_json(
2321 initial_data, video_id, duration)
2323 for engagment_pannel in (initial_data.get('engagementPanels') or []):
2325 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
2330 def chapter_time(mmlir):
2331 return parse_duration(
2332 get_text(mmlir.get('timeDescription')))
2335 for next_num, content in enumerate(contents, start=1):
2336 mmlir = content.get('macroMarkersListItemRenderer') or {}
2337 start_time = chapter_time(mmlir)
2338 end_time = chapter_time(try_get(
2339 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
2340 if next_num < len(contents) else duration
2341 if start_time is None or end_time is None:
2344 'start_time': start_time,
2345 'end_time': end_time,
2346 'title': get_text(mmlir.get('title')),
2351 info['chapters'] = chapters
2355 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
2357 for content in contents:
2358 vpir = content.get('videoPrimaryInfoRenderer')
2360 stl = vpir.get('superTitleLink')
2365 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
2366 info['location'] = stl
2368 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
2371 'series': mobj.group(1),
2372 'season_number': int(mobj.group(2)),
2373 'episode_number': int(mobj.group(3)),
2375 for tlb in (try_get(
2377 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
2379 tbr = tlb.get('toggleButtonRenderer') or {}
2380 for getter, regex in [(
2381 lambda x: x['defaultText']['accessibility']['accessibilityData'],
2382 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
2383 lambda x: x['accessibility'],
2384 lambda x: x['accessibilityData']['accessibilityData'],
2385 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
2386 label = (try_get(tbr, getter, dict) or {}).get('label')
2388 mobj = re.match(regex, label)
2390 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
2392 sbr_tooltip = try_get(
2393 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
2395 like_count, dislike_count = sbr_tooltip.split(' / ')
2397 'like_count': str_to_int(like_count),
2398 'dislike_count': str_to_int(dislike_count),
2400 vsir = content.get('videoSecondaryInfoRenderer')
2402 info['channel'] = get_text(try_get(
2404 lambda x: x['owner']['videoOwnerRenderer']['title'],
2408 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
2410 multiple_songs = False
2412 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
2413 multiple_songs = True
2416 mrr = row.get('metadataRowRenderer') or {}
2417 mrr_title = mrr.get('title')
2420 mrr_title = get_text(mrr['title'])
2421 mrr_contents_text = get_text(mrr['contents'][0])
2422 if mrr_title == 'License':
2423 info['license'] = mrr_contents_text
2424 elif not multiple_songs:
2425 if mrr_title == 'Album':
2426 info['album'] = mrr_contents_text
2427 elif mrr_title == 'Artist':
2428 info['artist'] = mrr_contents_text
2429 elif mrr_title == 'Song':
2430 info['track'] = mrr_contents_text
2433 'channel': 'uploader',
2434 'channel_id': 'uploader_id',
2435 'channel_url': 'uploader_url',
2437 for to, frm in fallbacks.items():
2438 if not info.get(to):
2439 info[to] = info.get(frm)
2441 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
2446 is_private = bool_or_none(video_details.get('isPrivate'))
2447 is_unlisted = bool_or_none(microformat.get('isUnlisted'))
2448 is_membersonly = None
2450 if initial_data and is_private is not None:
2451 is_membersonly = False
2453 contents = try_get(initial_data, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'], list)
2454 for content in contents or []:
2455 badges = try_get(content, lambda x: x['videoPrimaryInfoRenderer']['badges'], list)
2456 for badge in badges or []:
2457 label = try_get(badge, lambda x: x['metadataBadgeRenderer']['label']) or ''
2458 if label.lower() == 'members only':
2459 is_membersonly = True
2461 elif label.lower() == 'premium':
2464 if is_membersonly or is_premium:
2467 # TODO: Add this for playlists
2468 info['availability'] = self._availability(
2469 is_private=is_private,
2470 needs_premium=is_premium,
2471 needs_subscription=is_membersonly,
2472 needs_auth=info['age_limit'] >= 18,
2473 is_unlisted=None if is_private is None else is_unlisted)
2475 # get xsrf for annotations or comments
2476 get_annotations = self.get_param('writeannotations', False)
2477 get_comments = self.get_param('getcomments', False)
2478 if get_annotations or get_comments:
2480 ytcfg = self._extract_ytcfg(video_id, webpage)
2482 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2484 xsrf_token = self._search_regex(
2485 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2486 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2490 invideo_url = try_get(
2491 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2492 if xsrf_token and invideo_url:
2493 xsrf_field_name = None
2495 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2496 if not xsrf_field_name:
2497 xsrf_field_name = self._search_regex(
2498 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2499 webpage, 'xsrf field name',
2500 group='xsrf_field_name', default='session_token')
2501 info['annotations'] = self._download_webpage(
2502 self._proto_relative_url(invideo_url),
2503 video_id, note='Downloading annotations',
2504 errnote='Unable to download video annotations', fatal=False,
2505 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2508 info['__post_extractor'] = lambda: self._extract_comments(ytcfg, video_id, contents, webpage, xsrf_token)
2510 self.mark_watched(video_id, player_response)
2515 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2516 IE_DESC = 'YouTube.com tab'
2517 _VALID_URL = r'''(?x
)
2521 youtube(?
:kids
)?\
.com|
2525 (?
:channel|c|user
)/|
2528 (?
:playlist|watch
)\?.*?
\blist
=
2530 (?
!(?
:%s)\b) # Direct URLs
2533 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2534 IE_NAME = 'youtube:tab'
2537 'note': 'playlists, multipage',
2538 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2539 'playlist_mincount': 94,
2541 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2542 'title': 'Игорь Клейнер - Playlists',
2543 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2544 'uploader': 'Игорь Клейнер',
2545 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2548 'note': 'playlists, multipage, different order',
2549 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2550 'playlist_mincount': 94,
2552 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2553 'title': 'Игорь Клейнер - Playlists',
2554 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2555 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2556 'uploader': 'Игорь Клейнер',
2559 'note': 'playlists, series',
2560 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
2561 'playlist_mincount': 5,
2563 'id': 'UCYO_jab_esuFRV4b17AJtAw',
2564 'title': '3Blue1Brown - Playlists',
2565 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2566 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
2567 'uploader': '3Blue1Brown',
2570 'note': 'playlists, singlepage',
2571 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2572 'playlist_mincount': 4,
2574 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2575 'title': 'ThirstForScience - Playlists',
2576 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2577 'uploader': 'ThirstForScience',
2578 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2581 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2582 'only_matching': True,
2584 'note': 'basic, single video playlist',
2585 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2587 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2588 'uploader': 'Sergey M.',
2589 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2590 'title': 'youtube-dl public playlist',
2592 'playlist_count': 1,
2594 'note': 'empty playlist',
2595 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2597 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2598 'uploader': 'Sergey M.',
2599 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2600 'title': 'youtube-dl empty playlist',
2602 'playlist_count': 0,
2605 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2607 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2608 'title': 'lex will - Home',
2609 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2610 'uploader': 'lex will',
2611 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2613 'playlist_mincount': 2,
2615 'note': 'Videos tab',
2616 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2618 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2619 'title': 'lex will - Videos',
2620 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2621 'uploader': 'lex will',
2622 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2624 'playlist_mincount': 975,
2626 'note': 'Videos tab, sorted by popular',
2627 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2629 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2630 'title': 'lex will - Videos',
2631 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2632 'uploader': 'lex will',
2633 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2635 'playlist_mincount': 199,
2637 'note': 'Playlists tab',
2638 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2640 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2641 'title': 'lex will - Playlists',
2642 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2643 'uploader': 'lex will',
2644 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2646 'playlist_mincount': 17,
2648 'note': 'Community tab',
2649 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2651 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2652 'title': 'lex will - Community',
2653 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2654 'uploader': 'lex will',
2655 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2657 'playlist_mincount': 18,
2659 'note': 'Channels tab',
2660 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2662 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2663 'title': 'lex will - Channels',
2664 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2665 'uploader': 'lex will',
2666 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2668 'playlist_mincount': 12,
2670 'note': 'Search tab',
2671 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
2672 'playlist_mincount': 40,
2674 'id': 'UCYO_jab_esuFRV4b17AJtAw',
2675 'title': '3Blue1Brown - Search - linear algebra',
2676 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2677 'uploader': '3Blue1Brown',
2678 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
2681 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2682 'only_matching': True,
2684 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2685 'only_matching': True,
2687 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2688 'only_matching': True,
2690 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2691 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2693 'title': '29C3: Not my department',
2694 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2695 'uploader': 'Christiaan008',
2696 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2697 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2699 'playlist_count': 96,
2701 'note': 'Large playlist',
2702 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2704 'title': 'Uploads from Cauchemar',
2705 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2706 'uploader': 'Cauchemar',
2707 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2709 'playlist_mincount': 1123,
2711 'note': 'even larger playlist, 8832 videos',
2712 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2713 'only_matching': True,
2715 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2716 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2718 'title': 'Uploads from Interstellar Movie',
2719 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2720 'uploader': 'Interstellar Movie',
2721 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2723 'playlist_mincount': 21,
2725 'note': 'Playlist with "show unavailable videos" button',
2726 'url': 'https://www.youtube.com/playlist?list=UUTYLiWFZy8xtPwxFwX9rV7Q',
2728 'title': 'Uploads from Phim Siêu Nhân Nhật Bản',
2729 'id': 'UUTYLiWFZy8xtPwxFwX9rV7Q',
2730 'uploader': 'Phim Siêu Nhân Nhật Bản',
2731 'uploader_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
2733 'playlist_mincount': 200,
2735 'note': 'Playlist with unavailable videos in page 7',
2736 'url': 'https://www.youtube.com/playlist?list=UU8l9frL61Yl5KFOl87nIm2w',
2738 'title': 'Uploads from BlankTV',
2739 'id': 'UU8l9frL61Yl5KFOl87nIm2w',
2740 'uploader': 'BlankTV',
2741 'uploader_id': 'UC8l9frL61Yl5KFOl87nIm2w',
2743 'playlist_mincount': 1000,
2745 'note': 'https://github.com/ytdl-org/youtube-dl/issues/21844',
2746 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2748 'title': 'Data Analysis with Dr Mike Pound',
2749 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2750 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2751 'uploader': 'Computerphile',
2752 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2754 'playlist_mincount': 11,
2756 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2757 'only_matching': True,
2759 'note': 'Playlist URL that does not actually serve a playlist',
2760 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2762 'id': 'FqZTN594JQw',
2764 'title': "Smiley's People 01 detective, Adventure Series, Action",
2765 'uploader': 'STREEM',
2766 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2767 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2768 'upload_date': '20150526',
2769 'license': 'Standard YouTube License',
2770 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2771 'categories': ['People & Blogs'],
2775 'dislike_count': int,
2778 'skip_download': True,
2780 'skip': 'This video is not available.',
2781 'add_ie': [YoutubeIE.ie_key()],
2783 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2784 'only_matching': True,
2786 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2787 'only_matching': True,
2789 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2791 'id': 'X1whbWASnNQ', # This will keep changing
2793 'title': compat_str,
2794 'uploader': 'Sky News',
2795 'uploader_id': 'skynews',
2796 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2797 'upload_date': r're:\d{8}',
2798 'description': compat_str,
2799 'categories': ['News & Politics'],
2802 'dislike_count': int,
2805 'skip_download': True,
2807 'expected_warnings': ['Downloading just video ', 'Ignoring subtitle tracks found in '],
2809 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2811 'id': 'a48o2S1cPoo',
2813 'title': 'The Young Turks - Live Main Show',
2814 'uploader': 'The Young Turks',
2815 'uploader_id': 'TheYoungTurks',
2816 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2817 'upload_date': '20150715',
2818 'license': 'Standard YouTube License',
2819 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2820 'categories': ['News & Politics'],
2821 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2823 'dislike_count': int,
2826 'skip_download': True,
2828 'only_matching': True,
2830 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2831 'only_matching': True,
2833 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2834 'only_matching': True,
2836 'url': 'https://www.youtube.com/feed/trending',
2837 'only_matching': True,
2839 'url': 'https://www.youtube.com/feed/library',
2840 'only_matching': True,
2842 'url': 'https://www.youtube.com/feed/history',
2843 'only_matching': True,
2845 'url': 'https://www.youtube.com/feed/subscriptions',
2846 'only_matching': True,
2848 'url': 'https://www.youtube.com/feed/watch_later',
2849 'only_matching': True,
2851 'note': 'Recommended - redirects to home page',
2852 'url': 'https://www.youtube.com/feed/recommended',
2853 'only_matching': True,
2855 'note': 'inline playlist with not always working continuations',
2856 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2857 'only_matching': True,
2859 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2860 'only_matching': True,
2862 'url': 'https://www.youtube.com/course',
2863 'only_matching': True,
2865 'url': 'https://www.youtube.com/zsecurity',
2866 'only_matching': True,
2868 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2869 'only_matching': True,
2871 'url': 'https://www.youtube.com/TheYoungTurks/live',
2872 'only_matching': True,
2874 'url': 'https://www.youtube.com/hashtag/cctv9',
2879 'playlist_mincount': 350,
2881 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
2882 'only_matching': True,
2884 'note': 'Requires Premium: should request additional YTM-info webpage (and have format 141) for videos in playlist',
2885 'url': 'https://music.youtube.com/playlist?list=PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
2886 'only_matching': True
2890 def suitable(cls, url):
2891 return False if YoutubeIE.suitable(url) else super(
2892 YoutubeTabIE, cls).suitable(url)
2894 def _extract_channel_id(self, webpage):
2895 channel_id = self._html_search_meta(
2896 'channelId', webpage, 'channel id', default=None)
2899 channel_url = self._html_search_meta(
2900 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2901 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2902 'twitter:app:url:googleplay'), webpage, 'channel url')
2903 return self._search_regex(
2904 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2905 channel_url, 'channel id')
2908 def _extract_basic_item_renderer(item):
2909 # Modified from _extract_grid_item_renderer
2910 known_basic_renderers = (
2911 'playlistRenderer', 'videoRenderer', 'channelRenderer', 'showRenderer'
2913 for key, renderer in item.items():
2914 if not isinstance(renderer, dict):
2916 elif key in known_basic_renderers:
2918 elif key.startswith('grid') and key.endswith('Renderer'):
2921 def _grid_entries(self, grid_renderer):
2922 for item in grid_renderer['items']:
2923 if not isinstance(item, dict):
2925 renderer = self._extract_basic_item_renderer(item)
2926 if not isinstance(renderer, dict):
2929 renderer, (lambda x: x['title']['runs'][0]['text'],
2930 lambda x: x['title']['simpleText']), compat_str)
2932 playlist_id = renderer.get('playlistId')
2934 yield self.url_result(
2935 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2936 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2940 video_id = renderer.get('videoId')
2942 yield self._extract_video(renderer)
2945 channel_id = renderer.get('channelId')
2948 renderer, lambda x: x['title']['simpleText'], compat_str)
2949 yield self.url_result(
2950 'https://www.youtube.com/channel/%s' % channel_id,
2951 ie=YoutubeTabIE.ie_key(), video_title=title)
2953 # generic endpoint URL support
2954 ep_url = urljoin('https://www.youtube.com/', try_get(
2955 renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
2958 for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
2959 if ie.suitable(ep_url):
2960 yield self.url_result(
2961 ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
2964 def _shelf_entries_from_content(self, shelf_renderer):
2965 content = shelf_renderer.get('content')
2966 if not isinstance(content, dict):
2968 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
2970 # TODO: add support for nested playlists so each shelf is processed
2971 # as separate playlist
2972 # TODO: this includes only first N items
2973 for entry in self._grid_entries(renderer):
2975 renderer = content.get('horizontalListRenderer')
2980 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2982 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2984 shelf_url = urljoin('https://www.youtube.com', ep)
2986 # Skipping links to another channels, note that checking for
2987 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2989 if skip_channels and '/channels?' in shelf_url:
2992 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2993 yield self.url_result(shelf_url, video_title=title)
2994 # Shelf may not contain shelf URL, fallback to extraction from content
2995 for entry in self._shelf_entries_from_content(shelf_renderer):
2998 def _playlist_entries(self, video_list_renderer):
2999 for content in video_list_renderer['contents']:
3000 if not isinstance(content, dict):
3002 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
3003 if not isinstance(renderer, dict):
3005 video_id = renderer.get('videoId')
3008 yield self._extract_video(renderer)
3010 def _rich_entries(self, rich_grid_renderer):
3012 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
3013 video_id = renderer.get('videoId')
3016 yield self._extract_video(renderer)
3018 def _video_entry(self, video_renderer):
3019 video_id = video_renderer.get('videoId')
3021 return self._extract_video(video_renderer)
3023 def _post_thread_entries(self, post_thread_renderer):
3024 post_renderer = try_get(
3025 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
3026 if not post_renderer:
3029 video_renderer = try_get(
3030 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict) or {}
3031 video_id = video_renderer.get('videoId')
3033 entry = self._extract_video(video_renderer)
3036 # playlist attachment
3037 playlist_id = try_get(
3038 post_renderer, lambda x: x['backstageAttachment']['playlistRenderer']['playlistId'], compat_str)
3040 yield self.url_result(
3041 'https://www.youtube.com/playlist?list=%s' % playlist_id,
3042 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3043 # inline video links
3044 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
3046 if not isinstance(run, dict):
3049 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
3052 if not YoutubeIE.suitable(ep_url):
3054 ep_video_id = YoutubeIE._match_id(ep_url)
3055 if video_id == ep_video_id:
3057 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=ep_video_id)
3059 def _post_thread_continuation_entries(self, post_thread_continuation):
3060 contents = post_thread_continuation.get('contents')
3061 if not isinstance(contents, list):
3063 for content in contents:
3064 renderer = content.get('backstagePostThreadRenderer')
3065 if not isinstance(renderer, dict):
3067 for entry in self._post_thread_entries(renderer):
3071 def _rich_grid_entries(self
, contents
):
3072 for content
in contents
:
3073 video_renderer
= try_get(content
, lambda x
: x
['richItemRenderer']['content']['videoRenderer'], dict)
3075 entry
= self
._video
_entry
(video_renderer
)
3081 def _build_continuation_query(continuation, ctp=None):
3083 'ctoken': continuation,
3084 'continuation': continuation,
3091 def _extract_next_continuation_data(renderer):
3092 next_continuation = try_get(
3093 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
3094 if not next_continuation:
3096 continuation = next_continuation.get('continuation')
3097 if not continuation:
3099 ctp = next_continuation.get('clickTrackingParams')
3100 return YoutubeTabIE._build_continuation_query(continuation, ctp)
3103 def _extract_continuation(cls, renderer):
3104 next_continuation = cls._extract_next_continuation_data(renderer)
3105 if next_continuation:
3106 return next_continuation
3108 for key in ('contents', 'items'):
3109 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
3110 for content in contents:
3111 if not isinstance(content, dict):
3113 continuation_ep = try_get(
3114 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
3116 if not continuation_ep:
3118 continuation = try_get(
3119 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
3120 if not continuation:
3122 ctp = continuation_ep.get('clickTrackingParams')
3123 return YoutubeTabIE._build_continuation_query(continuation, ctp)
3125 def _entries(self, tab, item_id, identity_token, account_syncid, ytcfg):
3127 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
3128 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
3129 for content in contents:
3130 if not isinstance(content, dict):
3132 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
3134 renderer = content.get('richItemRenderer')
3136 for entry in self._rich_entries(renderer):
3138 continuation_list[0] = self._extract_continuation(parent_renderer)
3140 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
3141 for isr_content in isr_contents:
3142 if not isinstance(isr_content, dict):
3146 'playlistVideoListRenderer': self._playlist_entries,
3147 'gridRenderer': self._grid_entries,
3148 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
3149 'backstagePostThreadRenderer': self._post_thread_entries,
3150 'videoRenderer': lambda x: [self._video_entry(x)],
3152 for key, renderer in isr_content.items():
3153 if key not in known_renderers:
3155 for entry in known_renderers[key](renderer):
3158 continuation_list[0] = self._extract_continuation(renderer)
3161 if not continuation_list[0]:
3162 continuation_list[0] = self._extract_continuation(is_renderer)
3164 if not continuation_list[0]:
3165 continuation_list[0] = self._extract_continuation(parent_renderer)
3167 continuation_list = [None] # Python 2 doesnot support nonlocal
3168 tab_content = try_get(tab, lambda x: x['content'], dict)
3172 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
3173 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
3174 for entry in extract_entries(parent_renderer):
3176 continuation = continuation_list[0]
3177 context = self._extract_context(ytcfg)
3178 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
3180 for page_num in itertools.count(1):
3181 if not continuation:
3184 'continuation': continuation['continuation'],
3185 'clickTracking': {'clickTrackingParams': continuation['itct']}
3187 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
3188 response = self._extract_response(
3189 item_id='%s page %s' % (item_id, page_num),
3190 query=query, headers=headers, ytcfg=ytcfg,
3191 check_get_keys=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3195 visitor_data = try_get(
3196 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
3198 known_continuation_renderers = {
3199 'playlistVideoListContinuation': self._playlist_entries,
3200 'gridContinuation': self._grid_entries,
3201 'itemSectionContinuation': self._post_thread_continuation_entries,
3202 'sectionListContinuation': extract_entries, # for feeds
3204 continuation_contents = try_get(
3205 response, lambda x: x['continuationContents'], dict) or {}
3206 continuation_renderer = None
3207 for key, value in continuation_contents.items():
3208 if key not in known_continuation_renderers:
3210 continuation_renderer = value
3211 continuation_list = [None]
3212 for entry in known_continuation_renderers[key](continuation_renderer):
3214 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
3216 if continuation_renderer:
3220 'gridPlaylistRenderer': (self._grid_entries, 'items'),
3221 'gridVideoRenderer': (self._grid_entries, 'items'),
3222 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
3223 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
3224 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
3225 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents')
3227 on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3228 continuation_items = try_get(
3229 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
3230 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
3231 video_items_renderer = None
3232 for key, value in continuation_item.items():
3233 if key not in known_renderers:
3235 video_items_renderer = {known_renderers[key][1]: continuation_items}
3236 continuation_list = [None]
3237 for entry in known_renderers[key][0](video_items_renderer):
3239 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
3241 if video_items_renderer:
3246 def _extract_selected_tab(tabs):
3248 renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
3249 if renderer.get('selected') is True:
3252 raise ExtractorError('Unable to find selected tab')
3255 def _extract_uploader(data):
3257 sidebar_renderer = try_get(
3258 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3259 if sidebar_renderer:
3260 for item in sidebar_renderer:
3261 if not isinstance(item, dict):
3263 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
3264 if not isinstance(renderer, dict):
3267 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
3269 uploader['uploader'] = owner.get('text')
3270 uploader['uploader_id'] = try_get(
3271 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
3272 uploader['uploader_url'] = urljoin(
3273 'https://www.youtube.com/',
3274 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
3275 return {k: v for k, v in uploader.items() if v is not None}
3277 def _extract_from_tabs(self, item_id, webpage, data, tabs):
3278 playlist_id = title = description = channel_url = channel_name = channel_id = None
3279 thumbnails_list = tags = []
3281 selected_tab = self._extract_selected_tab(tabs)
3283 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
3285 channel_name = renderer.get('title')
3286 channel_url = renderer.get('channelUrl')
3287 channel_id = renderer.get('externalId')
3290 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
3293 title = renderer.get('title')
3294 description = renderer.get('description', '')
3295 playlist_id = channel_id
3296 tags = renderer.get('keywords', '').split()
3298 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
3301 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
3306 for t in thumbnails_list:
3307 if not isinstance(t, dict):
3309 thumbnail_url = url_or_none(t.get('url'))
3310 if not thumbnail_url:
3313 'url': thumbnail_url,
3314 'width': int_or_none(t.get('width')),
3315 'height': int_or_none(t.get('height')),
3317 if playlist_id is None:
3318 playlist_id = item_id
3321 try_get(data, lambda x: x['header']['hashtagHeaderRenderer']['hashtag']['simpleText'])
3323 title += format_field(selected_tab, 'title', ' - %s')
3324 title += format_field(selected_tab, 'expandedText', ' - %s')
3327 'playlist_id': playlist_id,
3328 'playlist_title': title,
3329 'playlist_description': description,
3330 'uploader': channel_name,
3331 'uploader_id': channel_id,
3332 'uploader_url': channel_url,
3333 'thumbnails': thumbnails,
3337 metadata.update(self._extract_uploader(data))
3339 'channel': metadata['uploader'],
3340 'channel_id': metadata['uploader_id'],
3341 'channel_url': metadata['uploader_url']})
3342 return self.playlist_result(
3344 selected_tab, playlist_id,
3345 self._extract_identity_token(webpage, item_id),
3346 self._extract_account_syncid(data),
3347 self._extract_ytcfg(item_id, webpage)),
3350 def _extract_mix_playlist(self, playlist, playlist_id, data, webpage):
3351 first_id = last_id = None
3352 ytcfg = self._extract_ytcfg(playlist_id, webpage)
3353 headers = self._generate_api_headers(
3354 ytcfg, account_syncid=self._extract_account_syncid(data),
3355 identity_token=self._extract_identity_token(webpage, item_id=playlist_id),
3356 visitor_data=try_get(self._extract_context(ytcfg), lambda x: x['client']['visitorData'], compat_str))
3357 for page_num in itertools.count(1):
3358 videos = list(self._playlist_entries(playlist))
3361 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
3362 if start >= len(videos):
3364 for video in videos[start:]:
3365 if video['id'] == first_id:
3366 self.to_screen('First video %s found again; Assuming end of Mix' % first_id)
3369 first_id = first_id or videos[0]['id']
3370 last_id = videos[-1]['id']
3371 watch_endpoint = try_get(
3372 playlist, lambda x: x['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
3374 'playlistId': playlist_id,
3375 'videoId': watch_endpoint.get('videoId') or last_id,
3376 'index': watch_endpoint.get('index') or len(videos),
3377 'params': watch_endpoint.get('params') or 'OAE%3D'
3379 response = self._extract_response(
3380 item_id='%s page %d' % (playlist_id, page_num),
3384 check_get_keys='contents'
3387 response, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3389 def _extract_from_playlist(self, item_id, url, data, playlist, webpage):
3390 title = playlist.get('title') or try_get(
3391 data, lambda x: x['titleText']['simpleText'], compat_str)
3392 playlist_id = playlist.get('playlistId') or item_id
3394 # Delegating everything except mix playlists to regular tab-based playlist URL
3395 playlist_url = urljoin(url, try_get(
3396 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3398 if playlist_url and playlist_url != url:
3399 return self.url_result(
3400 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3403 return self.playlist_result(
3404 self._extract_mix_playlist(playlist, playlist_id, data, webpage),
3405 playlist_id=playlist_id, playlist_title=title)
3408 def _extract_alerts(data):
3409 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
3410 if not isinstance(alert_dict, dict):
3412 for alert in alert_dict.values():
3413 alert_type = alert.get('type')
3416 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str) or ''
3418 yield alert_type, message
3419 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
3420 message += try_get(run, lambda x: x['text'], compat_str)
3422 yield alert_type, message
3424 def _report_alerts(self, alerts, expected=True):
3427 for alert_type, alert_message in alerts:
3428 if alert_type.lower() == 'error':
3429 errors.append([alert_type, alert_message])
3431 warnings.append([alert_type, alert_message])
3433 for alert_type, alert_message in (warnings + errors[:-1]):
3434 self.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3436 raise ExtractorError('YouTube said: %s' % errors[-1][1], expected=expected)
3438 def _extract_and_report_alerts(self, data, *args, **kwargs):
3439 return self._report_alerts(self._extract_alerts(data), *args, **kwargs)
3441 def _reload_with_unavailable_videos(self, item_id, data, webpage):
3443 Get playlist with unavailable videos if the 'show unavailable videos' button exists.
3445 sidebar_renderer = try_get(
3446 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3447 if not sidebar_renderer:
3449 browse_id = params = None
3450 for item in sidebar_renderer:
3451 if not isinstance(item, dict):
3453 renderer = item.get('playlistSidebarPrimaryInfoRenderer')
3454 menu_renderer = try_get(
3455 renderer, lambda x: x['menu']['menuRenderer']['items'], list) or []
3456 for menu_item in menu_renderer:
3457 if not isinstance(menu_item, dict):
3459 nav_item_renderer = menu_item.get('menuNavigationItemRenderer')
3461 nav_item_renderer, lambda x: x['text']['simpleText'], compat_str)
3462 if not text or text.lower() != 'show unavailable videos':
3464 browse_endpoint = try_get(
3465 nav_item_renderer, lambda x: x['navigationEndpoint']['browseEndpoint'], dict) or {}
3466 browse_id = browse_endpoint.get('browseId')
3467 params = browse_endpoint.get('params')
3470 ytcfg = self._extract_ytcfg(item_id, webpage)
3471 headers = self._generate_api_headers(
3472 ytcfg, account_syncid=self._extract_account_syncid(ytcfg),
3473 identity_token=self._extract_identity_token(webpage, item_id=item_id),
3474 visitor_data=try_get(
3475 self._extract_context(ytcfg), lambda x: x['client']['visitorData'], compat_str))
3477 'params': params or 'wgYCCAA=',
3478 'browseId': browse_id or 'VL%s' % item_id
3480 return self._extract_response(
3481 item_id=item_id, headers=headers, query=query,
3482 check_get_keys='contents', fatal=False,
3483 note='Downloading API JSON with unavailable videos')
3485 def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
3486 ytcfg=None, check_get_keys=None, ep='browse', fatal=True):
3490 retries = self.get_param('extractor_retries', 3)
3491 if check_get_keys is None:
3493 while count < retries:
3496 self.report_warning('%s. Retrying ...' % last_error)
3498 response = self._call_api(
3499 ep=ep, fatal=True, headers=headers,
3500 video_id=item_id, query=query,
3501 context=self._extract_context(ytcfg),
3502 api_key=self._extract_api_key(ytcfg),
3503 note='%s%s' % (note, ' (retry #%d)' % count if count else ''))
3504 except ExtractorError as e:
3505 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
3506 # Downloading page may result in intermittent 5xx HTTP error
3507 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
3508 last_error = 'HTTP Error %s' % e.cause.code
3514 self.report_warning(error_to_compat_str(e))
3518 # Youtube may send alerts if there was an issue with the continuation page
3519 self._extract_and_report_alerts(response, expected=False)
3520 if not check_get_keys or dict_get(response, check_get_keys):
3522 # Youtube sometimes sends incomplete data
3523 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
3524 last_error = 'Incomplete data received'
3525 if count >= retries:
3527 raise ExtractorError(last_error)
3529 self.report_warning(last_error)
3533 def _extract_webpage(self, url, item_id):
3534 retries = self.get_param('extractor_retries', 3)
3536 last_error = 'Incomplete yt initial data recieved'
3537 while count < retries:
3539 # Sometimes youtube returns a webpage with incomplete ytInitialData
3540 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3542 self.report_warning('%s. Retrying ...' % last_error)
3543 webpage = self._download_webpage(
3545 'Downloading webpage%s' % (' (retry #%d)' % count if count else ''))
3546 data = self._extract_yt_initial_data(item_id, webpage)
3547 if data.get('contents') or data.get('currentVideoEndpoint'):
3549 # Extract alerts here only when there is error
3550 self._extract_and_report_alerts(data)
3551 if count >= retries:
3552 raise ExtractorError(last_error)
3553 return webpage, data
3556 def _smuggle_data(entries, data):
3557 for entry in entries:
3559 entry['url'] = smuggle_url(entry['url'], data)
3562 def _real_extract(self, url):
3563 url, smuggled_data = unsmuggle_url(url, {})
3564 if self.is_music_url(url):
3565 smuggled_data['is_music_url'] = True
3566 info_dict = self.__real_extract(url)
3567 if info_dict.get('entries'):
3568 info_dict['entries'] = self._smuggle_data(info_dict['entries'], smuggled_data)
3571 def __real_extract(self, url):
3572 item_id = self._match_id(url)
3573 url = compat_urlparse.urlunparse(
3574 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3575 compat_opts = self.get_param('compat_opts', [])
3577 # This is not matched in a channel page with a tab selected
3578 mobj = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
3579 mobj = mobj.groupdict() if mobj else {}
3580 if mobj and not mobj.get('not_channel') and 'no-youtube-channel-redirect' not in compat_opts:
3581 self.report_warning(
3582 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3583 'To download only the videos in the home page, add a "/featured" to the URL')
3584 url = '%s/videos%s' % (mobj.get('pre'), mobj.get('post') or '')
3586 # Handle both video/playlist URLs
3588 video_id = qs.get('v', [None])[0]
3589 playlist_id = qs.get('list', [None])[0]
3591 if not video_id and (mobj.get('not_channel') or '').startswith('watch'):
3593 # If there is neither video or playlist ids,
3594 # youtube redirects to home page, which is undesirable
3595 raise ExtractorError('Unable to recognize tab page')
3596 self.report_warning('A video URL was given without video ID. Trying to download playlist %s' % playlist_id)
3597 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3599 if video_id and playlist_id:
3600 if self.get_param('noplaylist'):
3601 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3602 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3603 self.to_screen('Downloading playlist %s; add --no-playlist to just download video %s' % (playlist_id, video_id))
3605 webpage, data = self._extract_webpage(url, item_id)
3607 # YouTube sometimes provides a button to reload playlist with unavailable videos.
3608 if 'no-youtube-unavailable-videos' not in compat_opts:
3609 data = self._reload_with_unavailable_videos(item_id, data, webpage) or data
3610 self._extract_and_report_alerts(data)
3613 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3615 return self._extract_from_tabs(item_id, webpage, data, tabs)
3618 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3620 return self._extract_from_playlist(item_id, url, data, playlist, webpage)
3623 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3624 compat_str) or video_id
3626 self.report_warning('Unable to recognize playlist. Downloading just video %s' % video_id)
3627 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3629 raise ExtractorError('Unable to recognize tab page')
3632 class YoutubePlaylistIE(InfoExtractor):
3633 IE_DESC = 'YouTube.com playlists'
3634 _VALID_URL = r'''(?x
)(?
:
3639 youtube(?
:kids
)?\
.com|
3644 (?P
<id>%(playlist_id)s)
3645 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3646 IE_NAME = 'youtube:playlist'
3648 'note': 'issue #673',
3649 'url': 'PLBB231211A4F62143',
3651 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3652 'id': 'PLBB231211A4F62143',
3653 'uploader': 'Wickydoo',
3654 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3656 'playlist_mincount': 29,
3658 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3660 'title': 'YDL_safe_search',
3661 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3663 'playlist_count': 2,
3664 'skip': 'This playlist is private',
3667 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3668 'playlist_count': 4,
3671 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3672 'uploader': 'milan',
3673 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3676 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3677 'playlist_mincount': 982,
3679 'title': '2018 Chinese New Singles (11/6 updated)',
3680 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3682 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3685 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3686 'only_matching': True,
3688 # music album playlist
3689 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3690 'only_matching': True,
3694 def suitable(cls, url):
3695 if YoutubeTabIE.suitable(url):
3697 # Hack for lazy extractors until more generic solution is implemented
3699 from .youtube import parse_qs
3701 if qs.get('v', [None])[0]:
3703 return super(YoutubePlaylistIE, cls).suitable(url)
3705 def _real_extract(self, url):
3706 playlist_id = self._match_id(url)
3707 is_music_url = self.is_music_url(url)
3708 url = update_url_query(
3709 'https://www.youtube.com/playlist',
3710 parse_qs(url) or {'list': playlist_id})
3712 url = smuggle_url(url, {'is_music_url': True})
3713 return self.url_result(url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3716 class YoutubeYtBeIE(InfoExtractor):
3717 IE_DESC = 'youtu.be'
3718 _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}
3720 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3722 'id': 'yeWKywCrFtk',
3724 'title': 'Small Scale Baler and Braiding Rugs',
3725 'uploader': 'Backus-Page House Museum',
3726 'uploader_id': 'backuspagemuseum',
3727 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3728 'upload_date': '20161008',
3729 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3730 'categories': ['Nonprofits & Activism'],
3733 'dislike_count': int,
3737 'skip_download': True,
3740 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3741 'only_matching': True,
3744 def _real_extract(self, url):
3745 mobj = re.match(self._VALID_URL, url)
3746 video_id = mobj.group('id')
3747 playlist_id = mobj.group('playlist_id')
3748 return self.url_result(
3749 update_url_query('https://www.youtube.com/watch', {
3751 'list': playlist_id,
3752 'feature': 'youtu.be',
3753 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3756 class YoutubeYtUserIE(InfoExtractor):
3757 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3758 _VALID_URL = r'ytuser:(?P<id>.+)'
3760 'url': 'ytuser:phihag',
3761 'only_matching': True,
3764 def _real_extract(self, url):
3765 user_id = self._match_id(url)
3766 return self.url_result(
3767 'https://www.youtube.com/user/%s' % user_id,
3768 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3771 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3772 IE_NAME = 'youtube:favorites'
3773 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3774 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3775 _LOGIN_REQUIRED = True
3778 'only_matching': True,
3780 'url': ':ytfavorites',
3781 'only_matching': True,
3784 def _real_extract(self, url):
3785 return self.url_result(
3786 'https://www.youtube.com/playlist?list=LL',
3787 ie=YoutubeTabIE.ie_key())
3790 class YoutubeSearchIE(SearchInfoExtractor, YoutubeTabIE):
3791 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3792 # there doesn't appear to be a real limit, for example if you search for
3793 # 'python' you get more than 8.000.000 results
3794 _MAX_RESULTS = float('inf')
3795 IE_NAME = 'youtube:search'
3796 _SEARCH_KEY = 'ytsearch'
3797 _SEARCH_PARAMS = None
3800 def _entries(self, query, n):
3801 data = {'query': query}
3802 if self._SEARCH_PARAMS:
3803 data['params'] = self._SEARCH_PARAMS
3805 for page_num in itertools.count(1):
3806 search = self._extract_response(
3807 item_id='query "%s" page %s' % (query, page_num), ep='search', query=data,
3808 check_get_keys=('contents', 'onResponseReceivedCommands')
3812 slr_contents = try_get(
3814 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3815 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3817 if not slr_contents:
3820 # Youtube sometimes adds promoted content to searches,
3821 # changing the index location of videos and token.
3822 # So we search through all entries till we find them.
3823 continuation_token = None
3824 for slr_content in slr_contents:
3825 if continuation_token is None:
3826 continuation_token = try_get(
3828 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3831 isr_contents = try_get(
3833 lambda x: x['itemSectionRenderer']['contents'],
3835 if not isr_contents:
3837 for content in isr_contents:
3838 if not isinstance(content, dict):
3840 video = content.get('videoRenderer')
3841 if not isinstance(video, dict):
3843 video_id = video.get('videoId')
3847 yield self._extract_video(video)
3852 if not continuation_token:
3854 data['continuation'] = continuation_token
3856 def _get_n_results(self, query, n):
3857 """Get a specified number of results for a query"""
3858 return self.playlist_result(self._entries(query, n), query)
3861 class YoutubeSearchDateIE(YoutubeSearchIE):
3862 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3863 _SEARCH_KEY = 'ytsearchdate'
3864 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3865 _SEARCH_PARAMS = 'CAI%3D'
3868 class YoutubeSearchURLIE(YoutubeSearchIE):
3869 IE_DESC = 'YouTube.com search URLs'
3870 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
3871 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
3872 # _MAX_RESULTS = 100
3874 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3875 'playlist_mincount': 5,
3877 'title': 'youtube-dl test video',
3880 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3881 'only_matching': True,
3885 def _make_valid_url(cls):
3886 return cls._VALID_URL
3888 def _real_extract(self, url):
3889 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
3890 query = (qs.get('search_query') or qs.get('q'))[0]
3891 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
3892 return self._get_n_results(query, self._MAX_RESULTS)
3895 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3897 Base class for feed extractors
3898 Subclasses must define the _FEED_NAME property.
3900 _LOGIN_REQUIRED = True
3905 return 'youtube:%s' % self._FEED_NAME
3907 def _real_initialize(self):
3910 def _real_extract(self, url):
3911 return self.url_result(
3912 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3913 ie=YoutubeTabIE.ie_key())
3916 class YoutubeWatchLaterIE(InfoExtractor):
3917 IE_NAME = 'youtube:watchlater'
3918 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3919 _VALID_URL = r':ytwatchlater'
3921 'url': ':ytwatchlater',
3922 'only_matching': True,
3925 def _real_extract(self, url):
3926 return self.url_result(
3927 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3930 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3931 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3932 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
3933 _FEED_NAME = 'recommended'
3936 'only_matching': True,
3938 'url': ':ytrecommended',
3939 'only_matching': True,
3941 'url': 'https://youtube.com',
3942 'only_matching': True,
3946 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3947 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
3948 _VALID_URL = r':ytsub(?:scription)?s?'
3949 _FEED_NAME = 'subscriptions'
3952 'only_matching': True,
3954 'url': ':ytsubscriptions',
3955 'only_matching': True,
3959 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3960 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
3961 _VALID_URL = r':ythis(?:tory)?'
3962 _FEED_NAME = 'history'
3964 'url': ':ythistory',
3965 'only_matching': True,
3969 class YoutubeTruncatedURLIE(InfoExtractor):
3970 IE_NAME = 'youtube:truncated_url'
3971 IE_DESC = False # Do not list
3972 _VALID_URL = r'''(?x
)
3974 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
3977 annotation_id
=annotation_
[^
&]+|
3983 attribution_link
\?a
=[^
&]+
3989 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3990 'only_matching': True,
3992 'url': 'https://www.youtube.com/watch?',
3993 'only_matching': True,
3995 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3996 'only_matching': True,
3998 'url': 'https://www.youtube.com/watch?feature=foo',
3999 'only_matching': True,
4001 'url': 'https://www.youtube.com/watch?hl=en-GB',
4002 'only_matching': True,
4004 'url': 'https://www.youtube.com/watch?t=2372',
4005 'only_matching': True,
4008 def _real_extract(self, url):
4009 raise ExtractorError(
4010 'Did you forget to quote the URL? Remember that & is a meta '
4011 'character in most shells, so you want to put the URL in quotes, '
4013 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
4014 ' or simply youtube-dl BaW_jenozKc .',
4018 class YoutubeTruncatedIDIE(InfoExtractor):
4019 IE_NAME = 'youtube:truncated_id'
4020 IE_DESC = False # Do not list
4021 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
4024 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
4025 'only_matching': True,
4028 def _real_extract(self, url):
4029 video_id = self._match_id(url)
4030 raise ExtractorError(
4031 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),