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|browse|playlist|watch|w|v|embed|e|watch_popup|'
71 r
'movies|results|shared|hashtag|trending|feed|feeds|oembed|get_video_info|'
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.
90 self
.report_warning(message
)
92 # username+password login is broken
93 if self
._LOGIN
_REQUIRED
and self
.get_param('cookiefile') is None:
94 self
.raise_login_required(
95 'Login details are needed to download this content', method
='cookies')
96 username
, password
= self
._get
_login
_info
()
98 warn('Logging in using username and password is broken. %s' % self
._LOGIN
_HINTS
['cookies'])
100 # Everything below this is broken!
102 # No authentication to be performed
104 if self
._LOGIN
_REQUIRED
and self
.get_param('cookiefile') is None:
105 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
106 # if self.get_param('cookiefile'): # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
107 # self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
110 login_page
= self
._download
_webpage
(
111 self
._LOGIN
_URL
, None,
112 note
='Downloading login page',
113 errnote
='unable to fetch login page', fatal
=False)
114 if login_page
is False:
117 login_form
= self
._hidden
_inputs
(login_page
)
119 def req(url
, f_req
, note
, errnote
):
120 data
= login_form
.copy()
123 'checkConnection': 'youtube',
124 'checkedDomains': 'youtube',
126 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
127 'f.req': json
.dumps(f_req
),
128 'flowName': 'GlifWebSignIn',
129 'flowEntry': 'ServiceLogin',
130 # TODO: reverse actual botguard identifier generation algo
131 'bgRequest': '["identifier",""]',
133 return self
._download
_json
(
134 url
, None, note
=note
, errnote
=errnote
,
135 transform_source
=lambda s
: re
.sub(r
'^[^[]*', '', s
),
137 data
=urlencode_postdata(data
), headers
={
138 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
139 'Google-Accounts-XSRF': 1,
144 None, [], None, 'US', None, None, 2, False, True,
148 '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',
150 1, [None, None, []], None, None, None, True
155 lookup_results
= req(
156 self
._LOOKUP
_URL
, lookup_req
,
157 'Looking up account info', 'Unable to look up account info')
159 if lookup_results
is False:
162 user_hash
= try_get(lookup_results
, lambda x
: x
[0][2], compat_str
)
164 warn('Unable to extract user hash')
169 None, 1, None, [1, None, None, None, [password
, None, True]],
171 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],
172 1, [None, None, []], None, None, None, True
175 challenge_results
= req(
176 self
._CHALLENGE
_URL
, challenge_req
,
177 'Logging in', 'Unable to log in')
179 if challenge_results
is False:
182 login_res
= try_get(challenge_results
, lambda x
: x
[0][5], list)
184 login_msg
= try_get(login_res
, lambda x
: x
[5], compat_str
)
186 'Unable to login: %s' % 'Invalid password'
187 if login_msg
== 'INCORRECT_ANSWER_ENTERED' else login_msg
)
190 res
= try_get(challenge_results
, lambda x
: x
[0][-1], list)
192 warn('Unable to extract result entry')
195 login_challenge
= try_get(res
, lambda x
: x
[0][0], list)
197 challenge_str
= try_get(login_challenge
, lambda x
: x
[2], compat_str
)
198 if challenge_str
== 'TWO_STEP_VERIFICATION':
199 # SEND_SUCCESS - TFA code has been successfully sent to phone
200 # QUOTA_EXCEEDED - reached the limit of TFA codes
201 status
= try_get(login_challenge
, lambda x
: x
[5], compat_str
)
202 if status
== 'QUOTA_EXCEEDED':
203 warn('Exceeded the limit of TFA codes, try later')
206 tl
= try_get(challenge_results
, lambda x
: x
[1][2], compat_str
)
208 warn('Unable to extract TL')
211 tfa_code
= self
._get
_tfa
_info
('2-step verification code')
215 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
216 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
219 tfa_code
= remove_start(tfa_code
, 'G-')
222 user_hash
, None, 2, None,
224 9, None, None, None, None, None, None, None,
225 [None, tfa_code
, True, 2]
229 self
._TFA
_URL
.format(tl
), tfa_req
,
230 'Submitting TFA code', 'Unable to submit TFA code')
232 if tfa_results
is False:
235 tfa_res
= try_get(tfa_results
, lambda x
: x
[0][5], list)
237 tfa_msg
= try_get(tfa_res
, lambda x
: x
[5], compat_str
)
239 'Unable to finish TFA: %s' % 'Invalid TFA code'
240 if tfa_msg
== 'INCORRECT_ANSWER_ENTERED' else tfa_msg
)
243 check_cookie_url
= try_get(
244 tfa_results
, lambda x
: x
[0][-1][2], compat_str
)
247 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
248 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
249 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
251 challenge
= CHALLENGES
.get(
253 '%s returned error %s.' % (self
.IE_NAME
, challenge_str
))
254 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge
)
257 check_cookie_url
= try_get(res
, lambda x
: x
[2], compat_str
)
259 if not check_cookie_url
:
260 warn('Unable to extract CheckCookie URL')
263 check_cookie_results
= self
._download
_webpage
(
264 check_cookie_url
, None, 'Checking cookie', fatal
=False)
266 if check_cookie_results
is False:
269 if 'https://myaccount.google.com/' not in check_cookie_results
:
270 warn('Unable to log in')
275 def _initialize_consent(self
):
276 cookies
= self
._get
_cookies
('https://www.youtube.com/')
277 if cookies
.get('__Secure-3PSID'):
280 consent
= cookies
.get('CONSENT')
282 if 'YES' in consent
.value
:
284 consent_id
= self
._search
_regex
(
285 r
'PENDING\+(\d+)', consent
.value
, 'consent', default
=None)
287 consent_id
= random
.randint(100, 999)
288 self
._set
_cookie
('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id
)
290 def _real_initialize(self
):
291 self
._initialize
_consent
()
292 if self
._downloader
is None:
294 if not self
._login
():
297 _YT_WEB_CLIENT_VERSION
= '2.20210407.08.00'
298 _YT_INNERTUBE_API_KEY
= 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
299 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
300 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
301 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
303 def _generate_sapisidhash_header(self):
304 sapisid_cookie = self._get_cookies('https://www.youtube.com').get('SAPISID')
305 if sapisid_cookie is None:
307 time_now = round(time.time())
308 sapisidhash = hashlib.sha1((str(time_now) + " " + sapisid_cookie.value + " " + "https
://www
.youtube
.com
").encode("utf
-8")).hexdigest()
309 return "SAPISIDHASH
%s_%s" % (time_now, sapisidhash)
311 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
312 note='Downloading API JSON', errnote='Unable to download API page',
313 context=None, api_key=None):
315 data = {'context': context} if context else {'context': self._extract_context()}
317 real_headers = self._generate_api_headers()
318 real_headers.update({'content-type': 'application/json'})
320 real_headers.update(headers)
321 return self._download_json(
322 'https://www.youtube.com/youtubei/v1/%s' % ep,
323 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
324 data=json.dumps(data).encode('utf8'), headers=real_headers,
325 query={'key': api_key or self._extract_api_key()})
327 def _extract_api_key(self, ytcfg=None):
328 return try_get(ytcfg, lambda x: x['INNERTUBE_API_KEY'], compat_str) or self._YT_INNERTUBE_API_KEY
330 def _extract_yt_initial_data(self, video_id, webpage):
331 return self._parse_json(
333 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
334 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
337 def _extract_identity_token(self, webpage, item_id):
338 ytcfg = self._extract_ytcfg(item_id, webpage)
340 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
343 return self._search_regex(
344 r'\bID_TOKEN["\']\s
*:\s
*["\'](.+?)["\']', webpage,
345 'identity token
', default=None)
348 def _extract_account_syncid(data):
350 Extract syncId required to download private playlists of secondary channels
351 @param data Either response or ytcfg
354 data, (lambda x: x['responseContext
']['mainAppWebResponseContext
']['datasyncId
'],
355 lambda x: x['DATASYNC_ID
']), compat_str) or '').split("||")
356 if len(sync_ids) >= 2 and sync_ids[1]:
357 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
358 # and just "user_syncid||" for primary channel. We only want the channel_syncid
360 # ytcfg includes channel_syncid if on secondary channel
361 return data.get('DELEGATED_SESSION_ID
')
363 def _extract_ytcfg(self, video_id, webpage):
366 return self._parse_json(
368 r'ytcfg\
.set\s
*\
(\s
*({.+?}
)\s
*\
)\s
*;', webpage, 'ytcfg
',
369 default='{}'), video_id, fatal=False) or {}
371 def __extract_client_version(self
, ytcfg
):
372 return try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_VERSION'], compat_str
) or self
._YT
_WEB
_CLIENT
_VERSION
374 def _extract_context(self
, ytcfg
=None):
375 context
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CONTEXT'], dict)
379 # Recreate the client context (required)
380 client_version
= self
.__extract
_client
_version
(ytcfg
)
381 client_name
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_NAME'], compat_str
) or 'WEB'
384 'clientName': client_name
,
385 'clientVersion': client_version
,
388 visitor_data
= try_get(ytcfg
, lambda x
: x
['VISITOR_DATA'], compat_str
)
390 context
['client']['visitorData'] = visitor_data
393 def _generate_api_headers(self
, ytcfg
=None, identity_token
=None, account_syncid
=None, visitor_data
=None):
395 'X-YouTube-Client-Name': '1',
396 'X-YouTube-Client-Version': self
.__extract
_client
_version
(ytcfg
),
399 headers
['x-youtube-identity-token'] = identity_token
401 headers
['X-Goog-PageId'] = account_syncid
402 headers
['X-Goog-AuthUser'] = 0
404 headers
['x-goog-visitor-id'] = visitor_data
405 auth
= self
._generate
_sapisidhash
_header
()
407 headers
['Authorization'] = auth
408 headers
['X-Origin'] = 'https://www.youtube.com'
412 def is_music_url(url
):
413 return re
.match(r
'https?://music\.youtube\.com/', url
) is not None
415 def _extract_video(self
, renderer
):
416 video_id
= renderer
.get('videoId')
419 (lambda x
: x
['title']['runs'][0]['text'],
420 lambda x
: x
['title']['simpleText']), compat_str
)
421 description
= try_get(
422 renderer
, lambda x
: x
['descriptionSnippet']['runs'][0]['text'],
424 duration
= parse_duration(try_get(
425 renderer
, lambda x
: x
['lengthText']['simpleText'], compat_str
))
426 view_count_text
= try_get(
427 renderer
, lambda x
: x
['viewCountText']['simpleText'], compat_str
) or ''
428 view_count
= str_to_int(self
._search
_regex
(
429 r
'^([\d,]+)', re
.sub(r
'\s', '', view_count_text
),
430 'view count', default
=None))
433 (lambda x
: x
['ownerText']['runs'][0]['text'],
434 lambda x
: x
['shortBylineText']['runs'][0]['text']), compat_str
)
437 'ie_key': YoutubeIE
.ie_key(),
441 'description': description
,
442 'duration': duration
,
443 'view_count': view_count
,
444 'uploader': uploader
,
448 class YoutubeIE(YoutubeBaseInfoExtractor
):
449 IE_DESC
= 'YouTube.com'
451 # invidious-redirect websites
452 r
'(?:www\.)?redirect\.invidious\.io',
453 r
'(?:(?:www|dev)\.)?invidio\.us',
454 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
455 r
'(?:www\.)?invidious\.pussthecat\.org',
456 r
'(?:www\.)?invidious\.zee\.li',
457 r
'(?:(?:www|au)\.)?ytprivate\.com',
458 r
'(?:www\.)?invidious\.namazso\.eu',
459 r
'(?:www\.)?invidious\.ethibox\.fr',
460 r
'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
461 r
'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
462 r
'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
463 r
'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
464 # youtube-dl invidious instances list
465 r
'(?:(?:www|no)\.)?invidiou\.sh',
466 r
'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
467 r
'(?:www\.)?invidious\.kabi\.tk',
468 r
'(?:www\.)?invidious\.mastodon\.host',
469 r
'(?:www\.)?invidious\.zapashcanon\.fr',
470 r
'(?:www\.)?invidious\.kavin\.rocks',
471 r
'(?:www\.)?invidious\.tinfoil-hat\.net',
472 r
'(?:www\.)?invidious\.himiko\.cloud',
473 r
'(?:www\.)?invidious\.reallyancient\.tech',
474 r
'(?:www\.)?invidious\.tube',
475 r
'(?:www\.)?invidiou\.site',
476 r
'(?:www\.)?invidious\.site',
477 r
'(?:www\.)?invidious\.xyz',
478 r
'(?:www\.)?invidious\.nixnet\.xyz',
479 r
'(?:www\.)?invidious\.048596\.xyz',
480 r
'(?:www\.)?invidious\.drycat\.fr',
481 r
'(?:www\.)?inv\.skyn3t\.in',
482 r
'(?:www\.)?tube\.poal\.co',
483 r
'(?:www\.)?tube\.connect\.cafe',
484 r
'(?:www\.)?vid\.wxzm\.sx',
485 r
'(?:www\.)?vid\.mint\.lgbt',
486 r
'(?:www\.)?vid\.puffyan\.us',
487 r
'(?:www\.)?yewtu\.be',
488 r
'(?:www\.)?yt\.elukerio\.org',
489 r
'(?:www\.)?yt\.lelux\.fi',
490 r
'(?:www\.)?invidious\.ggc-project\.de',
491 r
'(?:www\.)?yt\.maisputain\.ovh',
492 r
'(?:www\.)?ytprivate\.com',
493 r
'(?:www\.)?invidious\.13ad\.de',
494 r
'(?:www\.)?invidious\.toot\.koeln',
495 r
'(?:www\.)?invidious\.fdn\.fr',
496 r
'(?:www\.)?watch\.nettohikari\.com',
497 r
'(?:www\.)?kgg2m7yk5aybusll\.onion',
498 r
'(?:www\.)?qklhadlycap4cnod\.onion',
499 r
'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
500 r
'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
501 r
'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
502 r
'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
503 r
'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
504 r
'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
506 _VALID_URL
= r
"""(?x)^
508 (?:https?://|//) # http(s):// or protocol-independent URL
509 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
510 (?:www\.)?deturl\.com/www\.youtube\.com|
511 (?:www\.)?pwnyoutube\.com|
512 (?:www\.)?hooktube\.com|
513 (?:www\.)?yourepeat\.com|
516 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
517 (?:.*?\#/)? # handle anchor (#/) redirect urls
518 (?: # the various things that can precede the ID:
519 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
520 |(?: # or the v= param in all its forms
521 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
522 (?:\?|\#!?) # the params delimiter ? or # or #!
523 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
528 youtu\.be| # just youtu.be/xxxx
529 vid\.plus| # or vid.plus/xxxx
530 zwearz\.com/watch| # or zwearz.com/watch/xxxx
533 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
535 )? # all until now is optional -> you can pass the naked ID
536 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
537 (?(1).+)? # if we found the ID, everything can follow
539 'invidious': '|'.join(_INVIDIOUS_SITES
),
542 r
'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
543 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$',
544 r
'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
547 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
548 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
549 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'}
,
550 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'}
,
551 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'}
,
552 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
553 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
554 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
555 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
556 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'}
,
557 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
558 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
559 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
560 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
561 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
562 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
563 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
564 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
568 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
569 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
570 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
571 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
572 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20}
,
573 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
574 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
576 # Apple HTTP Live Streaming
577 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
578 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
579 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
580 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
581 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
582 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
583 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
584 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10}
,
587 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
588 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
589 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
590 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
591 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
592 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}
, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
593 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
594 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
595 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
596 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
597 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
598 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
601 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'}
,
602 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'}
,
603 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'}
,
604 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
605 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
606 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'}
,
607 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'}
,
610 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
611 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
612 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
613 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
614 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
615 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
616 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'}
,
617 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
618 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
619 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
620 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
621 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
622 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
623 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
624 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
625 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
626 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
627 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
628 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
629 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
630 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
631 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
634 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128}
,
635 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256}
,
637 # Dash webm audio with opus inside
638 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50}
,
639 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70}
,
640 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160}
,
643 '_rtmp': {'protocol': 'rtmp'}
,
645 # av01 video only formats sometimes served with "unknown" codecs
646 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
647 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
648 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
649 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
651 _SUBTITLE_FORMATS
= ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
658 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
662 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
663 'uploader': 'Philipp Hagemeister',
664 'uploader_id': 'phihag',
665 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
666 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
667 'channel_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
668 'upload_date': '20121002',
669 '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 .',
670 'categories': ['Science & Technology'],
671 'tags': ['youtube-dl'],
675 'dislike_count': int,
681 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
682 'note': 'Embed-only video (#1746)',
686 'upload_date': '20120608',
687 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
688 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
689 'uploader': 'SET India',
690 'uploader_id': 'setindia',
691 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/setindia',
694 'skip': 'Private video',
697 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
698 'note': 'Use the first video ID in the URL',
702 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
703 'uploader': 'Philipp Hagemeister',
704 'uploader_id': 'phihag',
705 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
706 'upload_date': '20121002',
707 '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 .',
708 'categories': ['Science & Technology'],
709 'tags': ['youtube-dl'],
713 'dislike_count': int,
716 'skip_download': True,
720 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
721 'note': '256k DASH audio (format 141) via DASH manifest',
725 'upload_date': '20121002',
726 'uploader_id': '8KVIDEO',
727 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
729 'uploader': '8KVIDEO',
730 'title': 'UHDTV TEST 8K VIDEO.mp4'
733 'youtube_include_dash_manifest': True,
736 'skip': 'format 141 not served anymore',
738 # DASH manifest with encrypted signature
740 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
744 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
745 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
747 'uploader': 'AfrojackVEVO',
748 'uploader_id': 'AfrojackVEVO',
749 'upload_date': '20131011',
753 'youtube_include_dash_manifest': True,
754 'format': '141/bestaudio[ext=m4a]',
759 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
764 'upload_date': '20100909',
765 'uploader': 'Amazing Atheist',
766 'uploader_id': 'TheAmazingAtheist',
767 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
768 'title': 'Burning Everyone\'s Koran',
769 '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',
772 # Normal age-gate video (embed allowed)
774 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
778 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
779 'description': r
're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
781 'uploader': 'The Witcher',
782 'uploader_id': 'WitcherGame',
783 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
784 'upload_date': '20140605',
788 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
789 # YouTube Red ad is not captured for creator
791 'url': '__2ABJjxzNo',
796 'upload_date': '20100430',
797 'uploader_id': 'deadmau5',
798 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/deadmau5',
799 'creator': 'deadmau5',
800 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
801 'uploader': 'deadmau5',
802 'title': 'Deadmau5 - Some Chords (HD)',
803 'alt_title': 'Some Chords',
805 'expected_warnings': [
806 'DASH manifest missing',
809 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
811 'url': 'lqQg6PlCWgI',
816 'upload_date': '20150827',
817 'uploader_id': 'olympic',
818 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/olympic',
819 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
820 'uploader': 'Olympic',
821 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
824 'skip_download': 'requires avconv',
829 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
833 'stretched_ratio': 16 / 9.,
835 'upload_date': '20110310',
836 'uploader_id': 'AllenMeow',
837 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
838 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
840 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
843 # url_encoded_fmt_stream_map is empty string
845 'url': 'qEJwOuvDf7I',
849 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
851 'upload_date': '20150404',
852 'uploader_id': 'spbelect',
853 'uploader': 'Наблюдатели Петербурга',
856 'skip_download': 'requires avconv',
858 'skip': 'This live event has ended.',
860 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
862 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
866 'title': 'md5:7b81415841e02ecd4313668cde88737a',
867 'description': 'md5:116377fd2963b81ec4ce64b542173306',
869 'upload_date': '20150625',
870 'uploader_id': 'dorappi2000',
871 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
872 'uploader': 'dorappi2000',
873 'formats': 'mincount:31',
875 'skip': 'not actual anymore',
877 # DASH manifest with segment_list
879 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
880 'md5': '8ce563a1d667b599d21064e982ab9e31',
884 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
885 'uploader': 'Airtek',
886 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
887 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
888 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
891 'youtube_include_dash_manifest': True,
892 'format': '135', # bestvideo
894 'skip': 'This live event has ended.',
897 # Multifeed videos (multiple cameras), URL is for Main Camera
898 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
901 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
902 'description': 'md5:e03b909557865076822aa169218d6a5d',
908 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
909 'description': 'md5:e03b909557865076822aa169218d6a5d',
911 'upload_date': '20161111',
912 'uploader': 'Team PGP',
913 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
914 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
920 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
921 'description': 'md5:e03b909557865076822aa169218d6a5d',
923 'upload_date': '20161111',
924 'uploader': 'Team PGP',
925 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
926 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
932 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
933 'description': 'md5:e03b909557865076822aa169218d6a5d',
935 'upload_date': '20161111',
936 'uploader': 'Team PGP',
937 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
938 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
944 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
945 'description': 'md5:e03b909557865076822aa169218d6a5d',
947 'upload_date': '20161111',
948 'uploader': 'Team PGP',
949 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
950 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
954 'skip_download': True,
958 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
959 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
962 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
965 'skip': 'Not multifeed anymore',
968 'url': 'https://vid.plus/FlRa-iH7PGw',
969 'only_matching': True,
972 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
973 'only_matching': True,
976 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
977 # Also tests cut-off URL expansion in video description (see
978 # https://github.com/ytdl-org/youtube-dl/issues/1892,
979 # https://github.com/ytdl-org/youtube-dl/issues/8164)
980 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
984 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
985 'alt_title': 'Dark Walk - Position Music',
986 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
988 'upload_date': '20151119',
989 'uploader_id': 'IronSoulElf',
990 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
991 'uploader': 'IronSoulElf',
992 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
993 'track': 'Dark Walk - Position Music',
994 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
995 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
998 'skip_download': True,
1002 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
1003 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
1004 'only_matching': True,
1007 # Video with yt:stretch=17:0
1008 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
1010 'id': 'Q39EVAstoRM',
1012 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
1013 'description': 'md5:ee18a25c350637c8faff806845bddee9',
1014 'upload_date': '20151107',
1015 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
1016 'uploader': 'CH GAMER DROID',
1019 'skip_download': True,
1021 'skip': 'This video does not exist.',
1024 # Video with incomplete 'yt:stretch=16:'
1025 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
1026 'only_matching': True,
1029 # Video licensed under Creative Commons
1030 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1032 'id': 'M4gD1WSo5mA',
1034 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1035 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
1037 'upload_date': '20150127',
1038 'uploader_id': 'BerkmanCenter',
1039 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
1040 'uploader': 'The Berkman Klein Center for Internet & Society',
1041 'license': 'Creative Commons Attribution license (reuse allowed)',
1044 'skip_download': True,
1048 # Channel-like uploader_url
1049 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1051 'id': 'eQcmzGIKrzg',
1053 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1054 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1056 'upload_date': '20151119',
1057 'uploader': 'Bernie Sanders',
1058 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1059 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
1060 'license': 'Creative Commons Attribution license (reuse allowed)',
1063 'skip_download': True,
1067 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
1068 'only_matching': True,
1071 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
1072 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1073 'only_matching': True,
1076 # Rental video preview
1077 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1079 'id': 'uGpuVWrhIzE',
1081 'title': 'Piku - Trailer',
1082 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1083 'upload_date': '20150811',
1084 'uploader': 'FlixMatrix',
1085 'uploader_id': 'FlixMatrixKaravan',
1086 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
1087 'license': 'Standard YouTube License',
1090 'skip_download': True,
1092 'skip': 'This video is not available.',
1095 # YouTube Red video with episode data
1096 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1098 'id': 'iqKdEhx-dD4',
1100 'title': 'Isolation - Mind Field (Ep 1)',
1101 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1103 'upload_date': '20170118',
1104 'uploader': 'Vsauce',
1105 'uploader_id': 'Vsauce',
1106 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1107 'series': 'Mind Field',
1109 'episode_number': 1,
1112 'skip_download': True,
1114 'expected_warnings': [
1115 'Skipping DASH manifest',
1119 # The following content has been identified by the YouTube community
1120 # as inappropriate or offensive to some audiences.
1121 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1123 'id': '6SJNVb0GnPI',
1125 'title': 'Race Differences in Intelligence',
1126 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1128 'upload_date': '20140124',
1129 'uploader': 'New Century Foundation',
1130 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1131 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1134 'skip_download': True,
1136 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1140 'url': '1t24XAntNCY',
1141 'only_matching': True,
1144 # geo restricted to JP
1145 'url': 'sJL6WA-aGkQ',
1146 'only_matching': True,
1149 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1150 'only_matching': True,
1153 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1154 'only_matching': True,
1157 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1158 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1159 'only_matching': True,
1163 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1164 'only_matching': True,
1167 # Video with unsupported adaptive stream type formats
1168 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1170 'id': 'Z4Vy8R84T1U',
1172 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1173 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1175 'upload_date': '20130923',
1176 'uploader': 'Amelia Putri Harwita',
1177 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1178 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1179 'formats': 'maxcount:10',
1182 'skip_download': True,
1183 'youtube_include_dash_manifest': False,
1185 'skip': 'not actual anymore',
1188 # Youtube Music Auto-generated description
1189 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1191 'id': 'MgNrAu2pzNs',
1193 'title': 'Voyeur Girl',
1194 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1195 'upload_date': '20190312',
1196 'uploader': 'Stephen - Topic',
1197 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1198 'artist': 'Stephen',
1199 'track': 'Voyeur Girl',
1200 'album': 'it\'s too much love to know my dear',
1201 'release_date': '20190313',
1202 'release_year': 2019,
1205 'skip_download': True,
1209 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1210 'only_matching': True,
1213 # invalid -> valid video id redirection
1214 'url': 'DJztXj2GPfl',
1216 'id': 'DJztXj2GPfk',
1218 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1219 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1220 'upload_date': '20090125',
1221 'uploader': 'Prochorowka',
1222 'uploader_id': 'Prochorowka',
1223 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1224 'artist': 'Panjabi MC',
1225 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1226 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1229 'skip_download': True,
1231 'skip': 'Video unavailable',
1234 # empty description results in an empty string
1235 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1237 'id': 'x41yOUIvK2k',
1239 'title': 'IMG 3456',
1241 'upload_date': '20170613',
1242 'uploader_id': 'ElevageOrVert',
1243 'uploader': 'ElevageOrVert',
1246 'skip_download': True,
1250 # with '};' inside yt initial data (see [1])
1251 # see [2] for an example with '};' inside ytInitialPlayerResponse
1252 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1253 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1254 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1256 'id': 'CHqg6qOn4no',
1258 'title': 'Part 77 Sort a list of simple types in c#',
1259 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1260 'upload_date': '20130831',
1261 'uploader_id': 'kudvenkat',
1262 'uploader': 'kudvenkat',
1265 'skip_download': True,
1269 # another example of '};' in ytInitialData
1270 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1271 'only_matching': True,
1274 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1275 'only_matching': True,
1278 # https://github.com/ytdl-org/youtube-dl/pull/28094
1279 'url': 'OtqTfy26tG0',
1281 'id': 'OtqTfy26tG0',
1283 'title': 'Burn Out',
1284 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1285 'upload_date': '20141120',
1286 'uploader': 'The Cinematic Orchestra - Topic',
1287 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1288 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1289 'artist': 'The Cinematic Orchestra',
1290 'track': 'Burn Out',
1291 'album': 'Every Day',
1292 'release_data': None,
1293 'release_year': None,
1296 'skip_download': True,
1300 # controversial video, only works with bpctr when authenticated with cookies
1301 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1302 'only_matching': True,
1305 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1306 'url': 'cBvYw8_A0vQ',
1308 'id': 'cBvYw8_A0vQ',
1310 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
1311 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1312 'upload_date': '20201120',
1313 'uploader': 'Walk around Japan',
1314 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1315 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1318 'skip_download': True,
1321 # Has multiple audio streams
1322 'url': 'WaOKSUlf4TM',
1323 'only_matching': True
1325 # Requires Premium: has format 141 when requested using YTM url
1326 'url': 'https://music.youtube.com/watch?v=XclachpHxis',
1327 'only_matching': True
1329 # multiple subtitles with same lang_code
1330 'url': 'https://www.youtube.com/watch?v=wsQiKKfKxug',
1331 'only_matching': True,
1336 def suitable(cls
, url
):
1337 # Hack for lazy extractors until more generic solution is implemented
1339 from .youtube
import parse_qs
1341 if qs
.get('list', [None])[0]:
1343 return super(YoutubeIE
, cls
).suitable(url
)
1345 def __init__(self
, *args
, **kwargs
):
1346 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
1347 self
._code
_cache
= {}
1348 self
._player
_cache
= {}
1350 def _signature_cache_id(self
, example_sig
):
1351 """ Return a string representation of a signature """
1352 return '.'.join(compat_str(len(part
)) for part
in example_sig
.split('.'))
1355 def _extract_player_info(cls
, player_url
):
1356 for player_re
in cls
._PLAYER
_INFO
_RE
:
1357 id_m
= re
.search(player_re
, player_url
)
1361 raise ExtractorError('Cannot identify player %r' % player_url
)
1362 return id_m
.group('id')
1364 def _extract_signature_function(self
, video_id
, player_url
, example_sig
):
1365 player_id
= self
._extract
_player
_info
(player_url
)
1367 # Read from filesystem cache
1368 func_id
= 'js_%s_%s' % (
1369 player_id
, self
._signature
_cache
_id
(example_sig
))
1370 assert os
.path
.basename(func_id
) == func_id
1372 cache_spec
= self
._downloader
.cache
.load('youtube-sigfuncs', func_id
)
1373 if cache_spec
is not None:
1374 return lambda s
: ''.join(s
[i
] for i
in cache_spec
)
1376 if player_id
not in self
._code
_cache
:
1377 self
._code
_cache
[player_id
] = self
._download
_webpage
(
1378 player_url
, video_id
,
1379 note
='Downloading player ' + player_id
,
1380 errnote
='Download of %s failed' % player_url
)
1381 code
= self
._code
_cache
[player_id
]
1382 res
= self
._parse
_sig
_js
(code
)
1384 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1385 cache_res
= res(test_string
)
1386 cache_spec
= [ord(c
) for c
in cache_res
]
1388 self
._downloader
.cache
.store('youtube-sigfuncs', func_id
, cache_spec
)
1391 def _print_sig_code(self
, func
, example_sig
):
1392 def gen_sig_code(idxs
):
1393 def _genslice(start
, end
, step
):
1394 starts
= '' if start
== 0 else str(start
)
1395 ends
= (':%d' % (end
+ step
)) if end
+ step
>= 0 else ':'
1396 steps
= '' if step
== 1 else (':%d' % step
)
1397 return 's[%s%s%s]' % (starts
, ends
, steps
)
1400 # Quelch pyflakes warnings - start will be set when step is set
1401 start
= '(Never used)'
1402 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
1403 if step
is not None:
1404 if i
- prev
== step
:
1406 yield _genslice(start
, prev
, step
)
1409 if i
- prev
in [-1, 1]:
1414 yield 's[%d]' % prev
1418 yield _genslice(start
, i
, step
)
1420 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1421 cache_res
= func(test_string
)
1422 cache_spec
= [ord(c
) for c
in cache_res
]
1423 expr_code
= ' + '.join(gen_sig_code(cache_spec
))
1424 signature_id_tuple
= '(%s)' % (
1425 ', '.join(compat_str(len(p
)) for p
in example_sig
.split('.')))
1426 code
= ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1427 ' return %s\n') % (signature_id_tuple
, expr_code
)
1428 self
.to_screen('Extracted signature function:\n' + code
)
1430 def _parse_sig_js(self
, jscode
):
1431 funcname
= self
._search
_regex
(
1432 (r
'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1433 r
'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1434 r
'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1435 r
'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1436 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+\)',
1437 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*\)',
1438 r
'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1440 r
'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1441 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1442 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1443 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1444 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1445 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1446 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1447 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1448 jscode, 'Initial JS player signature function name
', group='sig
')
1450 jsi = JSInterpreter(jscode)
1451 initial_function = jsi.extract_function(funcname)
1452 return lambda s: initial_function([s])
1454 def _decrypt_signature(self, s, video_id, player_url):
1455 """Turn the encrypted s field into a working signature"""
1457 if player_url is None:
1458 raise ExtractorError('Cannot decrypt signature without player_url
')
1460 if player_url.startswith('//'):
1461 player_url = 'https
:' + player_url
1462 elif not re.match(r'https?
://', player_url):
1463 player_url = compat_urlparse.urljoin(
1464 'https
://www
.youtube
.com
', player_url)
1466 player_id = (player_url, self._signature_cache_id(s))
1467 if player_id not in self._player_cache:
1468 func = self._extract_signature_function(
1469 video_id, player_url, s
1471 self._player_cache[player_id] = func
1472 func = self._player_cache[player_id]
1473 if self.get_param('youtube_print_sig_code
'):
1474 self._print_sig_code(func, s)
1476 except Exception as e:
1477 tb = traceback.format_exc()
1478 raise ExtractorError(
1479 'Signature extraction failed
: ' + tb, cause=e)
1481 def _mark_watched(self, video_id, player_response):
1482 playback_url = url_or_none(try_get(
1484 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1485 if not playback_url:
1487 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1488 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1490 # cpn generation algorithm is reverse engineered from base.js.
1491 # In fact it works even with dummy cpn.
1492 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1493 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1499 playback_url = compat_urlparse.urlunparse(
1500 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1502 self._download_webpage(
1503 playback_url, video_id, 'Marking watched
',
1504 'Unable to mark watched
', fatal=False)
1507 def _extract_urls(webpage):
1508 # Embedded YouTube player
1510 unescapeHTML(mobj.group('url
'))
1511 for mobj in re.finditer(r'''(?x)
1521 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1522 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1525 # lazyYT YouTube embed
1526 entries.extend(list(map(
1528 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1530 # Wordpress "YouTube Video Importer
" plugin
1531 matches = re.findall(r'''(?x)<div[^>]+
1532 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1533 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1534 entries.extend(m[-1] for m in matches)
1539 def _extract_url(webpage):
1540 urls = YoutubeIE._extract_urls(webpage)
1541 return urls[0] if urls else None
1544 def extract_id(cls, url):
1545 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1547 raise ExtractorError('Invalid URL: %s' % url)
1548 video_id = mobj.group(2)
1551 def _extract_chapters_from_json(self, data, video_id, duration):
1552 chapters_list = try_get(
1554 lambda x: x['playerOverlays']
1555 ['playerOverlayRenderer']
1556 ['decoratedPlayerBarRenderer']
1557 ['decoratedPlayerBarRenderer']
1559 ['chapteredPlayerBarRenderer']
1562 if not chapters_list:
1565 def chapter_time(chapter):
1566 return float_or_none(
1569 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1573 for next_num, chapter in enumerate(chapters_list, start=1):
1574 start_time = chapter_time(chapter)
1575 if start_time is None:
1577 end_time = (chapter_time(chapters_list[next_num])
1578 if next_num < len(chapters_list) else duration)
1579 if end_time is None:
1582 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1585 'start_time': start_time,
1586 'end_time': end_time,
1591 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1592 return self._parse_json(self._search_regex(
1593 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1594 regex), webpage, name, default='{}'), video_id, fatal=False)
1597 def parse_time_text(time_text):
1599 Parse the comment time text
1600 time_text is in the format 'X units ago (edited)'
1602 time_text_split = time_text.split(' ')
1603 if len(time_text_split) >= 3:
1604 return datetime_from_str('now-%s%s' % (time_text_split[0], time_text_split[1]), precision='auto')
1607 def _join_text_entries(runs):
1610 if not isinstance(run, dict):
1612 sub_text = try_get(run, lambda x: x['text'], compat_str)
1620 def _extract_comment(self, comment_renderer, parent=None):
1621 comment_id = comment_renderer.get('commentId')
1624 comment_text_runs = try_get(comment_renderer, lambda x: x['contentText']['runs']) or []
1625 text = self._join_text_entries(comment_text_runs) or ''
1626 comment_time_text = try_get(comment_renderer, lambda x: x['publishedTimeText']['runs']) or []
1627 time_text = self._join_text_entries(comment_time_text)
1628 timestamp = calendar.timegm(self.parse_time_text(time_text).timetuple())
1629 author = try_get(comment_renderer, lambda x: x['authorText']['simpleText'], compat_str)
1630 author_id = try_get(comment_renderer,
1631 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], compat_str)
1632 votes = str_to_int(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
1633 lambda x: x['likeCount']), compat_str)) or 0
1634 author_thumbnail = try_get(comment_renderer,
1635 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], compat_str)
1637 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
1638 is_liked = try_get(comment_renderer, lambda x: x['isLiked'], bool)
1642 'timestamp': timestamp,
1643 'time_text': time_text,
1644 'like_count': votes,
1645 'is_favorited': is_liked,
1647 'author_id': author_id,
1648 'author_thumbnail': author_thumbnail,
1649 'author_is_uploader': author_is_uploader,
1650 'parent': parent or 'root'
1653 def _comment_entries(self, root_continuation_data, identity_token, account_syncid,
1654 ytcfg, session_token_list, parent=None, comment_counts=None):
1656 def extract_thread(parent_renderer):
1657 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
1659 comment_counts[2] = 0
1660 for content in contents:
1661 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
1662 comment_renderer = try_get(
1663 comment_thread_renderer, (lambda x: x['comment']['commentRenderer'], dict)) or try_get(
1664 content, (lambda x: x['commentRenderer'], dict))
1666 if not comment_renderer:
1668 comment = self._extract_comment(comment_renderer, parent)
1671 comment_counts[0] += 1
1673 # Attempt to get the replies
1674 comment_replies_renderer = try_get(
1675 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
1677 if comment_replies_renderer:
1678 comment_counts[2] += 1
1679 comment_entries_iter = self._comment_entries(
1680 comment_replies_renderer, identity_token, account_syncid, ytcfg,
1681 parent=comment.get('id'), session_token_list=session_token_list,
1682 comment_counts=comment_counts)
1684 for reply_comment in comment_entries_iter:
1687 if not comment_counts:
1688 # comment so far, est. total comments, current comment thread #
1689 comment_counts = [0, 0, 0]
1691 # TODO: Generalize the download code with TabIE
1692 context = self._extract_context(ytcfg)
1693 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
1694 continuation = YoutubeTabIE._extract_continuation(root_continuation_data) # TODO
1695 first_continuation = False
1697 first_continuation = True
1699 for page_num in itertools.count(0):
1700 if not continuation:
1702 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
1703 retries = self.get_param('extractor_retries', 3)
1707 while count < retries:
1710 self.report_warning('%s. Retrying ...' % last_error)
1713 'ctoken': continuation['ctoken'],
1718 query['action_get_comment_replies'] = 1
1720 query['action_get_comments'] = 1
1722 comment_prog_str = '(%d/%d)' % (comment_counts[0], comment_counts[1])
1724 if first_continuation:
1725 note_prefix = 'Downloading initial comment continuation page'
1727 note_prefix = ' Downloading comment reply thread %d %s' % (comment_counts[2], comment_prog_str)
1729 note_prefix = '%sDownloading comment%s page %d %s' % (
1730 ' ' if parent else '',
1731 ' replies' if parent else '',
1735 browse = self._download_json(
1736 'https://www.youtube.com/comment_service_ajax', None,
1737 '%s %s' % (note_prefix, '(retry #%d)' % count if count else ''),
1738 headers=headers, query=query,
1739 data=urlencode_postdata({
1740 'session_token': session_token_list[0]
1742 except ExtractorError as e:
1743 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404, 413):
1744 if e.cause.code == 413:
1745 self.report_warning('Assumed end of comments (received HTTP Error 413)')
1747 # Downloading page may result in intermittent 5xx HTTP error
1748 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1749 last_error = 'HTTP Error %s' % e.cause.code
1750 if e.cause.code == 404:
1751 last_error = last_error + ' (this API is probably deprecated)'
1756 session_token = try_get(browse, lambda x: x['xsrf_token'], compat_str)
1758 session_token_list[0] = session_token
1760 response = try_get(browse,
1761 (lambda x: x['response'],
1762 lambda x: x[1]['response'])) or {}
1764 if response.get('continuationContents'):
1767 # YouTube sometimes gives reload: now json if something went wrong (e.g. bad auth)
1768 if browse.get('reload'):
1769 raise ExtractorError('Invalid or missing params in continuation request', expected=False)
1771 # TODO: not tested, merged from old extractor
1772 err_msg = browse.get('externalErrorMessage')
1774 raise ExtractorError('YouTube said: %s' % err_msg, expected=False)
1776 # Youtube sometimes sends incomplete data
1777 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1778 last_error = 'Incomplete data received'
1779 if count >= retries:
1780 raise ExtractorError(last_error)
1784 visitor_data = try_get(
1786 lambda x: x['responseContext']['webResponseContextExtensionData']['ytConfigData']['visitorData'],
1787 compat_str) or visitor_data
1789 known_continuation_renderers = {
1790 'itemSectionContinuation': extract_thread,
1791 'commentRepliesContinuation': extract_thread
1794 # extract next root continuation from the results
1795 continuation_contents = try_get(
1796 response, lambda x: x['continuationContents'], dict) or {}
1798 for key, value in continuation_contents.items():
1799 if key not in known_continuation_renderers:
1801 continuation_renderer = value
1803 if first_continuation:
1804 first_continuation = False
1805 expected_comment_count = try_get(
1806 continuation_renderer,
1807 (lambda x: x['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'],
1808 lambda x: x['header']['commentsHeaderRenderer']['commentsCount']['runs'][0]['text']),
1811 if expected_comment_count:
1812 comment_counts[1] = str_to_int(expected_comment_count)
1813 self.to_screen('Downloading ~%d comments' % str_to_int(expected_comment_count))
1814 yield comment_counts[1]
1817 # 1/True for newest, 0/False for popular (default)
1818 comment_sort_index = int(True)
1819 sort_continuation_renderer = try_get(
1820 continuation_renderer,
1821 lambda x: x['header']['commentsHeaderRenderer']['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems']
1822 [comment_sort_index]['continuation']['reloadContinuationData'], dict)
1823 # If this fails, the initial continuation page
1824 # starts off with popular anyways.
1825 if sort_continuation_renderer:
1826 continuation = YoutubeTabIE._build_continuation_query(
1827 continuation=sort_continuation_renderer.get('continuation'),
1828 ctp=sort_continuation_renderer.get('clickTrackingParams'))
1829 self.to_screen('Sorting comments by %s' % ('popular' if comment_sort_index == 0 else 'newest'))
1832 for entry in known_continuation_renderers[key](continuation_renderer):
1835 continuation = YoutubeTabIE._extract_continuation(continuation_renderer) # TODO
1838 def _extract_comments(self, ytcfg, video_id, contents, webpage, xsrf_token):
1839 """Entry for comment extraction"""
1841 known_entry_comment_renderers = (
1842 'itemSectionRenderer',
1845 for entry in contents:
1846 for key, renderer in entry.items():
1847 if key not in known_entry_comment_renderers:
1850 comment_iter = self._comment_entries(
1852 identity_token=self._extract_identity_token(webpage, item_id=video_id),
1853 account_syncid=self._extract_account_syncid(ytcfg),
1855 session_token_list=[xsrf_token])
1857 for comment in comment_iter:
1858 if isinstance(comment, int):
1859 estimated_total = comment
1861 comments.append(comment)
1863 self.to_screen('Downloaded %d/%d comments' % (len(comments), estimated_total))
1865 'comments': comments,
1866 'comment_count': len(comments),
1869 def _real_extract(self, url):
1870 url, smuggled_data = unsmuggle_url(url, {})
1871 video_id = self._match_id(url)
1873 is_music_url = smuggled_data.get('is_music_url') or self.is_music_url(url)
1875 base_url = self.http_scheme() + '//www.youtube.com/'
1876 webpage_url = base_url + 'watch?v=' + video_id
1877 webpage = self._download_webpage(
1878 webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1883 text = x.get('simpleText')
1884 if text and isinstance(text, compat_str):
1886 runs = x.get('runs')
1887 if not isinstance(runs, list):
1889 return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1891 ytm_streaming_data = {}
1893 # we are forcing to use parse_json because 141 only appeared in get_video_info.
1894 # el, c, cver, cplayer field required for 141(aac 256kbps) codec
1895 # maybe paramter of youtube music player?
1896 ytm_player_response = self._parse_json(try_get(compat_parse_qs(
1897 self._download_webpage(
1898 base_url + 'get_video_info', video_id,
1899 'Fetching youtube music info webpage',
1900 'unable to download youtube music info webpage', query={
1901 'video_id': video_id,
1902 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1906 'cplayer': 'UNIPLAYER',
1909 lambda x: x['player_response'][0],
1910 compat_str) or '{}', video_id)
1911 ytm_streaming_data = ytm_player_response.get('streamingData') or {}
1913 player_response = None
1915 player_response = self._extract_yt_initial_variable(
1916 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1917 video_id, 'initial player response')
1919 ytcfg = self._extract_ytcfg(video_id, webpage)
1920 if not player_response:
1921 player_response = self._call_api(
1922 'player', {'videoId': video_id}, video_id, api_key=self._extract_api_key(ytcfg))
1924 playability_status = player_response.get('playabilityStatus') or {}
1925 if playability_status.get('reason') == 'Sign in to confirm your age':
1926 pr = self._parse_json(try_get(compat_parse_qs(
1927 self._download_webpage(
1928 base_url + 'get_video_info', video_id,
1929 'Refetching age-gated info webpage',
1930 'unable to download video info webpage', query={
1931 'video_id': video_id,
1932 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1935 lambda x: x['player_response'][0],
1936 compat_str) or '{}', video_id)
1938 player_response = pr
1940 trailer_video_id = try_get(
1942 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1944 if trailer_video_id:
1945 return self.url_result(
1946 trailer_video_id, self.ie_key(), trailer_video_id)
1949 lambda x: self._html_search_meta(x, webpage, default=None)) \
1950 if webpage else lambda x: None
1952 video_details = player_response.get('videoDetails') or {}
1953 microformat = try_get(
1955 lambda x: x['microformat']['playerMicroformatRenderer'],
1957 video_title = video_details.get('title') \
1958 or get_text(microformat.get('title')) \
1959 or search_meta(['og:title', 'twitter:title', 'title'])
1960 video_description = video_details.get('shortDescription')
1962 if not smuggled_data.get('force_singlefeed', False):
1963 if not self.get_param('noplaylist'):
1964 multifeed_metadata_list = try_get(
1966 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1968 if multifeed_metadata_list:
1971 for feed in multifeed_metadata_list.split(','):
1972 # Unquote should take place before split on comma (,) since textual
1973 # fields may contain comma as well (see
1974 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1975 feed_data = compat_parse_qs(
1976 compat_urllib_parse_unquote_plus(feed))
1978 def feed_entry(name):
1980 feed_data, lambda x: x[name][0], compat_str)
1982 feed_id = feed_entry('id')
1985 feed_title = feed_entry('title')
1988 title += ' (%s)' % feed_title
1990 '_type': 'url_transparent',
1991 'ie_key': 'Youtube',
1993 base_url + 'watch?v=' + feed_data['id'][0],
1994 {'force_singlefeed': True}),
1997 feed_ids.append(feed_id)
1999 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
2000 % (', '.join(feed_ids), video_id))
2001 return self.playlist_result(
2002 entries, video_id, video_title, video_description)
2004 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
2006 formats, itags, stream_ids = [], [], []
2010 'tiny', 'audio_quality_low', 'audio_quality_medium', 'audio_quality_high', # Audio only formats
2011 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'
2014 streaming_data = player_response.get('streamingData') or {}
2015 streaming_formats = streaming_data.get('formats') or []
2016 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
2017 streaming_formats.extend(ytm_streaming_data.get('formats') or [])
2018 streaming_formats.extend(ytm_streaming_data.get('adaptiveFormats') or [])
2020 for fmt in streaming_formats:
2021 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
2024 itag = str_or_none(fmt.get('itag'))
2025 audio_track = fmt.get('audioTrack') or {}
2026 stream_id = '%s.%s' % (itag or '', audio_track.get('id', ''))
2027 if stream_id in stream_ids:
2030 quality = fmt.get('quality')
2031 if quality == 'tiny' or not quality:
2032 quality = fmt.get('audioQuality', '').lower() or quality
2033 if itag and quality:
2034 itag_qualities[itag] = quality
2035 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
2036 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
2037 # number of fragment that would subsequently requested with (`&sq=N`)
2038 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
2041 fmt_url = fmt.get('url')
2043 sc = compat_parse_qs(fmt.get('signatureCipher'))
2044 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
2045 encrypted_sig = try_get(sc, lambda x: x['s'][0])
2046 if not (sc and fmt_url and encrypted_sig):
2051 player_url = self._search_regex(
2052 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
2053 webpage, 'player URL', fatal=False)
2056 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
2057 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
2058 fmt_url += '&' + sp + '=' + signature
2062 stream_ids.append(stream_id)
2064 tbr = float_or_none(
2065 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
2067 'asr': int_or_none(fmt.get('audioSampleRate')),
2068 'filesize': int_or_none(fmt.get('contentLength')),
2070 'format_note': audio_track.get('displayName') or fmt.get('qualityLabel') or quality,
2071 'fps': int_or_none(fmt.get('fps')),
2072 'height': int_or_none(fmt.get('height')),
2073 'quality': q(quality),
2076 'width': fmt.get('width'),
2077 'language': audio_track.get('id', '').split('.')[0],
2079 mimetype = fmt.get('mimeType')
2082 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
2084 dct['ext'] = mimetype2ext(mobj.group(1))
2085 dct.update(parse_codecs(mobj.group(2)))
2086 no_audio = dct.get('acodec') == 'none'
2087 no_video = dct.get('vcodec') == 'none'
2092 if no_audio or no_video:
2093 dct['downloader_options'] = {
2094 # Youtube throttles chunks >~10M
2095 'http_chunk_size': 10485760,
2098 dct['container'] = dct['ext'] + '_dash'
2101 for sd in (streaming_data, ytm_streaming_data):
2102 hls_manifest_url = sd.get('hlsManifestUrl')
2103 if hls_manifest_url:
2104 for f in self._extract_m3u8_formats(
2105 hls_manifest_url, video_id, 'mp4', fatal=False):
2106 itag = self._search_regex(
2107 r'/itag/(\d+)', f['url'], 'itag', default=None)
2109 f['format_id'] = itag
2112 if self.get_param('youtube_include_dash_manifest', True):
2113 for sd in (streaming_data, ytm_streaming_data):
2114 dash_manifest_url = sd.get('dashManifestUrl')
2115 if dash_manifest_url:
2116 for f in self._extract_mpd_formats(
2117 dash_manifest_url, video_id, fatal=False):
2118 itag = f['format_id']
2121 if itag in itag_qualities:
2122 f['quality'] = q(itag_qualities[itag])
2123 filesize = int_or_none(self._search_regex(
2124 r'/clen/(\d+)', f.get('fragment_base_url')
2125 or f['url'], 'file size', default=None))
2127 f['filesize'] = filesize
2131 if not self.get_param('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
2132 self.raise_no_formats(
2133 'This video is DRM protected.', expected=True)
2136 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
2138 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
2139 subreason = pemr.get('subreason')
2141 subreason = clean_html(get_text(subreason))
2142 if subreason == 'The uploader has not made this video available in your country.':
2143 countries = microformat.get('availableCountries')
2145 regions_allowed = search_meta('regionsAllowed')
2146 countries = regions_allowed.split(',') if regions_allowed else None
2147 self.raise_geo_restricted(subreason, countries, metadata_available=True)
2148 reason += '\n' + subreason
2150 self.raise_no_formats(reason, expected=True)
2152 self._sort_formats(formats)
2154 keywords = video_details.get('keywords') or []
2155 if not keywords and webpage:
2157 unescapeHTML(m.group('content'))
2158 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
2159 for keyword in keywords:
2160 if keyword.startswith('yt:stretch='):
2161 mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
2163 # NB: float is intentional for forcing float division
2164 w, h = (float(v) for v in mobj.groups())
2168 if f.get('vcodec') != 'none':
2169 f['stretched_ratio'] = ratio
2173 for container in (video_details, microformat):
2174 for thumbnail in (try_get(
2176 lambda x: x['thumbnail']['thumbnails'], list) or []):
2177 thumbnail_url = thumbnail.get('url')
2178 if not thumbnail_url:
2180 # Sometimes youtube gives a wrong thumbnail URL. See:
2181 # https://github.com/yt-dlp/yt-dlp/issues/233
2182 # https://github.com/ytdl-org/youtube-dl/issues/28023
2183 if 'maxresdefault' in thumbnail_url:
2184 thumbnail_url = thumbnail_url.split('?')[0]
2186 'url': thumbnail_url,
2187 'height': int_or_none(thumbnail.get('height')),
2188 'width': int_or_none(thumbnail.get('width')),
2189 'preference': 1 if 'maxresdefault' in thumbnail_url else -1
2191 thumbnail_url = search_meta(['og:image', 'twitter:image'])
2194 'url': thumbnail_url,
2195 'preference': 1 if 'maxresdefault' in thumbnail_url else -1
2197 # All videos have a maxresdefault thumbnail, but sometimes it does not appear in the webpage
2198 # See: https://github.com/ytdl-org/youtube-dl/issues/29049
2200 'url': 'https://i.ytimg.com/vi/%s/maxresdefault.jpg' % video_id,
2203 self._remove_duplicate_formats(thumbnails)
2205 category = microformat.get('category') or search_meta('genre')
2206 channel_id = video_details.get('channelId') \
2207 or microformat.get('externalChannelId') \
2208 or search_meta('channelId')
2209 duration = int_or_none(
2210 video_details.get('lengthSeconds')
2211 or microformat.get('lengthSeconds')) \
2212 or parse_duration(search_meta('duration'))
2213 is_live = video_details.get('isLive')
2214 owner_profile_url = microformat.get('ownerProfileUrl')
2218 'title': self._live_title(video_title) if is_live else video_title,
2220 'thumbnails': thumbnails,
2221 'description': video_description,
2222 'upload_date': unified_strdate(
2223 microformat.get('uploadDate')
2224 or search_meta('uploadDate')),
2225 'uploader': video_details['author'],
2226 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
2227 'uploader_url': owner_profile_url,
2228 'channel_id': channel_id,
2229 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
2230 'duration': duration,
2231 'view_count': int_or_none(
2232 video_details.get('viewCount')
2233 or microformat.get('viewCount')
2234 or search_meta('interactionCount')),
2235 'average_rating': float_or_none(video_details.get('averageRating')),
2236 'age_limit': 18 if (
2237 microformat.get('isFamilySafe') is False
2238 or search_meta('isFamilyFriendly') == 'false'
2239 or search_meta('og:restrictions:age') == '18+') else 0,
2240 'webpage_url': webpage_url,
2241 'categories': [category] if category else None,
2244 'playable_in_embed': playability_status.get('playableInEmbed'),
2245 'was_live': video_details.get('isLiveContent'),
2250 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
2253 def process_language(container, base_url, lang_code, sub_name, query):
2254 lang_subs = container.setdefault(lang_code, [])
2255 for fmt in self._SUBTITLE_FORMATS:
2261 'url': update_url_query(base_url, query),
2265 for caption_track in (pctr.get('captionTracks') or []):
2266 base_url = caption_track.get('baseUrl')
2269 if caption_track.get('kind') != 'asr':
2271 remove_start(caption_track.get('vssId') or '', '.').replace('.', '-')
2272 or caption_track.get('languageCode'))
2276 subtitles, base_url, lang_code,
2277 try_get(caption_track, lambda x: x.get('name').get('simpleText')),
2280 automatic_captions = {}
2281 for translation_language in (pctr.get('translationLanguages') or []):
2282 translation_language_code = translation_language.get('languageCode')
2283 if not translation_language_code:
2286 automatic_captions, base_url, translation_language_code,
2287 try_get(translation_language, lambda x: x['languageName']['simpleText']),
2288 {'tlang': translation_language_code})
2289 info['automatic_captions'] = automatic_captions
2290 info['subtitles'] = subtitles
2292 parsed_url = compat_urllib_parse_urlparse(url)
2293 for component in [parsed_url.fragment, parsed_url.query]:
2294 query = compat_parse_qs(component)
2295 for k, v in query.items():
2296 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
2298 if d_k not in info and k in s_ks:
2299 info[d_k] = parse_duration(query[k][0])
2301 # Youtube Music Auto-generated description
2302 if video_description:
2303 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)
2305 release_year = mobj.group('release_year')
2306 release_date = mobj.group('release_date')
2308 release_date = release_date.replace('-', '')
2309 if not release_year:
2310 release_year = release_date[:4]
2312 'album': mobj.group('album'.strip()),
2313 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
2314 'track': mobj.group('track').strip(),
2315 'release_date': release_date,
2316 'release_year': int_or_none(release_year),
2321 initial_data = self._extract_yt_initial_variable(
2322 webpage, self._YT_INITIAL_DATA_RE, video_id,
2324 if not initial_data:
2325 initial_data = self._call_api(
2326 'next', {'videoId': video_id}, video_id, fatal=False, api_key=self._extract_api_key(ytcfg))
2330 # This will error if there is no livechat
2331 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
2332 info['subtitles']['live_chat'] = [{
2333 'url': 'https://www.youtube.com/watch?v=%s' % video_id, # url is needed to set cookies
2334 'video_id': video_id,
2336 'protocol': 'youtube_live_chat_replay',
2338 except (KeyError, IndexError, TypeError):
2342 chapters = self._extract_chapters_from_json(
2343 initial_data, video_id, duration)
2345 for engagment_pannel in (initial_data.get('engagementPanels') or []):
2347 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
2352 def chapter_time(mmlir):
2353 return parse_duration(
2354 get_text(mmlir.get('timeDescription')))
2357 for next_num, content in enumerate(contents, start=1):
2358 mmlir = content.get('macroMarkersListItemRenderer') or {}
2359 start_time = chapter_time(mmlir)
2360 end_time = chapter_time(try_get(
2361 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
2362 if next_num < len(contents) else duration
2363 if start_time is None or end_time is None:
2366 'start_time': start_time,
2367 'end_time': end_time,
2368 'title': get_text(mmlir.get('title')),
2373 info['chapters'] = chapters
2377 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
2379 for content in contents:
2380 vpir = content.get('videoPrimaryInfoRenderer')
2382 stl = vpir.get('superTitleLink')
2387 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
2388 info['location'] = stl
2390 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
2393 'series': mobj.group(1),
2394 'season_number': int(mobj.group(2)),
2395 'episode_number': int(mobj.group(3)),
2397 for tlb in (try_get(
2399 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
2401 tbr = tlb.get('toggleButtonRenderer') or {}
2402 for getter, regex in [(
2403 lambda x: x['defaultText']['accessibility']['accessibilityData'],
2404 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
2405 lambda x: x['accessibility'],
2406 lambda x: x['accessibilityData']['accessibilityData'],
2407 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
2408 label = (try_get(tbr, getter, dict) or {}).get('label')
2410 mobj = re.match(regex, label)
2412 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
2414 sbr_tooltip = try_get(
2415 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
2417 like_count, dislike_count = sbr_tooltip.split(' / ')
2419 'like_count': str_to_int(like_count),
2420 'dislike_count': str_to_int(dislike_count),
2422 vsir = content.get('videoSecondaryInfoRenderer')
2424 info['channel'] = get_text(try_get(
2426 lambda x: x['owner']['videoOwnerRenderer']['title'],
2430 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
2432 multiple_songs = False
2434 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
2435 multiple_songs = True
2438 mrr = row.get('metadataRowRenderer') or {}
2439 mrr_title = mrr.get('title')
2442 mrr_title = get_text(mrr['title'])
2443 mrr_contents_text = get_text(mrr['contents'][0])
2444 if mrr_title == 'License':
2445 info['license'] = mrr_contents_text
2446 elif not multiple_songs:
2447 if mrr_title == 'Album':
2448 info['album'] = mrr_contents_text
2449 elif mrr_title == 'Artist':
2450 info['artist'] = mrr_contents_text
2451 elif mrr_title == 'Song':
2452 info['track'] = mrr_contents_text
2455 'channel': 'uploader',
2456 'channel_id': 'uploader_id',
2457 'channel_url': 'uploader_url',
2459 for to, frm in fallbacks.items():
2460 if not info.get(to):
2461 info[to] = info.get(frm)
2463 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
2468 is_private = bool_or_none(video_details.get('isPrivate'))
2469 is_unlisted = bool_or_none(microformat.get('isUnlisted'))
2470 is_membersonly = None
2472 if initial_data and is_private is not None:
2473 is_membersonly = False
2475 contents = try_get(initial_data, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'], list)
2476 for content in contents or []:
2477 badges = try_get(content, lambda x: x['videoPrimaryInfoRenderer']['badges'], list)
2478 for badge in badges or []:
2479 label = try_get(badge, lambda x: x['metadataBadgeRenderer']['label']) or ''
2480 if label.lower() == 'members only':
2481 is_membersonly = True
2483 elif label.lower() == 'premium':
2486 if is_membersonly or is_premium:
2489 # TODO: Add this for playlists
2490 info['availability'] = self._availability(
2491 is_private=is_private,
2492 needs_premium=is_premium,
2493 needs_subscription=is_membersonly,
2494 needs_auth=info['age_limit'] >= 18,
2495 is_unlisted=None if is_private is None else is_unlisted)
2497 # get xsrf for annotations or comments
2498 get_annotations = self.get_param('writeannotations', False)
2499 get_comments = self.get_param('getcomments', False)
2500 if get_annotations or get_comments:
2502 ytcfg = self._extract_ytcfg(video_id, webpage)
2504 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2506 xsrf_token = self._search_regex(
2507 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2508 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2512 invideo_url = try_get(
2513 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2514 if xsrf_token and invideo_url:
2515 xsrf_field_name = None
2517 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2518 if not xsrf_field_name:
2519 xsrf_field_name = self._search_regex(
2520 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2521 webpage, 'xsrf field name',
2522 group='xsrf_field_name', default='session_token')
2523 info['annotations'] = self._download_webpage(
2524 self._proto_relative_url(invideo_url),
2525 video_id, note='Downloading annotations',
2526 errnote='Unable to download video annotations', fatal=False,
2527 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2530 info['__post_extractor'] = lambda: self._extract_comments(ytcfg, video_id, contents, webpage, xsrf_token)
2532 self.mark_watched(video_id, player_response)
2537 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2538 IE_DESC = 'YouTube.com tab'
2539 _VALID_URL = r'''(?x
)
2543 youtube(?
:kids
)?\
.com|
2547 (?P
<channel_type
>channel|c|user|browse
)/|
2550 (?
:playlist|watch
)\?.*?
\blist
=
2552 (?
!(?
:%s)\b) # Direct URLs
2555 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2556 IE_NAME = 'youtube:tab'
2559 'note': 'playlists, multipage',
2560 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2561 'playlist_mincount': 94,
2563 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2564 'title': 'Игорь Клейнер - Playlists',
2565 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2566 'uploader': 'Игорь Клейнер',
2567 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2570 'note': 'playlists, multipage, different order',
2571 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2572 'playlist_mincount': 94,
2574 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2575 'title': 'Игорь Клейнер - Playlists',
2576 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2577 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2578 'uploader': 'Игорь Клейнер',
2581 'note': 'playlists, series',
2582 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
2583 'playlist_mincount': 5,
2585 'id': 'UCYO_jab_esuFRV4b17AJtAw',
2586 'title': '3Blue1Brown - Playlists',
2587 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2588 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
2589 'uploader': '3Blue1Brown',
2592 'note': 'playlists, singlepage',
2593 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2594 'playlist_mincount': 4,
2596 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2597 'title': 'ThirstForScience - Playlists',
2598 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2599 'uploader': 'ThirstForScience',
2600 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2603 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2604 'only_matching': True,
2606 'note': 'basic, single video playlist',
2607 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2609 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2610 'uploader': 'Sergey M.',
2611 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2612 'title': 'youtube-dl public playlist',
2614 'playlist_count': 1,
2616 'note': 'empty playlist',
2617 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2619 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2620 'uploader': 'Sergey M.',
2621 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2622 'title': 'youtube-dl empty playlist',
2624 'playlist_count': 0,
2627 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2629 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2630 'title': 'lex will - Home',
2631 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2632 'uploader': 'lex will',
2633 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2635 'playlist_mincount': 2,
2637 'note': 'Videos tab',
2638 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2640 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2641 'title': 'lex will - Videos',
2642 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2643 'uploader': 'lex will',
2644 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2646 'playlist_mincount': 975,
2648 'note': 'Videos tab, sorted by popular',
2649 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2651 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2652 'title': 'lex will - Videos',
2653 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2654 'uploader': 'lex will',
2655 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2657 'playlist_mincount': 199,
2659 'note': 'Playlists tab',
2660 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2662 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2663 'title': 'lex will - Playlists',
2664 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2665 'uploader': 'lex will',
2666 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2668 'playlist_mincount': 17,
2670 'note': 'Community tab',
2671 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2673 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2674 'title': 'lex will - Community',
2675 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2676 'uploader': 'lex will',
2677 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2679 'playlist_mincount': 18,
2681 'note': 'Channels tab',
2682 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2684 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2685 'title': 'lex will - Channels',
2686 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2687 'uploader': 'lex will',
2688 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2690 'playlist_mincount': 12,
2692 'note': 'Search tab',
2693 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
2694 'playlist_mincount': 40,
2696 'id': 'UCYO_jab_esuFRV4b17AJtAw',
2697 'title': '3Blue1Brown - Search - linear algebra',
2698 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2699 'uploader': '3Blue1Brown',
2700 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
2703 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2704 'only_matching': True,
2706 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2707 'only_matching': True,
2709 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2710 'only_matching': True,
2712 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2713 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2715 'title': '29C3: Not my department',
2716 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2717 'uploader': 'Christiaan008',
2718 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2719 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2721 'playlist_count': 96,
2723 'note': 'Large playlist',
2724 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2726 'title': 'Uploads from Cauchemar',
2727 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2728 'uploader': 'Cauchemar',
2729 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2731 'playlist_mincount': 1123,
2733 'note': 'even larger playlist, 8832 videos',
2734 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2735 'only_matching': True,
2737 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2738 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2740 'title': 'Uploads from Interstellar Movie',
2741 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2742 'uploader': 'Interstellar Movie',
2743 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2745 'playlist_mincount': 21,
2747 'note': 'Playlist with "show unavailable videos" button',
2748 'url': 'https://www.youtube.com/playlist?list=UUTYLiWFZy8xtPwxFwX9rV7Q',
2750 'title': 'Uploads from Phim Siêu Nhân Nhật Bản',
2751 'id': 'UUTYLiWFZy8xtPwxFwX9rV7Q',
2752 'uploader': 'Phim Siêu Nhân Nhật Bản',
2753 'uploader_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
2755 'playlist_mincount': 200,
2757 'note': 'Playlist with unavailable videos in page 7',
2758 'url': 'https://www.youtube.com/playlist?list=UU8l9frL61Yl5KFOl87nIm2w',
2760 'title': 'Uploads from BlankTV',
2761 'id': 'UU8l9frL61Yl5KFOl87nIm2w',
2762 'uploader': 'BlankTV',
2763 'uploader_id': 'UC8l9frL61Yl5KFOl87nIm2w',
2765 'playlist_mincount': 1000,
2767 'note': 'https://github.com/ytdl-org/youtube-dl/issues/21844',
2768 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2770 'title': 'Data Analysis with Dr Mike Pound',
2771 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2772 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2773 'uploader': 'Computerphile',
2774 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2776 'playlist_mincount': 11,
2778 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2779 'only_matching': True,
2781 'note': 'Playlist URL that does not actually serve a playlist',
2782 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2784 'id': 'FqZTN594JQw',
2786 'title': "Smiley's People 01 detective, Adventure Series, Action",
2787 'uploader': 'STREEM',
2788 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2789 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2790 'upload_date': '20150526',
2791 'license': 'Standard YouTube License',
2792 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2793 'categories': ['People & Blogs'],
2797 'dislike_count': int,
2800 'skip_download': True,
2802 'skip': 'This video is not available.',
2803 'add_ie': [YoutubeIE.ie_key()],
2805 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2806 'only_matching': True,
2808 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2809 'only_matching': True,
2811 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2813 'id': 'X1whbWASnNQ', # This will keep changing
2815 'title': compat_str,
2816 'uploader': 'Sky News',
2817 'uploader_id': 'skynews',
2818 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2819 'upload_date': r're:\d{8}',
2820 'description': compat_str,
2821 'categories': ['News & Politics'],
2824 'dislike_count': int,
2827 'skip_download': True,
2829 'expected_warnings': ['Downloading just video ', 'Ignoring subtitle tracks found in '],
2831 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2833 'id': 'a48o2S1cPoo',
2835 'title': 'The Young Turks - Live Main Show',
2836 'uploader': 'The Young Turks',
2837 'uploader_id': 'TheYoungTurks',
2838 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2839 'upload_date': '20150715',
2840 'license': 'Standard YouTube License',
2841 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2842 'categories': ['News & Politics'],
2843 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2845 'dislike_count': int,
2848 'skip_download': True,
2850 'only_matching': True,
2852 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2853 'only_matching': True,
2855 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2856 'only_matching': True,
2858 'note': 'A channel that is not live. Should raise error',
2859 'url': 'https://www.youtube.com/user/numberphile/live',
2860 'only_matching': True,
2862 'url': 'https://www.youtube.com/feed/trending',
2863 'only_matching': True,
2865 'url': 'https://www.youtube.com/feed/library',
2866 'only_matching': True,
2868 'url': 'https://www.youtube.com/feed/history',
2869 'only_matching': True,
2871 'url': 'https://www.youtube.com/feed/subscriptions',
2872 'only_matching': True,
2874 'url': 'https://www.youtube.com/feed/watch_later',
2875 'only_matching': True,
2877 'note': 'Recommended - redirects to home page',
2878 'url': 'https://www.youtube.com/feed/recommended',
2879 'only_matching': True,
2881 'note': 'inline playlist with not always working continuations',
2882 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2883 'only_matching': True,
2885 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2886 'only_matching': True,
2888 'url': 'https://www.youtube.com/course',
2889 'only_matching': True,
2891 'url': 'https://www.youtube.com/zsecurity',
2892 'only_matching': True,
2894 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2895 'only_matching': True,
2897 'url': 'https://www.youtube.com/TheYoungTurks/live',
2898 'only_matching': True,
2900 'url': 'https://www.youtube.com/hashtag/cctv9',
2905 'playlist_mincount': 350,
2907 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
2908 'only_matching': True,
2910 'note': 'Requires Premium: should request additional YTM-info webpage (and have format 141) for videos in playlist',
2911 'url': 'https://music.youtube.com/playlist?list=PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
2912 'only_matching': True
2914 'note': '/browse/ should redirect to /channel/',
2915 'url': 'https://music.youtube.com/browse/UC1a8OFewdjuLq6KlF8M_8Ng',
2916 'only_matching': True
2918 'note': 'VLPL, should redirect to playlist?list=PL...',
2919 'url': 'https://music.youtube.com/browse/VLPLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
2921 'id': 'PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
2922 'uploader': 'NoCopyrightSounds',
2923 'description': 'Providing you with copyright free / safe music for gaming, live streaming, studying and more!',
2924 'uploader_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg',
2925 'title': 'NCS Releases',
2927 'playlist_mincount': 166,
2929 'note': 'Topic, should redirect to playlist?list=UU...',
2930 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
2932 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
2933 'uploader_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
2934 'title': 'Uploads from Royalty Free Music - Topic',
2935 'uploader': 'Royalty Free Music - Topic',
2937 'expected_warnings': [
2938 'A channel/user page was given',
2939 'The URL does not have a videos tab',
2941 'playlist_mincount': 101,
2943 'note': 'Topic without a UU playlist',
2944 'url': 'https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg',
2946 'id': 'UCtFRv9O2AHqOZjjynzrv-xg',
2947 'title': 'UCtFRv9O2AHqOZjjynzrv-xg',
2949 'expected_warnings': [
2950 'A channel/user page was given',
2951 'The URL does not have a videos tab',
2952 'Falling back to channel URL',
2954 'playlist_mincount': 9,
2956 'note': 'Youtube music Album',
2957 'url': 'https://music.youtube.com/browse/MPREb_gTAcphH99wE',
2959 'id': 'OLAK5uy_l1m0thk3g31NmIIz_vMIbWtyv7eZixlH0',
2960 'title': 'Album - Royalty Free Music Library V2 (50 Songs)',
2962 'playlist_count': 50,
2966 def suitable(cls, url):
2967 return False if YoutubeIE.suitable(url) else super(
2968 YoutubeTabIE, cls).suitable(url)
2970 def _extract_channel_id(self, webpage):
2971 channel_id = self._html_search_meta(
2972 'channelId', webpage, 'channel id', default=None)
2975 channel_url = self._html_search_meta(
2976 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2977 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2978 'twitter:app:url:googleplay'), webpage, 'channel url')
2979 return self._search_regex(
2980 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2981 channel_url, 'channel id')
2984 def _extract_basic_item_renderer(item):
2985 # Modified from _extract_grid_item_renderer
2986 known_basic_renderers = (
2987 'playlistRenderer', 'videoRenderer', 'channelRenderer', 'showRenderer'
2989 for key, renderer in item.items():
2990 if not isinstance(renderer, dict):
2992 elif key in known_basic_renderers:
2994 elif key.startswith('grid') and key.endswith('Renderer'):
2997 def _grid_entries(self, grid_renderer):
2998 for item in grid_renderer['items']:
2999 if not isinstance(item, dict):
3001 renderer = self._extract_basic_item_renderer(item)
3002 if not isinstance(renderer, dict):
3005 renderer, (lambda x: x['title']['runs'][0]['text'],
3006 lambda x: x['title']['simpleText']), compat_str)
3008 playlist_id = renderer.get('playlistId')
3010 yield self.url_result(
3011 'https://www.youtube.com/playlist?list=%s' % playlist_id,
3012 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3016 video_id = renderer.get('videoId')
3018 yield self._extract_video(renderer)
3021 channel_id = renderer.get('channelId')
3024 renderer, lambda x: x['title']['simpleText'], compat_str)
3025 yield self.url_result(
3026 'https://www.youtube.com/channel/%s' % channel_id,
3027 ie=YoutubeTabIE.ie_key(), video_title=title)
3029 # generic endpoint URL support
3030 ep_url = urljoin('https://www.youtube.com/', try_get(
3031 renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
3034 for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
3035 if ie.suitable(ep_url):
3036 yield self.url_result(
3037 ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
3040 def _shelf_entries_from_content(self, shelf_renderer):
3041 content = shelf_renderer.get('content')
3042 if not isinstance(content, dict):
3044 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
3046 # TODO: add support for nested playlists so each shelf is processed
3047 # as separate playlist
3048 # TODO: this includes only first N items
3049 for entry in self._grid_entries(renderer):
3051 renderer = content.get('horizontalListRenderer')
3056 def _shelf_entries(self, shelf_renderer, skip_channels=False):
3058 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3060 shelf_url = urljoin('https://www.youtube.com', ep)
3062 # Skipping links to another channels, note that checking for
3063 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
3065 if skip_channels and '/channels?' in shelf_url:
3068 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
3069 yield self.url_result(shelf_url, video_title=title)
3070 # Shelf may not contain shelf URL, fallback to extraction from content
3071 for entry in self._shelf_entries_from_content(shelf_renderer):
3074 def _playlist_entries(self, video_list_renderer):
3075 for content in video_list_renderer['contents']:
3076 if not isinstance(content, dict):
3078 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
3079 if not isinstance(renderer, dict):
3081 video_id = renderer.get('videoId')
3084 yield self._extract_video(renderer)
3086 def _rich_entries(self, rich_grid_renderer):
3088 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
3089 video_id = renderer.get('videoId')
3092 yield self._extract_video(renderer)
3094 def _video_entry(self, video_renderer):
3095 video_id = video_renderer.get('videoId')
3097 return self._extract_video(video_renderer)
3099 def _post_thread_entries(self, post_thread_renderer):
3100 post_renderer = try_get(
3101 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
3102 if not post_renderer:
3105 video_renderer = try_get(
3106 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict) or {}
3107 video_id = video_renderer.get('videoId')
3109 entry = self._extract_video(video_renderer)
3112 # playlist attachment
3113 playlist_id = try_get(
3114 post_renderer, lambda x: x['backstageAttachment']['playlistRenderer']['playlistId'], compat_str)
3116 yield self.url_result(
3117 'https://www.youtube.com/playlist?list=%s' % playlist_id,
3118 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3119 # inline video links
3120 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
3122 if not isinstance(run, dict):
3125 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
3128 if not YoutubeIE.suitable(ep_url):
3130 ep_video_id = YoutubeIE._match_id(ep_url)
3131 if video_id == ep_video_id:
3133 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=ep_video_id)
3135 def _post_thread_continuation_entries(self, post_thread_continuation):
3136 contents = post_thread_continuation.get('contents')
3137 if not isinstance(contents, list):
3139 for content in contents:
3140 renderer = content.get('backstagePostThreadRenderer')
3141 if not isinstance(renderer, dict):
3143 for entry in self._post_thread_entries(renderer):
3147 def _rich_grid_entries(self
, contents
):
3148 for content
in contents
:
3149 video_renderer
= try_get(content
, lambda x
: x
['richItemRenderer']['content']['videoRenderer'], dict)
3151 entry
= self
._video
_entry
(video_renderer
)
3157 def _build_continuation_query(continuation, ctp=None):
3159 'ctoken': continuation,
3160 'continuation': continuation,
3167 def _extract_next_continuation_data(renderer):
3168 next_continuation = try_get(
3169 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
3170 if not next_continuation:
3172 continuation = next_continuation.get('continuation')
3173 if not continuation:
3175 ctp = next_continuation.get('clickTrackingParams')
3176 return YoutubeTabIE._build_continuation_query(continuation, ctp)
3179 def _extract_continuation(cls, renderer):
3180 next_continuation = cls._extract_next_continuation_data(renderer)
3181 if next_continuation:
3182 return next_continuation
3184 for key in ('contents', 'items'):
3185 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
3186 for content in contents:
3187 if not isinstance(content, dict):
3189 continuation_ep = try_get(
3190 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
3192 if not continuation_ep:
3194 continuation = try_get(
3195 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
3196 if not continuation:
3198 ctp = continuation_ep.get('clickTrackingParams')
3199 return YoutubeTabIE._build_continuation_query(continuation, ctp)
3201 def _entries(self, tab, item_id, identity_token, account_syncid, ytcfg):
3203 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
3204 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
3205 for content in contents:
3206 if not isinstance(content, dict):
3208 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
3210 renderer = content.get('richItemRenderer')
3212 for entry in self._rich_entries(renderer):
3214 continuation_list[0] = self._extract_continuation(parent_renderer)
3216 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
3217 for isr_content in isr_contents:
3218 if not isinstance(isr_content, dict):
3222 'playlistVideoListRenderer': self._playlist_entries,
3223 'gridRenderer': self._grid_entries,
3224 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
3225 'backstagePostThreadRenderer': self._post_thread_entries,
3226 'videoRenderer': lambda x: [self._video_entry(x)],
3228 for key, renderer in isr_content.items():
3229 if key not in known_renderers:
3231 for entry in known_renderers[key](renderer):
3234 continuation_list[0] = self._extract_continuation(renderer)
3237 if not continuation_list[0]:
3238 continuation_list[0] = self._extract_continuation(is_renderer)
3240 if not continuation_list[0]:
3241 continuation_list[0] = self._extract_continuation(parent_renderer)
3243 continuation_list = [None] # Python 2 doesnot support nonlocal
3244 tab_content = try_get(tab, lambda x: x['content'], dict)
3248 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
3249 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
3250 for entry in extract_entries(parent_renderer):
3252 continuation = continuation_list[0]
3253 context = self._extract_context(ytcfg)
3254 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
3256 for page_num in itertools.count(1):
3257 if not continuation:
3260 'continuation': continuation['continuation'],
3261 'clickTracking': {'clickTrackingParams': continuation['itct']}
3263 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
3264 response = self._extract_response(
3265 item_id='%s page %s' % (item_id, page_num),
3266 query=query, headers=headers, ytcfg=ytcfg,
3267 check_get_keys=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3271 visitor_data = try_get(
3272 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
3274 known_continuation_renderers = {
3275 'playlistVideoListContinuation': self._playlist_entries,
3276 'gridContinuation': self._grid_entries,
3277 'itemSectionContinuation': self._post_thread_continuation_entries,
3278 'sectionListContinuation': extract_entries, # for feeds
3280 continuation_contents = try_get(
3281 response, lambda x: x['continuationContents'], dict) or {}
3282 continuation_renderer = None
3283 for key, value in continuation_contents.items():
3284 if key not in known_continuation_renderers:
3286 continuation_renderer = value
3287 continuation_list = [None]
3288 for entry in known_continuation_renderers[key](continuation_renderer):
3290 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
3292 if continuation_renderer:
3296 'gridPlaylistRenderer': (self._grid_entries, 'items'),
3297 'gridVideoRenderer': (self._grid_entries, 'items'),
3298 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
3299 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
3300 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
3301 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents')
3303 on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3304 continuation_items = try_get(
3305 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
3306 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
3307 video_items_renderer = None
3308 for key, value in continuation_item.items():
3309 if key not in known_renderers:
3311 video_items_renderer = {known_renderers[key][1]: continuation_items}
3312 continuation_list = [None]
3313 for entry in known_renderers[key][0](video_items_renderer):
3315 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
3317 if video_items_renderer:
3322 def _extract_selected_tab(tabs):
3324 renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
3325 if renderer.get('selected') is True:
3328 raise ExtractorError('Unable to find selected tab')
3331 def _extract_uploader(data):
3333 sidebar_renderer = try_get(
3334 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3335 if sidebar_renderer:
3336 for item in sidebar_renderer:
3337 if not isinstance(item, dict):
3339 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
3340 if not isinstance(renderer, dict):
3343 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
3345 uploader['uploader'] = owner.get('text')
3346 uploader['uploader_id'] = try_get(
3347 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
3348 uploader['uploader_url'] = urljoin(
3349 'https://www.youtube.com/',
3350 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
3351 return {k: v for k, v in uploader.items() if v is not None}
3353 def _extract_from_tabs(self, item_id, webpage, data, tabs):
3354 playlist_id = title = description = channel_url = channel_name = channel_id = None
3355 thumbnails_list = tags = []
3357 selected_tab = self._extract_selected_tab(tabs)
3359 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
3361 channel_name = renderer.get('title')
3362 channel_url = renderer.get('channelUrl')
3363 channel_id = renderer.get('externalId')
3366 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
3369 title = renderer.get('title')
3370 description = renderer.get('description', '')
3371 playlist_id = channel_id
3372 tags = renderer.get('keywords', '').split()
3374 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
3377 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
3382 for t in thumbnails_list:
3383 if not isinstance(t, dict):
3385 thumbnail_url = url_or_none(t.get('url'))
3386 if not thumbnail_url:
3389 'url': thumbnail_url,
3390 'width': int_or_none(t.get('width')),
3391 'height': int_or_none(t.get('height')),
3393 if playlist_id is None:
3394 playlist_id = item_id
3397 try_get(data, lambda x: x['header']['hashtagHeaderRenderer']['hashtag']['simpleText'])
3399 title += format_field(selected_tab, 'title', ' - %s')
3400 title += format_field(selected_tab, 'expandedText', ' - %s')
3403 'playlist_id': playlist_id,
3404 'playlist_title': title,
3405 'playlist_description': description,
3406 'uploader': channel_name,
3407 'uploader_id': channel_id,
3408 'uploader_url': channel_url,
3409 'thumbnails': thumbnails,
3413 metadata.update(self._extract_uploader(data))
3415 'channel': metadata['uploader'],
3416 'channel_id': metadata['uploader_id'],
3417 'channel_url': metadata['uploader_url']})
3418 return self.playlist_result(
3420 selected_tab, playlist_id,
3421 self._extract_identity_token(webpage, item_id),
3422 self._extract_account_syncid(data),
3423 self._extract_ytcfg(item_id, webpage)),
3426 def _extract_mix_playlist(self, playlist, playlist_id, data, webpage):
3427 first_id = last_id = None
3428 ytcfg = self._extract_ytcfg(playlist_id, webpage)
3429 headers = self._generate_api_headers(
3430 ytcfg, account_syncid=self._extract_account_syncid(data),
3431 identity_token=self._extract_identity_token(webpage, item_id=playlist_id),
3432 visitor_data=try_get(self._extract_context(ytcfg), lambda x: x['client']['visitorData'], compat_str))
3433 for page_num in itertools.count(1):
3434 videos = list(self._playlist_entries(playlist))
3437 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
3438 if start >= len(videos):
3440 for video in videos[start:]:
3441 if video['id'] == first_id:
3442 self.to_screen('First video %s found again; Assuming end of Mix' % first_id)
3445 first_id = first_id or videos[0]['id']
3446 last_id = videos[-1]['id']
3447 watch_endpoint = try_get(
3448 playlist, lambda x: x['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
3450 'playlistId': playlist_id,
3451 'videoId': watch_endpoint.get('videoId') or last_id,
3452 'index': watch_endpoint.get('index') or len(videos),
3453 'params': watch_endpoint.get('params') or 'OAE%3D'
3455 response = self._extract_response(
3456 item_id='%s page %d' % (playlist_id, page_num),
3460 check_get_keys='contents'
3463 response, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3465 def _extract_from_playlist(self, item_id, url, data, playlist, webpage):
3466 title = playlist.get('title') or try_get(
3467 data, lambda x: x['titleText']['simpleText'], compat_str)
3468 playlist_id = playlist.get('playlistId') or item_id
3470 # Delegating everything except mix playlists to regular tab-based playlist URL
3471 playlist_url = urljoin(url, try_get(
3472 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3474 if playlist_url and playlist_url != url:
3475 return self.url_result(
3476 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3479 return self.playlist_result(
3480 self._extract_mix_playlist(playlist, playlist_id, data, webpage),
3481 playlist_id=playlist_id, playlist_title=title)
3484 def _extract_alerts(data):
3485 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
3486 if not isinstance(alert_dict, dict):
3488 for alert in alert_dict.values():
3489 alert_type = alert.get('type')
3492 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str) or ''
3494 yield alert_type, message
3495 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
3496 message += try_get(run, lambda x: x['text'], compat_str)
3498 yield alert_type, message
3500 def _report_alerts(self, alerts, expected=True):
3503 for alert_type, alert_message in alerts:
3504 if alert_type.lower() == 'error':
3505 errors.append([alert_type, alert_message])
3507 warnings.append([alert_type, alert_message])
3509 for alert_type, alert_message in (warnings + errors[:-1]):
3510 self.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3512 raise ExtractorError('YouTube said: %s' % errors[-1][1], expected=expected)
3514 def _extract_and_report_alerts(self, data, *args, **kwargs):
3515 return self._report_alerts(self._extract_alerts(data), *args, **kwargs)
3517 def _reload_with_unavailable_videos(self, item_id, data, webpage):
3519 Get playlist with unavailable videos if the 'show unavailable videos' button exists.
3521 sidebar_renderer = try_get(
3522 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3523 if not sidebar_renderer:
3525 browse_id = params = None
3526 for item in sidebar_renderer:
3527 if not isinstance(item, dict):
3529 renderer = item.get('playlistSidebarPrimaryInfoRenderer')
3530 menu_renderer = try_get(
3531 renderer, lambda x: x['menu']['menuRenderer']['items'], list) or []
3532 for menu_item in menu_renderer:
3533 if not isinstance(menu_item, dict):
3535 nav_item_renderer = menu_item.get('menuNavigationItemRenderer')
3537 nav_item_renderer, lambda x: x['text']['simpleText'], compat_str)
3538 if not text or text.lower() != 'show unavailable videos':
3540 browse_endpoint = try_get(
3541 nav_item_renderer, lambda x: x['navigationEndpoint']['browseEndpoint'], dict) or {}
3542 browse_id = browse_endpoint.get('browseId')
3543 params = browse_endpoint.get('params')
3546 ytcfg = self._extract_ytcfg(item_id, webpage)
3547 headers = self._generate_api_headers(
3548 ytcfg, account_syncid=self._extract_account_syncid(ytcfg),
3549 identity_token=self._extract_identity_token(webpage, item_id=item_id),
3550 visitor_data=try_get(
3551 self._extract_context(ytcfg), lambda x: x['client']['visitorData'], compat_str))
3553 'params': params or 'wgYCCAA=',
3554 'browseId': browse_id or 'VL%s' % item_id
3556 return self._extract_response(
3557 item_id=item_id, headers=headers, query=query,
3558 check_get_keys='contents', fatal=False,
3559 note='Downloading API JSON with unavailable videos')
3561 def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
3562 ytcfg=None, check_get_keys=None, ep='browse', fatal=True):
3566 retries = self.get_param('extractor_retries', 3)
3567 if check_get_keys is None:
3569 while count < retries:
3572 self.report_warning('%s. Retrying ...' % last_error)
3574 response = self._call_api(
3575 ep=ep, fatal=True, headers=headers,
3576 video_id=item_id, query=query,
3577 context=self._extract_context(ytcfg),
3578 api_key=self._extract_api_key(ytcfg),
3579 note='%s%s' % (note, ' (retry #%d)' % count if count else ''))
3580 except ExtractorError as e:
3581 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
3582 # Downloading page may result in intermittent 5xx HTTP error
3583 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
3584 last_error = 'HTTP Error %s' % e.cause.code
3590 self.report_warning(error_to_compat_str(e))
3594 # Youtube may send alerts if there was an issue with the continuation page
3595 self._extract_and_report_alerts(response, expected=False)
3596 if not check_get_keys or dict_get(response, check_get_keys):
3598 # Youtube sometimes sends incomplete data
3599 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
3600 last_error = 'Incomplete data received'
3601 if count >= retries:
3603 raise ExtractorError(last_error)
3605 self.report_warning(last_error)
3609 def _extract_webpage(self, url, item_id):
3610 retries = self.get_param('extractor_retries', 3)
3612 last_error = 'Incomplete yt initial data recieved'
3613 while count < retries:
3615 # Sometimes youtube returns a webpage with incomplete ytInitialData
3616 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3618 self.report_warning('%s. Retrying ...' % last_error)
3619 webpage = self._download_webpage(
3621 'Downloading webpage%s' % (' (retry #%d)' % count if count else ''))
3622 data = self._extract_yt_initial_data(item_id, webpage)
3623 if data.get('contents') or data.get('currentVideoEndpoint'):
3625 # Extract alerts here only when there is error
3626 self._extract_and_report_alerts(data)
3627 if count >= retries:
3628 raise ExtractorError(last_error)
3629 return webpage, data
3632 def _smuggle_data(entries, data):
3633 for entry in entries:
3635 entry['url'] = smuggle_url(entry['url'], data)
3638 def _real_extract(self, url):
3639 url, smuggled_data = unsmuggle_url(url, {})
3640 if self.is_music_url(url):
3641 smuggled_data['is_music_url'] = True
3642 info_dict = self.__real_extract(url, smuggled_data)
3643 if info_dict.get('entries'):
3644 info_dict['entries'] = self._smuggle_data(info_dict['entries'], smuggled_data)
3647 _url_re = re.compile(r'(?P<pre>%s)(?(channel_type)(?P<tab>/\w+))?(?P<post>.*)$' % _VALID_URL)
3649 def __real_extract(self, url, smuggled_data):
3650 item_id = self._match_id(url)
3651 url = compat_urlparse.urlunparse(
3652 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3653 compat_opts = self.get_param('compat_opts', [])
3656 mobj = self._url_re.match(url).groupdict()
3657 mobj.update((k, '') for k, v in mobj.items() if v is None)
3660 mobj = get_mobj(url)
3661 # Youtube returns incomplete data if tabname is not lower case
3662 pre, tab, post, is_channel = mobj['pre'], mobj['tab'].lower(), mobj['post'], not mobj['not_channel']
3665 if smuggled_data.get('is_music_url'):
3666 if item_id[:2] == 'VL':
3667 # Youtube music VL channels have an equivalent playlist
3668 item_id = item_id[2:]
3669 pre, tab, post, is_channel = 'https://www.youtube.com/playlist?list=%s' % item_id, '', '', False
3670 elif item_id[:2] == 'MP':
3671 # Youtube music albums (/channel/MP...) have a OLAK playlist that can be extracted from the webpage
3672 item_id = self._search_regex(
3673 r'\\x22audioPlaylistId\\x22:\\x22([0-9A-Za-z_-]+)\\x22',
3674 self._download_webpage('https://music.youtube.com/channel/%s' % item_id, item_id),
3676 pre, tab, post, is_channel = 'https://www.youtube.com/playlist?list=%s' % item_id, '', '', False
3677 elif mobj['channel_type'] == 'browse':
3678 # Youtube music /browse/ should be changed to /channel/
3679 pre = 'https://www.youtube.com/channel/%s' % item_id
3680 if is_channel and not tab and 'no-youtube-channel-redirect' not in compat_opts:
3681 # Home URLs should redirect to /videos/
3682 self.report_warning(
3683 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3684 'To download only the videos in the home page, add a "/featured" to the URL')
3687 url = ''.join((pre, tab, post))
3688 mobj = get_mobj(url)
3690 # Handle both video/playlist URLs
3692 video_id = qs.get('v', [None])[0]
3693 playlist_id = qs.get('list', [None])[0]
3695 if not video_id and mobj['not_channel'].startswith('watch'):
3697 # If there is neither video or playlist ids, youtube redirects to home page, which is undesirable
3698 raise ExtractorError('Unable to recognize tab page')
3699 # Common mistake: https://www.youtube.com/watch?list=playlist_id
3700 self.report_warning('A video URL was given without video ID. Trying to download playlist %s' % playlist_id)
3701 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3702 mobj = get_mobj(url)
3704 if video_id and playlist_id:
3705 if self.get_param('noplaylist'):
3706 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3707 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3708 self.to_screen('Downloading playlist %s; add --no-playlist to just download video %s' % (playlist_id, video_id))
3710 webpage, data = self._extract_webpage(url, item_id)
3713 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3715 selected_tab = self._extract_selected_tab(tabs)
3716 tab_name = selected_tab.get('title', '')
3717 if 'no-youtube-channel-redirect' not in compat_opts:
3718 if mobj['tab'] == '/live':
3719 # Live tab should have redirected to the video
3720 raise ExtractorError('The channel is not currently live', expected=True)
3721 if mobj['tab'] == '/videos' and tab_name.lower() != mobj['tab'][1:]:
3722 if not mobj['not_channel'] and item_id[:2] == 'UC':
3723 # Topic channels don't have /videos. Use the equivalent playlist instead
3724 self.report_warning('The URL does not have a %s tab. Trying to redirect to playlist UU%s instead' % (mobj['tab'][1:], item_id[2:]))
3725 pl_id = 'UU%s' % item_id[2:]
3726 pl_url = 'https://www.youtube.com/playlist?list=%s%s' % (pl_id, mobj['post'])
3728 pl_webpage, pl_data = self._extract_webpage(pl_url, pl_id)
3729 for alert_type, alert_message in self._extract_alerts(pl_data):
3730 if alert_type == 'error':
3731 raise ExtractorError('Youtube said: %s' % alert_message)
3732 item_id, url, webpage, data = pl_id, pl_url, pl_webpage, pl_data
3733 except ExtractorError:
3734 self.report_warning('The playlist gave error. Falling back to channel URL')
3736 self.report_warning('The URL does not have a %s tab. %s is being downloaded instead' % (mobj['tab'][1:], tab_name))
3738 self.write_debug('Final URL: %s' % url)
3740 # YouTube sometimes provides a button to reload playlist with unavailable videos.
3741 if 'no-youtube-unavailable-videos' not in compat_opts:
3742 data = self._reload_with_unavailable_videos(item_id, data, webpage) or data
3743 self._extract_and_report_alerts(data)
3746 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3748 return self._extract_from_tabs(item_id, webpage, data, tabs)
3751 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3753 return self._extract_from_playlist(item_id, url, data, playlist, webpage)
3756 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3757 compat_str) or video_id
3759 if mobj['tab'] != '/live': # live tab is expected to redirect to video
3760 self.report_warning('Unable to recognize playlist. Downloading just video %s' % video_id)
3761 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3763 raise ExtractorError('Unable to recognize tab page')
3766 class YoutubePlaylistIE(InfoExtractor):
3767 IE_DESC = 'YouTube.com playlists'
3768 _VALID_URL = r'''(?x
)(?
:
3773 youtube(?
:kids
)?\
.com|
3778 (?P
<id>%(playlist_id)s)
3779 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3780 IE_NAME = 'youtube:playlist'
3782 'note': 'issue #673',
3783 'url': 'PLBB231211A4F62143',
3785 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3786 'id': 'PLBB231211A4F62143',
3787 'uploader': 'Wickydoo',
3788 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3790 'playlist_mincount': 29,
3792 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3794 'title': 'YDL_safe_search',
3795 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3797 'playlist_count': 2,
3798 'skip': 'This playlist is private',
3801 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3802 'playlist_count': 4,
3805 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3806 'uploader': 'milan',
3807 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3810 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3811 'playlist_mincount': 982,
3813 'title': '2018 Chinese New Singles (11/6 updated)',
3814 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3816 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3819 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3820 'only_matching': True,
3822 # music album playlist
3823 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3824 'only_matching': True,
3828 def suitable(cls, url):
3829 if YoutubeTabIE.suitable(url):
3831 # Hack for lazy extractors until more generic solution is implemented
3833 from .youtube import parse_qs
3835 if qs.get('v', [None])[0]:
3837 return super(YoutubePlaylistIE, cls).suitable(url)
3839 def _real_extract(self, url):
3840 playlist_id = self._match_id(url)
3841 is_music_url = YoutubeBaseInfoExtractor.is_music_url(url)
3842 url = update_url_query(
3843 'https://www.youtube.com/playlist',
3844 parse_qs(url) or {'list': playlist_id})
3846 url = smuggle_url(url, {'is_music_url': True})
3847 return self.url_result(url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3850 class YoutubeYtBeIE(InfoExtractor):
3851 IE_DESC = 'youtu.be'
3852 _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}
3854 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3856 'id': 'yeWKywCrFtk',
3858 'title': 'Small Scale Baler and Braiding Rugs',
3859 'uploader': 'Backus-Page House Museum',
3860 'uploader_id': 'backuspagemuseum',
3861 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3862 'upload_date': '20161008',
3863 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3864 'categories': ['Nonprofits & Activism'],
3867 'dislike_count': int,
3871 'skip_download': True,
3874 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3875 'only_matching': True,
3878 def _real_extract(self, url):
3879 mobj = re.match(self._VALID_URL, url)
3880 video_id = mobj.group('id')
3881 playlist_id = mobj.group('playlist_id')
3882 return self.url_result(
3883 update_url_query('https://www.youtube.com/watch', {
3885 'list': playlist_id,
3886 'feature': 'youtu.be',
3887 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3890 class YoutubeYtUserIE(InfoExtractor):
3891 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3892 _VALID_URL = r'ytuser:(?P<id>.+)'
3894 'url': 'ytuser:phihag',
3895 'only_matching': True,
3898 def _real_extract(self, url):
3899 user_id = self._match_id(url)
3900 return self.url_result(
3901 'https://www.youtube.com/user/%s' % user_id,
3902 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3905 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3906 IE_NAME = 'youtube:favorites'
3907 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3908 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3909 _LOGIN_REQUIRED = True
3912 'only_matching': True,
3914 'url': ':ytfavorites',
3915 'only_matching': True,
3918 def _real_extract(self, url):
3919 return self.url_result(
3920 'https://www.youtube.com/playlist?list=LL',
3921 ie=YoutubeTabIE.ie_key())
3924 class YoutubeSearchIE(SearchInfoExtractor, YoutubeTabIE):
3925 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3926 # there doesn't appear to be a real limit, for example if you search for
3927 # 'python' you get more than 8.000.000 results
3928 _MAX_RESULTS = float('inf')
3929 IE_NAME = 'youtube:search'
3930 _SEARCH_KEY = 'ytsearch'
3931 _SEARCH_PARAMS = None
3934 def _entries(self, query, n):
3935 data = {'query': query}
3936 if self._SEARCH_PARAMS:
3937 data['params'] = self._SEARCH_PARAMS
3939 for page_num in itertools.count(1):
3940 search = self._extract_response(
3941 item_id='query "%s" page %s' % (query, page_num), ep='search', query=data,
3942 check_get_keys=('contents', 'onResponseReceivedCommands')
3946 slr_contents = try_get(
3948 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3949 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3951 if not slr_contents:
3954 # Youtube sometimes adds promoted content to searches,
3955 # changing the index location of videos and token.
3956 # So we search through all entries till we find them.
3957 continuation_token = None
3958 for slr_content in slr_contents:
3959 if continuation_token is None:
3960 continuation_token = try_get(
3962 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3965 isr_contents = try_get(
3967 lambda x: x['itemSectionRenderer']['contents'],
3969 if not isr_contents:
3971 for content in isr_contents:
3972 if not isinstance(content, dict):
3974 video = content.get('videoRenderer')
3975 if not isinstance(video, dict):
3977 video_id = video.get('videoId')
3981 yield self._extract_video(video)
3986 if not continuation_token:
3988 data['continuation'] = continuation_token
3990 def _get_n_results(self, query, n):
3991 """Get a specified number of results for a query"""
3992 return self.playlist_result(self._entries(query, n), query)
3995 class YoutubeSearchDateIE(YoutubeSearchIE):
3996 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3997 _SEARCH_KEY = 'ytsearchdate'
3998 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3999 _SEARCH_PARAMS = 'CAI%3D'
4002 class YoutubeSearchURLIE(YoutubeSearchIE):
4003 IE_DESC = 'YouTube.com search URLs'
4004 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
4005 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
4006 # _MAX_RESULTS = 100
4008 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
4009 'playlist_mincount': 5,
4011 'title': 'youtube-dl test video',
4014 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
4015 'only_matching': True,
4019 def _make_valid_url(cls):
4020 return cls._VALID_URL
4022 def _real_extract(self, url):
4023 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
4024 query = (qs.get('search_query') or qs.get('q'))[0]
4025 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
4026 return self._get_n_results(query, self._MAX_RESULTS)
4029 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
4031 Base class for feed extractors
4032 Subclasses must define the _FEED_NAME property.
4034 _LOGIN_REQUIRED = True
4039 return 'youtube:%s' % self._FEED_NAME
4041 def _real_extract(self, url):
4042 return self.url_result(
4043 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
4044 ie=YoutubeTabIE.ie_key())
4047 class YoutubeWatchLaterIE(InfoExtractor):
4048 IE_NAME = 'youtube:watchlater'
4049 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
4050 _VALID_URL = r':ytwatchlater'
4052 'url': ':ytwatchlater',
4053 'only_matching': True,
4056 def _real_extract(self, url):
4057 return self.url_result(
4058 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
4061 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
4062 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
4063 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
4064 _FEED_NAME = 'recommended'
4067 'only_matching': True,
4069 'url': ':ytrecommended',
4070 'only_matching': True,
4072 'url': 'https://youtube.com',
4073 'only_matching': True,
4077 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
4078 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
4079 _VALID_URL = r':ytsub(?:scription)?s?'
4080 _FEED_NAME = 'subscriptions'
4083 'only_matching': True,
4085 'url': ':ytsubscriptions',
4086 'only_matching': True,
4090 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
4091 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
4092 _VALID_URL = r':ythis(?:tory)?'
4093 _FEED_NAME = 'history'
4095 'url': ':ythistory',
4096 'only_matching': True,
4100 class YoutubeTruncatedURLIE(InfoExtractor):
4101 IE_NAME = 'youtube:truncated_url'
4102 IE_DESC = False # Do not list
4103 _VALID_URL = r'''(?x
)
4105 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
4108 annotation_id
=annotation_
[^
&]+|
4114 attribution_link
\?a
=[^
&]+
4120 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
4121 'only_matching': True,
4123 'url': 'https://www.youtube.com/watch?',
4124 'only_matching': True,
4126 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
4127 'only_matching': True,
4129 'url': 'https://www.youtube.com/watch?feature=foo',
4130 'only_matching': True,
4132 'url': 'https://www.youtube.com/watch?hl=en-GB',
4133 'only_matching': True,
4135 'url': 'https://www.youtube.com/watch?t=2372',
4136 'only_matching': True,
4139 def _real_extract(self, url):
4140 raise ExtractorError(
4141 'Did you forget to quote the URL? Remember that & is a meta '
4142 'character in most shells, so you want to put the URL in quotes, '
4144 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
4145 ' or simply youtube-dl BaW_jenozKc .',
4149 class YoutubeTruncatedIDIE(InfoExtractor):
4150 IE_NAME = 'youtube:truncated_id'
4151 IE_DESC = False # Do not list
4152 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
4155 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
4156 'only_matching': True,
4159 def _real_extract(self, url):
4160 video_id = self._match_id(url)
4161 raise ExtractorError(
4162 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),