3 from __future__
import unicode_literals
14 from .common
import InfoExtractor
, SearchInfoExtractor
15 from ..compat
import (
21 compat_urllib_parse_unquote_plus
,
22 compat_urllib_parse_urlencode
,
23 compat_urllib_parse_urlparse
,
26 from ..jsinterp
import JSInterpreter
54 class YoutubeBaseInfoExtractor(InfoExtractor
):
55 """Provide base functions for Youtube extractors"""
56 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
57 _TWOFACTOR_URL
= 'https://accounts.google.com/signin/challenge'
59 _LOOKUP_URL
= 'https://accounts.google.com/_/signin/sl/lookup'
60 _CHALLENGE_URL
= 'https://accounts.google.com/_/signin/sl/challenge'
61 _TFA_URL
= 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
64 r
'channel|c|user|playlist|watch|w|v|embed|e|watch_popup|'
65 r
'movies|results|shared|hashtag|trending|feed|feeds|'
66 r
'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout')
68 _NETRC_MACHINE
= 'youtube'
69 # If True it will raise an error if no login info is provided
70 _LOGIN_REQUIRED
= False
72 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
74 def _ids_to_results(self
, ids
):
76 self
.url_result(vid_id
, 'Youtube', video_id
=vid_id
)
81 Attempt to log in to YouTube.
82 True is returned if successful or skipped.
83 False is returned if login failed.
85 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
87 username
, password
= self
._get
_login
_info
()
88 # No authentication to be performed
90 if self
._LOGIN
_REQUIRED
and self
._downloader
.params
.get('cookiefile') is None:
91 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
92 # if self._downloader.params.get('cookiefile'): # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
93 # self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
96 login_page
= self
._download
_webpage
(
97 self
._LOGIN
_URL
, None,
98 note
='Downloading login page',
99 errnote
='unable to fetch login page', fatal
=False)
100 if login_page
is False:
103 login_form
= self
._hidden
_inputs
(login_page
)
105 def req(url
, f_req
, note
, errnote
):
106 data
= login_form
.copy()
109 'checkConnection': 'youtube',
110 'checkedDomains': 'youtube',
112 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
113 'f.req': json
.dumps(f_req
),
114 'flowName': 'GlifWebSignIn',
115 'flowEntry': 'ServiceLogin',
116 # TODO: reverse actual botguard identifier generation algo
117 'bgRequest': '["identifier",""]',
119 return self
._download
_json
(
120 url
, None, note
=note
, errnote
=errnote
,
121 transform_source
=lambda s
: re
.sub(r
'^[^[]*', '', s
),
123 data
=urlencode_postdata(data
), headers
={
124 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
125 'Google-Accounts-XSRF': 1,
129 self
._downloader
.report_warning(message
)
133 None, [], None, 'US', None, None, 2, False, True,
137 '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',
139 1, [None, None, []], None, None, None, True
144 lookup_results
= req(
145 self
._LOOKUP
_URL
, lookup_req
,
146 'Looking up account info', 'Unable to look up account info')
148 if lookup_results
is False:
151 user_hash
= try_get(lookup_results
, lambda x
: x
[0][2], compat_str
)
153 warn('Unable to extract user hash')
158 None, 1, None, [1, None, None, None, [password
, None, True]],
160 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],
161 1, [None, None, []], None, None, None, True
164 challenge_results
= req(
165 self
._CHALLENGE
_URL
, challenge_req
,
166 'Logging in', 'Unable to log in')
168 if challenge_results
is False:
171 login_res
= try_get(challenge_results
, lambda x
: x
[0][5], list)
173 login_msg
= try_get(login_res
, lambda x
: x
[5], compat_str
)
175 'Unable to login: %s' % 'Invalid password'
176 if login_msg
== 'INCORRECT_ANSWER_ENTERED' else login_msg
)
179 res
= try_get(challenge_results
, lambda x
: x
[0][-1], list)
181 warn('Unable to extract result entry')
184 login_challenge
= try_get(res
, lambda x
: x
[0][0], list)
186 challenge_str
= try_get(login_challenge
, lambda x
: x
[2], compat_str
)
187 if challenge_str
== 'TWO_STEP_VERIFICATION':
188 # SEND_SUCCESS - TFA code has been successfully sent to phone
189 # QUOTA_EXCEEDED - reached the limit of TFA codes
190 status
= try_get(login_challenge
, lambda x
: x
[5], compat_str
)
191 if status
== 'QUOTA_EXCEEDED':
192 warn('Exceeded the limit of TFA codes, try later')
195 tl
= try_get(challenge_results
, lambda x
: x
[1][2], compat_str
)
197 warn('Unable to extract TL')
200 tfa_code
= self
._get
_tfa
_info
('2-step verification code')
204 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
205 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
208 tfa_code
= remove_start(tfa_code
, 'G-')
211 user_hash
, None, 2, None,
213 9, None, None, None, None, None, None, None,
214 [None, tfa_code
, True, 2]
218 self
._TFA
_URL
.format(tl
), tfa_req
,
219 'Submitting TFA code', 'Unable to submit TFA code')
221 if tfa_results
is False:
224 tfa_res
= try_get(tfa_results
, lambda x
: x
[0][5], list)
226 tfa_msg
= try_get(tfa_res
, lambda x
: x
[5], compat_str
)
228 'Unable to finish TFA: %s' % 'Invalid TFA code'
229 if tfa_msg
== 'INCORRECT_ANSWER_ENTERED' else tfa_msg
)
232 check_cookie_url
= try_get(
233 tfa_results
, lambda x
: x
[0][-1][2], compat_str
)
236 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
237 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
238 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
240 challenge
= CHALLENGES
.get(
242 '%s returned error %s.' % (self
.IE_NAME
, challenge_str
))
243 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge
)
246 check_cookie_url
= try_get(res
, lambda x
: x
[2], compat_str
)
248 if not check_cookie_url
:
249 warn('Unable to extract CheckCookie URL')
252 check_cookie_results
= self
._download
_webpage
(
253 check_cookie_url
, None, 'Checking cookie', fatal
=False)
255 if check_cookie_results
is False:
258 if 'https://myaccount.google.com/' not in check_cookie_results
:
259 warn('Unable to log in')
264 def _initialize_consent(self
):
265 cookies
= self
._get
_cookies
('https://www.youtube.com/')
266 if cookies
.get('__Secure-3PSID'):
269 consent
= cookies
.get('CONSENT')
271 if 'YES' in consent
.value
:
273 consent_id
= self
._search
_regex
(
274 r
'PENDING\+(\d+)', consent
.value
, 'consent', default
=None)
276 consent_id
= random
.randint(100, 999)
277 self
._set
_cookie
('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id
)
279 def _real_initialize(self
):
280 self
._initialize
_consent
()
281 if self
._downloader
is None:
283 if not self
._login
():
286 _YT_WEB_CLIENT_VERSION
= '2.20210301.08.00'
287 _DEFAULT_API_DATA
= {
291 'clientVersion': _YT_WEB_CLIENT_VERSION
,
296 _DEFAULT_BASIC_API_HEADERS
= {
297 'X-YouTube-Client-Name': '1',
298 'X-YouTube-Client-Version': _YT_WEB_CLIENT_VERSION
301 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
302 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
303 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
305 def _generate_sapisidhash_header(self):
306 sapisid_cookie = self._get_cookies('https://www.youtube.com').get('SAPISID')
307 if sapisid_cookie is None:
309 time_now = round(time.time())
310 sapisidhash = hashlib.sha1((str(time_now) + " " + sapisid_cookie.value + " " + "https
://www
.youtube
.com
").encode("utf
-8")).hexdigest()
311 return "SAPISIDHASH
%s_%s" % (time_now, sapisidhash)
313 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
314 note='Downloading API JSON', errnote='Unable to download API page'):
315 data = self._DEFAULT_API_DATA.copy()
317 headers = headers or {}
318 headers.update({'content-type': 'application/json'})
319 auth = self._generate_sapisidhash_header()
321 headers.update({'Authorization': auth, 'X-Origin': 'https://www.youtube.com'})
322 return self._download_json(
323 'https://www.youtube.com/youtubei/v1/%s' % ep,
324 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
325 data=json.dumps(data).encode('utf8'), headers=headers,
326 query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
328 def _extract_yt_initial_data(self, video_id, webpage):
329 return self._parse_json(
331 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
332 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
335 def _extract_identity_token(self, webpage, item_id):
336 ytcfg = self._extract_ytcfg(item_id, webpage)
338 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
341 return self._search_regex(
342 r'\bID_TOKEN["\']\s
*:\s
*["\'](.+?)["\']', webpage,
343 'identity token
', default=None)
346 def _extract_account_syncid(data):
347 """Extract syncId required to download private playlists of secondary channels"""
349 try_get(data, lambda x: x['responseContext
']['mainAppWebResponseContext
']['datasyncId
'], compat_str)
351 if len(sync_ids) >= 2 and sync_ids[1]:
352 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
353 # and just "user_syncid||" for primary channel. We only want the channel_syncid
356 def _extract_ytcfg(self, video_id, webpage):
357 return self._parse_json(
359 r'ytcfg\
.set\s
*\
(\s
*({.+?}
)\s
*\
)\s
*;', webpage, 'ytcfg
',
360 default='{}'), video_id, fatal=False)
362 def _extract_video(self, renderer):
363 video_id = renderer.get('videoId
')
366 (lambda x: x['title
']['runs
'][0]['text
'],
367 lambda x: x['title
']['simpleText
']), compat_str)
368 description = try_get(
369 renderer, lambda x: x['descriptionSnippet
']['runs
'][0]['text
'],
371 duration = parse_duration(try_get(
372 renderer, lambda x: x['lengthText
']['simpleText
'], compat_str))
373 view_count_text = try_get(
374 renderer, lambda x: x['viewCountText
']['simpleText
'], compat_str) or ''
375 view_count = str_to_int(self._search_regex(
376 r'^
([\d
,]+)', re.sub(r'\s
', '', view_count_text),
377 'view count
', default=None))
380 (lambda x: x['ownerText
']['runs
'][0]['text
'],
381 lambda x: x['shortBylineText
']['runs
'][0]['text
']), compat_str)
383 '_type
': 'url_transparent
',
384 'ie_key
': YoutubeIE.ie_key(),
388 'description
': description,
389 'duration
': duration,
390 'view_count
': view_count,
391 'uploader
': uploader,
395 class YoutubeIE(YoutubeBaseInfoExtractor):
396 IE_DESC = 'YouTube
.com
'
398 # invidious-redirect websites
399 r'(?
:www\
.)?redirect\
.invidious\
.io
',
400 r'(?
:(?
:www|dev
)\
.)?invidio\
.us
',
401 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
402 r'(?
:www\
.)?invidious\
.pussthecat\
.org
',
403 r'(?
:www\
.)?invidious\
.048596\
.xyz
',
404 r'(?
:www\
.)?invidious\
.zee\
.li
',
405 r'(?
:www\
.)?vid\
.puffyan\
.us
',
406 r'(?
:(?
:www|au
)\
.)?ytprivate\
.com
',
407 r'(?
:www\
.)?invidious\
.namazso\
.eu
',
408 r'(?
:www\
.)?invidious\
.ethibox\
.fr
',
409 r'(?
:www\
.)?inv\
.skyn3t\
.in',
410 r'(?
:www\
.)?invidious\
.himiko\
.cloud
',
411 r'(?
:www\
.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\
.onion
',
412 r'(?
:www\
.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\
.onion
',
413 r'(?
:www\
.)?invidious\
.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\
.onion
',
414 r'(?
:www\
.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\
.onion
',
415 # youtube-dl invidious instances list
416 r'(?
:(?
:www|no
)\
.)?invidiou\
.sh
',
417 r'(?
:(?
:www|fi
)\
.)?invidious\
.snopyta\
.org
',
418 r'(?
:www\
.)?invidious\
.kabi\
.tk
',
419 r'(?
:www\
.)?invidious\
.13ad\
.de
',
420 r'(?
:www\
.)?invidious\
.mastodon\
.host
',
421 r'(?
:www\
.)?invidious\
.zapashcanon\
.fr
',
422 r'(?
:www\
.)?invidious\
.kavin\
.rocks
',
423 r'(?
:www\
.)?invidious\
.tube
',
424 r'(?
:www\
.)?invidiou\
.site
',
425 r'(?
:www\
.)?invidious\
.site
',
426 r'(?
:www\
.)?invidious\
.xyz
',
427 r'(?
:www\
.)?invidious\
.nixnet\
.xyz
',
428 r'(?
:www\
.)?invidious\
.drycat\
.fr
',
429 r'(?
:www\
.)?tube\
.poal\
.co
',
430 r'(?
:www\
.)?tube\
.connect\
.cafe
',
431 r'(?
:www\
.)?vid\
.wxzm\
.sx
',
432 r'(?
:www\
.)?vid\
.mint\
.lgbt
',
433 r'(?
:www\
.)?yewtu\
.be
',
434 r'(?
:www\
.)?yt\
.elukerio\
.org
',
435 r'(?
:www\
.)?yt\
.lelux\
.fi
',
436 r'(?
:www\
.)?invidious\
.ggc
-project\
.de
',
437 r'(?
:www\
.)?yt\
.maisputain\
.ovh
',
438 r'(?
:www\
.)?invidious\
.toot\
.koeln
',
439 r'(?
:www\
.)?invidious\
.fdn\
.fr
',
440 r'(?
:www\
.)?watch\
.nettohikari\
.com
',
441 r'(?
:www\
.)?kgg2m7yk5aybusll\
.onion
',
442 r'(?
:www\
.)?qklhadlycap4cnod\
.onion
',
443 r'(?
:www\
.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\
.onion
',
444 r'(?
:www\
.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\
.onion
',
445 r'(?
:www\
.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\
.onion
',
446 r'(?
:www\
.)?invidious\
.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\
.onion
',
447 r'(?
:www\
.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\
.b32\
.i2p
',
448 r'(?
:www\
.)?
4l2dgddgsrkf
2ous
66i
6seeyi
6etzfgrue
332grh
2n
7madpwopotugyd\
.onion
',
450 _VALID_URL = r"""(?x)^
452 (?:https?://|//) # http(s):// or protocol-independent URL
453 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
454 (?:www\.)?deturl\.com/www\.youtube\.com|
455 (?:www\.)?pwnyoutube\.com|
456 (?:www\.)?hooktube\.com|
457 (?:www\.)?yourepeat\.com|
460 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
461 (?:.*?\#/)? # handle anchor (#/) redirect urls
462 (?: # the various things that can precede the ID:
463 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
464 |(?: # or the v= param in all its forms
465 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
466 (?:\?|\#!?) # the params delimiter ? or # or #!
467 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
472 youtu\.be| # just youtu.be/xxxx
473 vid\.plus| # or vid.plus/xxxx
474 zwearz\.com/watch| # or zwearz.com/watch/xxxx
477 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
479 )? # all until now is optional -> you can pass the naked ID
480 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
483 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
484 WL # WL are handled by the watch later IE
487 (?(1).+)? # if we found the ID, everything can follow
489 'playlist_id
': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE,
490 'invidious
': '|
'.join(_INVIDIOUS_SITES),
493 r'/s
/player
/(?P
<id>[a
-zA
-Z0
-9_-]{8,}
)/player
',
494 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$
',
495 r'\b(?P
<id>vfl
[a
-zA
-Z0
-9_-]+)\b.*?\
.js$
',
498 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
499 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
500 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
501 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
502 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
503 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
504 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
505 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
506 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
507 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
508 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
509 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
510 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
511 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
512 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
513 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
514 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
515 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
519 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
520 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
521 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
522 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
523 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
524 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
525 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
527 # Apple HTTP Live Streaming
528 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
529 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
530 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
531 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
532 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
533 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
534 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
535 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
538 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
539 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
540 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
541 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
542 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
543 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
544 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
545 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
546 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
547 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
548 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
549 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
552 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
553 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
554 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
555 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
556 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
557 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
558 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
561 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
562 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
563 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
564 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
565 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
566 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
567 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
568 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
569 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
570 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
571 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
572 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
573 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
574 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
575 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
576 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
577 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
578 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
579 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
580 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
581 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
582 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
585 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
586 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
588 # Dash webm audio with opus inside
589 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
590 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
591 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
594 '_rtmp
': {'protocol': 'rtmp'},
596 # av01 video only formats sometimes served with "unknown" codecs
597 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
598 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
599 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
600 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
602 _SUBTITLE_FORMATS = ('json3
', 'srv1
', 'srv2
', 'srv3
', 'ttml
', 'vtt
')
609 'url
': 'https
://www
.youtube
.com
/watch?v
=BaW_jenozKc
&t
=1s
&end
=9',
613 'title
': 'youtube
-dl test video
"\'/\\ä↭𝕐',
614 'uploader': 'Philipp Hagemeister',
615 'uploader_id': 'phihag',
616 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
617 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
618 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
619 'upload_date': '20121002',
620 '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 .',
621 'categories
': ['Science
& Technology
'],
622 'tags
': ['youtube
-dl
'],
626 'dislike_count
': int,
632 'url
': '//www
.YouTube
.com
/watch?v
=yZIXLfi8CZQ
',
633 'note
': 'Embed
-only
video (#1746)',
637 'upload_date': '20120608',
638 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
639 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
640 'uploader': 'SET India',
641 'uploader_id': 'setindia',
642 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/setindia',
645 'skip': 'Private video',
648 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
649 'note': 'Use the first video ID in the URL',
653 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
654 'uploader': 'Philipp Hagemeister',
655 'uploader_id': 'phihag',
656 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
657 'upload_date': '20121002',
658 '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 .',
659 'categories': ['Science & Technology'],
660 'tags': ['youtube-dl'],
664 'dislike_count': int,
667 'skip_download': True,
671 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
672 'note': '256k DASH audio (format 141) via DASH manifest',
676 'upload_date': '20121002',
677 'uploader_id': '8KVIDEO',
678 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
680 'uploader': '8KVIDEO',
681 'title': 'UHDTV TEST 8K VIDEO.mp4'
684 'youtube_include_dash_manifest': True,
687 'skip': 'format 141 not served anymore',
689 # DASH manifest with encrypted signature
691 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
695 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
696 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
698 'uploader': 'AfrojackVEVO',
699 'uploader_id': 'AfrojackVEVO',
700 'upload_date': '20131011',
704 'youtube_include_dash_manifest': True,
705 'format': '141/bestaudio[ext=m4a]',
710 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
715 'upload_date': '20100909',
716 'uploader': 'Amazing Atheist',
717 'uploader_id': 'TheAmazingAtheist',
718 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
719 'title': 'Burning Everyone\'s Koran',
720 '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',
723 # Normal age-gate video (embed allowed)
725 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
729 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
730 'description': r
're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
732 'uploader': 'The Witcher',
733 'uploader_id': 'WitcherGame',
734 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
735 'upload_date': '20140605',
739 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
740 # YouTube Red ad is not captured for creator
742 'url': '__2ABJjxzNo',
747 'upload_date': '20100430',
748 'uploader_id': 'deadmau5',
749 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/deadmau5',
750 'creator': 'deadmau5',
751 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
752 'uploader': 'deadmau5',
753 'title': 'Deadmau5 - Some Chords (HD)',
754 'alt_title': 'Some Chords',
756 'expected_warnings': [
757 'DASH manifest missing',
760 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
762 'url': 'lqQg6PlCWgI',
767 'upload_date': '20150827',
768 'uploader_id': 'olympic',
769 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/olympic',
770 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
771 'uploader': 'Olympic',
772 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
775 'skip_download': 'requires avconv',
780 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
784 'stretched_ratio': 16 / 9.,
786 'upload_date': '20110310',
787 'uploader_id': 'AllenMeow',
788 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
789 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
791 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
794 # url_encoded_fmt_stream_map is empty string
796 'url': 'qEJwOuvDf7I',
800 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
802 'upload_date': '20150404',
803 'uploader_id': 'spbelect',
804 'uploader': 'Наблюдатели Петербурга',
807 'skip_download': 'requires avconv',
809 'skip': 'This live event has ended.',
811 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
813 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
817 'title': 'md5:7b81415841e02ecd4313668cde88737a',
818 'description': 'md5:116377fd2963b81ec4ce64b542173306',
820 'upload_date': '20150625',
821 'uploader_id': 'dorappi2000',
822 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
823 'uploader': 'dorappi2000',
824 'formats': 'mincount:31',
826 'skip': 'not actual anymore',
828 # DASH manifest with segment_list
830 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
831 'md5': '8ce563a1d667b599d21064e982ab9e31',
835 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
836 'uploader': 'Airtek',
837 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
838 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
839 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
842 'youtube_include_dash_manifest': True,
843 'format': '135', # bestvideo
845 'skip': 'This live event has ended.',
848 # Multifeed videos (multiple cameras), URL is for Main Camera
849 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
852 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
853 'description': 'md5:e03b909557865076822aa169218d6a5d',
859 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
860 'description': 'md5:e03b909557865076822aa169218d6a5d',
862 'upload_date': '20161111',
863 'uploader': 'Team PGP',
864 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
865 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
871 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
872 'description': 'md5:e03b909557865076822aa169218d6a5d',
874 'upload_date': '20161111',
875 'uploader': 'Team PGP',
876 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
877 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
883 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
884 'description': 'md5:e03b909557865076822aa169218d6a5d',
886 'upload_date': '20161111',
887 'uploader': 'Team PGP',
888 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
889 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
895 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
896 'description': 'md5:e03b909557865076822aa169218d6a5d',
898 'upload_date': '20161111',
899 'uploader': 'Team PGP',
900 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
901 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
905 'skip_download': True,
909 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
910 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
913 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
916 'skip': 'Not multifeed anymore',
919 'url': 'https://vid.plus/FlRa-iH7PGw',
920 'only_matching': True,
923 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
924 'only_matching': True,
927 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
928 # Also tests cut-off URL expansion in video description (see
929 # https://github.com/ytdl-org/youtube-dl/issues/1892,
930 # https://github.com/ytdl-org/youtube-dl/issues/8164)
931 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
935 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
936 'alt_title': 'Dark Walk - Position Music',
937 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
939 'upload_date': '20151119',
940 'uploader_id': 'IronSoulElf',
941 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
942 'uploader': 'IronSoulElf',
943 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
944 'track': 'Dark Walk - Position Music',
945 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
946 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
949 'skip_download': True,
953 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
954 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
955 'only_matching': True,
958 # Video with yt:stretch=17:0
959 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
963 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
964 'description': 'md5:ee18a25c350637c8faff806845bddee9',
965 'upload_date': '20151107',
966 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
967 'uploader': 'CH GAMER DROID',
970 'skip_download': True,
972 'skip': 'This video does not exist.',
975 # Video licensed under Creative Commons
976 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
980 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
981 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
983 'upload_date': '20150127',
984 'uploader_id': 'BerkmanCenter',
985 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
986 'uploader': 'The Berkman Klein Center for Internet & Society',
987 'license': 'Creative Commons Attribution license (reuse allowed)',
990 'skip_download': True,
994 # Channel-like uploader_url
995 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
999 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1000 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1002 'upload_date': '20151119',
1003 'uploader': 'Bernie Sanders',
1004 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1005 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
1006 'license': 'Creative Commons Attribution license (reuse allowed)',
1009 'skip_download': True,
1013 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
1014 'only_matching': True,
1017 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
1018 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1019 'only_matching': True,
1022 # Rental video preview
1023 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1025 'id': 'uGpuVWrhIzE',
1027 'title': 'Piku - Trailer',
1028 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1029 'upload_date': '20150811',
1030 'uploader': 'FlixMatrix',
1031 'uploader_id': 'FlixMatrixKaravan',
1032 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
1033 'license': 'Standard YouTube License',
1036 'skip_download': True,
1038 'skip': 'This video is not available.',
1041 # YouTube Red video with episode data
1042 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1044 'id': 'iqKdEhx-dD4',
1046 'title': 'Isolation - Mind Field (Ep 1)',
1047 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1049 'upload_date': '20170118',
1050 'uploader': 'Vsauce',
1051 'uploader_id': 'Vsauce',
1052 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1053 'series': 'Mind Field',
1055 'episode_number': 1,
1058 'skip_download': True,
1060 'expected_warnings': [
1061 'Skipping DASH manifest',
1065 # The following content has been identified by the YouTube community
1066 # as inappropriate or offensive to some audiences.
1067 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1069 'id': '6SJNVb0GnPI',
1071 'title': 'Race Differences in Intelligence',
1072 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1074 'upload_date': '20140124',
1075 'uploader': 'New Century Foundation',
1076 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1077 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1080 'skip_download': True,
1082 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1086 'url': '1t24XAntNCY',
1087 'only_matching': True,
1090 # geo restricted to JP
1091 'url': 'sJL6WA-aGkQ',
1092 'only_matching': True,
1095 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1096 'only_matching': True,
1099 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1100 'only_matching': True,
1103 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1104 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1105 'only_matching': True,
1109 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1110 'only_matching': True,
1113 # Video with unsupported adaptive stream type formats
1114 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1116 'id': 'Z4Vy8R84T1U',
1118 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1119 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1121 'upload_date': '20130923',
1122 'uploader': 'Amelia Putri Harwita',
1123 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1124 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1125 'formats': 'maxcount:10',
1128 'skip_download': True,
1129 'youtube_include_dash_manifest': False,
1131 'skip': 'not actual anymore',
1134 # Youtube Music Auto-generated description
1135 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1137 'id': 'MgNrAu2pzNs',
1139 'title': 'Voyeur Girl',
1140 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1141 'upload_date': '20190312',
1142 'uploader': 'Stephen - Topic',
1143 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1144 'artist': 'Stephen',
1145 'track': 'Voyeur Girl',
1146 'album': 'it\'s too much love to know my dear',
1147 'release_date': '20190313',
1148 'release_year': 2019,
1151 'skip_download': True,
1155 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1156 'only_matching': True,
1159 # invalid -> valid video id redirection
1160 'url': 'DJztXj2GPfl',
1162 'id': 'DJztXj2GPfk',
1164 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1165 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1166 'upload_date': '20090125',
1167 'uploader': 'Prochorowka',
1168 'uploader_id': 'Prochorowka',
1169 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1170 'artist': 'Panjabi MC',
1171 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1172 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1175 'skip_download': True,
1177 'skip': 'Video unavailable',
1180 # empty description results in an empty string
1181 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1183 'id': 'x41yOUIvK2k',
1185 'title': 'IMG 3456',
1187 'upload_date': '20170613',
1188 'uploader_id': 'ElevageOrVert',
1189 'uploader': 'ElevageOrVert',
1192 'skip_download': True,
1196 # with '};' inside yt initial data (see [1])
1197 # see [2] for an example with '};' inside ytInitialPlayerResponse
1198 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1199 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1200 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1202 'id': 'CHqg6qOn4no',
1204 'title': 'Part 77 Sort a list of simple types in c#',
1205 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1206 'upload_date': '20130831',
1207 'uploader_id': 'kudvenkat',
1208 'uploader': 'kudvenkat',
1211 'skip_download': True,
1215 # another example of '};' in ytInitialData
1216 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1217 'only_matching': True,
1220 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1221 'only_matching': True,
1224 # https://github.com/ytdl-org/youtube-dl/pull/28094
1225 'url': 'OtqTfy26tG0',
1227 'id': 'OtqTfy26tG0',
1229 'title': 'Burn Out',
1230 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1231 'upload_date': '20141120',
1232 'uploader': 'The Cinematic Orchestra - Topic',
1233 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1234 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1235 'artist': 'The Cinematic Orchestra',
1236 'track': 'Burn Out',
1237 'album': 'Every Day',
1238 'release_data': None,
1239 'release_year': None,
1242 'skip_download': True,
1246 # controversial video, only works with bpctr when authenticated with cookies
1247 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1248 'only_matching': True,
1252 def __init__(self
, *args
, **kwargs
):
1253 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
1254 self
._code
_cache
= {}
1255 self
._player
_cache
= {}
1257 def _signature_cache_id(self
, example_sig
):
1258 """ Return a string representation of a signature """
1259 return '.'.join(compat_str(len(part
)) for part
in example_sig
.split('.'))
1262 def _extract_player_info(cls
, player_url
):
1263 for player_re
in cls
._PLAYER
_INFO
_RE
:
1264 id_m
= re
.search(player_re
, player_url
)
1268 raise ExtractorError('Cannot identify player %r' % player_url
)
1269 return id_m
.group('id')
1271 def _extract_signature_function(self
, video_id
, player_url
, example_sig
):
1272 player_id
= self
._extract
_player
_info
(player_url
)
1274 # Read from filesystem cache
1275 func_id
= 'js_%s_%s' % (
1276 player_id
, self
._signature
_cache
_id
(example_sig
))
1277 assert os
.path
.basename(func_id
) == func_id
1279 cache_spec
= self
._downloader
.cache
.load('youtube-sigfuncs', func_id
)
1280 if cache_spec
is not None:
1281 return lambda s
: ''.join(s
[i
] for i
in cache_spec
)
1283 if player_id
not in self
._code
_cache
:
1284 self
._code
_cache
[player_id
] = self
._download
_webpage
(
1285 player_url
, video_id
,
1286 note
='Downloading player ' + player_id
,
1287 errnote
='Download of %s failed' % player_url
)
1288 code
= self
._code
_cache
[player_id
]
1289 res
= self
._parse
_sig
_js
(code
)
1291 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1292 cache_res
= res(test_string
)
1293 cache_spec
= [ord(c
) for c
in cache_res
]
1295 self
._downloader
.cache
.store('youtube-sigfuncs', func_id
, cache_spec
)
1298 def _print_sig_code(self
, func
, example_sig
):
1299 def gen_sig_code(idxs
):
1300 def _genslice(start
, end
, step
):
1301 starts
= '' if start
== 0 else str(start
)
1302 ends
= (':%d' % (end
+ step
)) if end
+ step
>= 0 else ':'
1303 steps
= '' if step
== 1 else (':%d' % step
)
1304 return 's[%s%s%s]' % (starts
, ends
, steps
)
1307 # Quelch pyflakes warnings - start will be set when step is set
1308 start
= '(Never used)'
1309 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
1310 if step
is not None:
1311 if i
- prev
== step
:
1313 yield _genslice(start
, prev
, step
)
1316 if i
- prev
in [-1, 1]:
1321 yield 's[%d]' % prev
1325 yield _genslice(start
, i
, step
)
1327 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1328 cache_res
= func(test_string
)
1329 cache_spec
= [ord(c
) for c
in cache_res
]
1330 expr_code
= ' + '.join(gen_sig_code(cache_spec
))
1331 signature_id_tuple
= '(%s)' % (
1332 ', '.join(compat_str(len(p
)) for p
in example_sig
.split('.')))
1333 code
= ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1334 ' return %s\n') % (signature_id_tuple
, expr_code
)
1335 self
.to_screen('Extracted signature function:\n' + code
)
1337 def _parse_sig_js(self
, jscode
):
1338 funcname
= self
._search
_regex
(
1339 (r
'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1340 r
'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1341 r
'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1342 r
'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1343 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+\)',
1344 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*\)',
1345 r
'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1347 r
'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1348 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1349 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1350 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1351 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1352 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1353 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1354 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1355 jscode, 'Initial JS player signature function name
', group='sig
')
1357 jsi = JSInterpreter(jscode)
1358 initial_function = jsi.extract_function(funcname)
1359 return lambda s: initial_function([s])
1361 def _decrypt_signature(self, s, video_id, player_url):
1362 """Turn the encrypted s field into a working signature"""
1364 if player_url is None:
1365 raise ExtractorError('Cannot decrypt signature without player_url
')
1367 if player_url.startswith('//'):
1368 player_url = 'https
:' + player_url
1369 elif not re.match(r'https?
://', player_url):
1370 player_url = compat_urlparse.urljoin(
1371 'https
://www
.youtube
.com
', player_url)
1373 player_id = (player_url, self._signature_cache_id(s))
1374 if player_id not in self._player_cache:
1375 func = self._extract_signature_function(
1376 video_id, player_url, s
1378 self._player_cache[player_id] = func
1379 func = self._player_cache[player_id]
1380 if self._downloader.params.get('youtube_print_sig_code
'):
1381 self._print_sig_code(func, s)
1383 except Exception as e:
1384 tb = traceback.format_exc()
1385 raise ExtractorError(
1386 'Signature extraction failed
: ' + tb, cause=e)
1388 def _mark_watched(self, video_id, player_response):
1389 playback_url = url_or_none(try_get(
1391 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1392 if not playback_url:
1394 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1395 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1397 # cpn generation algorithm is reverse engineered from base.js.
1398 # In fact it works even with dummy cpn.
1399 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1400 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1406 playback_url = compat_urlparse.urlunparse(
1407 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1409 self._download_webpage(
1410 playback_url, video_id, 'Marking watched
',
1411 'Unable to mark watched
', fatal=False)
1414 def _extract_urls(webpage):
1415 # Embedded YouTube player
1417 unescapeHTML(mobj.group('url
'))
1418 for mobj in re.finditer(r'''(?x)
1428 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1429 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1432 # lazyYT YouTube embed
1433 entries.extend(list(map(
1435 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1437 # Wordpress "YouTube Video Importer
" plugin
1438 matches = re.findall(r'''(?x)<div[^>]+
1439 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1440 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1441 entries.extend(m[-1] for m in matches)
1446 def _extract_url(webpage):
1447 urls = YoutubeIE._extract_urls(webpage)
1448 return urls[0] if urls else None
1451 def extract_id(cls, url):
1452 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1454 raise ExtractorError('Invalid URL: %s' % url)
1455 video_id = mobj.group(2)
1458 def _extract_chapters_from_json(self, data, video_id, duration):
1459 chapters_list = try_get(
1461 lambda x: x['playerOverlays']
1462 ['playerOverlayRenderer']
1463 ['decoratedPlayerBarRenderer']
1464 ['decoratedPlayerBarRenderer']
1466 ['chapteredPlayerBarRenderer']
1469 if not chapters_list:
1472 def chapter_time(chapter):
1473 return float_or_none(
1476 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1480 for next_num, chapter in enumerate(chapters_list, start=1):
1481 start_time = chapter_time(chapter)
1482 if start_time is None:
1484 end_time = (chapter_time(chapters_list[next_num])
1485 if next_num < len(chapters_list) else duration)
1486 if end_time is None:
1489 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1492 'start_time': start_time,
1493 'end_time': end_time,
1498 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1499 return self._parse_json(self._search_regex(
1500 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1501 regex), webpage, name, default='{}'), video_id, fatal=False)
1504 def _join_text_entries(runs):
1507 if not isinstance(run, dict):
1509 sub_text = try_get(run, lambda x: x['text'], compat_str)
1517 def _extract_comment(self, comment_renderer, parent=None):
1518 comment_id = comment_renderer.get('commentId')
1521 comment_text_runs = try_get(comment_renderer, lambda x: x['contentText']['runs']) or []
1522 text = self._join_text_entries(comment_text_runs) or ''
1523 comment_time_text = try_get(comment_renderer, lambda x: x['publishedTimeText']['runs']) or []
1524 time_text = self._join_text_entries(comment_time_text)
1526 author = try_get(comment_renderer, lambda x: x['authorText']['simpleText'], compat_str)
1527 author_id = try_get(comment_renderer,
1528 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], compat_str)
1529 votes = str_to_int(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
1530 lambda x: x['likeCount']), compat_str)) or 0
1531 author_thumbnail = try_get(comment_renderer,
1532 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], compat_str)
1534 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
1535 is_liked = try_get(comment_renderer, lambda x: x['isLiked'], bool)
1540 # TODO: This should be parsed to timestamp
1541 'time_text': time_text,
1542 'like_count': votes,
1543 'is_favorited': is_liked,
1545 'author_id': author_id,
1546 'author_thumbnail': author_thumbnail,
1547 'author_is_uploader': author_is_uploader,
1548 'parent': parent or 'root'
1551 def _comment_entries(self, root_continuation_data, identity_token, account_syncid,
1552 session_token_list, parent=None, comment_counts=None):
1554 def extract_thread(parent_renderer):
1555 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
1557 comment_counts[2] = 0
1558 for content in contents:
1559 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
1560 comment_renderer = try_get(
1561 comment_thread_renderer, (lambda x: x['comment']['commentRenderer'], dict)) or try_get(
1562 content, (lambda x: x['commentRenderer'], dict))
1564 if not comment_renderer:
1566 comment = self._extract_comment(comment_renderer, parent)
1569 comment_counts[0] += 1
1571 # Attempt to get the replies
1572 comment_replies_renderer = try_get(
1573 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
1575 if comment_replies_renderer:
1576 comment_counts[2] += 1
1577 comment_entries_iter = self._comment_entries(
1578 comment_replies_renderer, identity_token, account_syncid,
1579 parent=comment.get('id'), session_token_list=session_token_list,
1580 comment_counts=comment_counts)
1582 for reply_comment in comment_entries_iter:
1585 if not comment_counts:
1586 # comment so far, est. total comments, current comment thread #
1587 comment_counts = [0, 0, 0]
1588 headers = self._DEFAULT_BASIC_API_HEADERS.copy()
1590 # TODO: Generalize the download code with TabIE
1592 headers['x-youtube-identity-token'] = identity_token
1595 headers['X-Goog-PageId'] = account_syncid
1596 headers['X-Goog-AuthUser'] = 0
1598 continuation = YoutubeTabIE._extract_continuation(root_continuation_data) # TODO
1599 first_continuation = False
1601 first_continuation = True
1603 for page_num in itertools.count(0):
1604 if not continuation:
1606 retries = self._downloader.params.get('extractor_retries', 3)
1610 while count < retries:
1613 self.report_warning('%s. Retrying ...' % last_error)
1616 'ctoken': continuation['ctoken'],
1621 query['action_get_comment_replies'] = 1
1623 query['action_get_comments'] = 1
1625 comment_prog_str = '(%d/%d)' % (comment_counts[0], comment_counts[1])
1627 if first_continuation:
1628 note_prefix = "Downloading initial comment continuation page"
1630 note_prefix = " Downloading comment reply thread %d %s" % (comment_counts[2], comment_prog_str)
1632 note_prefix = "%sDownloading comment%s page %d %s" % (
1633 " " if parent else "",
1634 ' replies' if parent else '',
1638 browse = self._download_json(
1639 'https://www.youtube.com/comment_service_ajax', None,
1640 '%s %s' % (note_prefix, '(retry #%d)' % count if count else ''),
1641 headers=headers, query=query,
1642 data=urlencode_postdata({
1643 'session_token': session_token_list[0]
1645 except ExtractorError as e:
1646 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404, 413):
1647 if e.cause.code == 413:
1648 self.report_warning("Assumed end of comments (received HTTP Error 413)")
1650 # Downloading page may result in intermittent 5xx HTTP error
1651 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1652 last_error = 'HTTP Error %s' % e.cause.code
1653 if e.cause.code == 404:
1654 last_error = last_error + " (this API is probably deprecated)"
1659 session_token = try_get(browse, lambda x: x['xsrf_token'], compat_str)
1661 session_token_list[0] = session_token
1663 response = try_get(browse,
1664 (lambda x: x['response'],
1665 lambda x: x[1]['response'])) or {}
1667 if response.get('continuationContents'):
1670 # YouTube sometimes gives reload: now json if something went wrong (e.g. bad auth)
1671 if browse.get('reload'):
1672 raise ExtractorError("Invalid or missing params in continuation request", expected=False)
1674 # TODO: not tested, merged from old extractor
1675 err_msg = browse.get('externalErrorMessage')
1677 raise ExtractorError('YouTube said: %s' % err_msg, expected=False)
1679 # Youtube sometimes sends incomplete data
1680 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1681 last_error = 'Incomplete data received'
1682 if count >= retries:
1683 self._downloader.report_error(last_error)
1688 known_continuation_renderers = {
1689 'itemSectionContinuation': extract_thread,
1690 'commentRepliesContinuation': extract_thread
1693 # extract next root continuation from the results
1694 continuation_contents = try_get(
1695 response, lambda x: x['continuationContents'], dict) or {}
1697 for key, value in continuation_contents.items():
1698 if key not in known_continuation_renderers:
1700 continuation_renderer = value
1702 if first_continuation:
1703 first_continuation = False
1704 expected_comment_count = try_get(
1705 continuation_renderer,
1706 (lambda x: x['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'],
1707 lambda x: x['header']['commentsHeaderRenderer']['commentsCount']['runs'][0]['text']),
1710 if expected_comment_count:
1711 comment_counts[1] = str_to_int(expected_comment_count)
1712 self.to_screen("Downloading ~%d comments" % str_to_int(expected_comment_count))
1713 yield comment_counts[1]
1716 # 1/True for newest, 0/False for popular (default)
1717 comment_sort_index = int(True)
1718 sort_continuation_renderer = try_get(
1719 continuation_renderer,
1720 lambda x: x['header']['commentsHeaderRenderer']['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems']
1721 [comment_sort_index]['continuation']['reloadContinuationData'], dict)
1722 # If this fails, the initial continuation page
1723 # starts off with popular anyways.
1724 if sort_continuation_renderer:
1725 continuation = YoutubeTabIE._build_continuation_query(
1726 continuation=sort_continuation_renderer.get('continuation'),
1727 ctp=sort_continuation_renderer.get('clickTrackingParams'))
1728 self.to_screen("Sorting comments by %s" % ('popular' if comment_sort_index == 0 else 'newest'))
1731 for entry in known_continuation_renderers[key](continuation_renderer):
1734 continuation = YoutubeTabIE._extract_continuation(continuation_renderer) # TODO
1737 def _extract_comments(self, ytcfg, video_id, contents, webpage, xsrf_token):
1738 """Entry for comment extraction"""
1740 known_entry_comment_renderers = (
1741 'itemSectionRenderer',
1744 for entry in contents:
1745 for key, renderer in entry.items():
1746 if key not in known_entry_comment_renderers:
1749 comment_iter = self._comment_entries(
1751 identity_token=self._extract_identity_token(webpage, item_id=video_id),
1752 account_syncid=self._extract_account_syncid(ytcfg),
1753 session_token_list=[xsrf_token])
1755 for comment in comment_iter:
1756 if isinstance(comment, int):
1757 estimated_total = comment
1759 comments.append(comment)
1761 self.to_screen("Downloaded %d/%d comments" % (len(comments), estimated_total))
1763 'comments': comments,
1764 'comment_count': len(comments),
1767 def _real_extract(self, url):
1768 url, smuggled_data = unsmuggle_url(url, {})
1769 video_id = self._match_id(url)
1770 base_url = self.http_scheme() + '//www.youtube.com/'
1771 webpage_url = base_url + 'watch?v=' + video_id
1772 webpage = self._download_webpage(
1773 webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1775 player_response = None
1777 player_response = self._extract_yt_initial_variable(
1778 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1779 video_id, 'initial player response')
1780 if not player_response:
1781 player_response = self._call_api(
1782 'player', {'videoId': video_id}, video_id)
1784 playability_status = player_response.get('playabilityStatus') or {}
1785 if playability_status.get('reason') == 'Sign in to confirm your age':
1786 pr = self._parse_json(try_get(compat_parse_qs(
1787 self._download_webpage(
1788 base_url + 'get_video_info', video_id,
1789 'Refetching age-gated info webpage',
1790 'unable to download video info webpage', query={
1791 'video_id': video_id,
1792 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1794 lambda x: x['player_response'][0],
1795 compat_str) or '{}', video_id)
1797 player_response = pr
1799 trailer_video_id = try_get(
1801 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1803 if trailer_video_id:
1804 return self.url_result(
1805 trailer_video_id, self.ie_key(), trailer_video_id)
1810 return x.get('simpleText') or ''.join([r['text'] for r in x['runs']])
1813 lambda x: self._html_search_meta(x, webpage, default=None)) \
1814 if webpage else lambda x: None
1816 video_details = player_response.get('videoDetails') or {}
1817 microformat = try_get(
1819 lambda x: x['microformat']['playerMicroformatRenderer'],
1821 video_title = video_details.get('title') \
1822 or get_text(microformat.get('title')) \
1823 or search_meta(['og:title', 'twitter:title', 'title'])
1824 video_description = video_details.get('shortDescription')
1826 if not smuggled_data.get('force_singlefeed', False):
1827 if not self._downloader.params.get('noplaylist'):
1828 multifeed_metadata_list = try_get(
1830 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1832 if multifeed_metadata_list:
1835 for feed in multifeed_metadata_list.split(','):
1836 # Unquote should take place before split on comma (,) since textual
1837 # fields may contain comma as well (see
1838 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1839 feed_data = compat_parse_qs(
1840 compat_urllib_parse_unquote_plus(feed))
1842 def feed_entry(name):
1844 feed_data, lambda x: x[name][0], compat_str)
1846 feed_id = feed_entry('id')
1849 feed_title = feed_entry('title')
1852 title += ' (%s)' % feed_title
1854 '_type': 'url_transparent',
1855 'ie_key': 'Youtube',
1857 base_url + 'watch?v=' + feed_data['id'][0],
1858 {'force_singlefeed': True}),
1861 feed_ids.append(feed_id)
1863 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1864 % (', '.join(feed_ids), video_id))
1865 return self.playlist_result(
1866 entries, video_id, video_title, video_description)
1868 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1874 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1875 streaming_data = player_response.get('streamingData') or {}
1876 streaming_formats = streaming_data.get('formats') or []
1877 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1878 for fmt in streaming_formats:
1879 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1882 itag = str_or_none(fmt.get('itag'))
1883 quality = fmt.get('quality')
1884 if itag and quality:
1885 itag_qualities[itag] = quality
1886 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1887 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1888 # number of fragment that would subsequently requested with (`&sq=N`)
1889 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1892 fmt_url = fmt.get('url')
1894 sc = compat_parse_qs(fmt.get('signatureCipher'))
1895 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1896 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1897 if not (sc and fmt_url and encrypted_sig):
1902 player_url = self._search_regex(
1903 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1904 webpage, 'player URL', fatal=False)
1907 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1908 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1909 fmt_url += '&' + sp + '=' + signature
1913 tbr = float_or_none(
1914 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1916 'asr': int_or_none(fmt.get('audioSampleRate')),
1917 'filesize': int_or_none(fmt.get('contentLength')),
1919 'format_note': fmt.get('qualityLabel') or quality,
1920 'fps': int_or_none(fmt.get('fps')),
1921 'height': int_or_none(fmt.get('height')),
1922 'quality': q(quality),
1925 'width': fmt.get('width'),
1927 mimetype = fmt.get('mimeType')
1930 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1932 dct['ext'] = mimetype2ext(mobj.group(1))
1933 dct.update(parse_codecs(mobj.group(2)))
1934 no_audio = dct.get('acodec') == 'none'
1935 no_video = dct.get('vcodec') == 'none'
1940 if no_audio or no_video:
1941 dct['downloader_options'] = {
1942 # Youtube throttles chunks >~10M
1943 'http_chunk_size': 10485760,
1946 dct['container'] = dct['ext'] + '_dash'
1949 hls_manifest_url = streaming_data.get('hlsManifestUrl')
1950 if hls_manifest_url:
1951 for f in self._extract_m3u8_formats(
1952 hls_manifest_url, video_id, 'mp4', fatal=False):
1953 itag = self._search_regex(
1954 r'/itag/(\d+)', f['url'], 'itag', default=None)
1956 f['format_id'] = itag
1959 if self._downloader.params.get('youtube_include_dash_manifest', True):
1960 dash_manifest_url = streaming_data.get('dashManifestUrl')
1961 if dash_manifest_url:
1962 for f in self._extract_mpd_formats(
1963 dash_manifest_url, video_id, fatal=False):
1964 itag = f['format_id']
1967 if itag in itag_qualities:
1968 # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
1969 # but kept to maintain feature parity (and code similarity) with youtube-dl
1970 # Remove if this causes any issues with sorting in future
1971 f['quality'] = q(itag_qualities[itag])
1972 filesize = int_or_none(self._search_regex(
1973 r'/clen/(\d+)', f.get('fragment_base_url')
1974 or f['url'], 'file size', default=None))
1976 f['filesize'] = filesize
1980 if not self._downloader.params.get('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
1981 raise ExtractorError(
1982 'This video is DRM protected.', expected=True)
1985 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
1987 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
1988 subreason = pemr.get('subreason')
1990 subreason = clean_html(get_text(subreason))
1991 if subreason == 'The uploader has not made this video available in your country.':
1992 countries = microformat.get('availableCountries')
1994 regions_allowed = search_meta('regionsAllowed')
1995 countries = regions_allowed.split(',') if regions_allowed else None
1996 self.raise_geo_restricted(
1997 subreason, countries)
1998 reason += '\n' + subreason
2000 raise ExtractorError(reason, expected=True)
2002 self._sort_formats(formats)
2004 keywords = video_details.get('keywords') or []
2005 if not keywords and webpage:
2007 unescapeHTML(m.group('content'))
2008 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
2009 for keyword in keywords:
2010 if keyword.startswith('yt:stretch='):
2011 w, h = keyword.split('=')[1].split(':')
2012 w, h = int(w), int(h)
2016 if f.get('vcodec') != 'none':
2017 f['stretched_ratio'] = ratio
2020 for container in (video_details, microformat):
2021 for thumbnail in (try_get(
2023 lambda x: x['thumbnail']['thumbnails'], list) or []):
2024 thumbnail_url = thumbnail.get('url')
2025 if not thumbnail_url:
2028 'height': int_or_none(thumbnail.get('height')),
2029 'url': thumbnail_url,
2030 'width': int_or_none(thumbnail.get('width')),
2035 thumbnail = search_meta(['og:image', 'twitter:image'])
2037 thumbnails = [{'url': thumbnail}]
2039 category = microformat.get('category') or search_meta('genre')
2040 channel_id = video_details.get('channelId') \
2041 or microformat.get('externalChannelId') \
2042 or search_meta('channelId')
2043 duration = int_or_none(
2044 video_details.get('lengthSeconds')
2045 or microformat.get('lengthSeconds')) \
2046 or parse_duration(search_meta('duration'))
2047 is_live = video_details.get('isLive')
2048 owner_profile_url = microformat.get('ownerProfileUrl')
2052 'title': self._live_title(video_title) if is_live else video_title,
2054 'thumbnails': thumbnails,
2055 'description': video_description,
2056 'upload_date': unified_strdate(
2057 microformat.get('uploadDate')
2058 or search_meta('uploadDate')),
2059 'uploader': video_details['author'],
2060 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
2061 'uploader_url': owner_profile_url,
2062 'channel_id': channel_id,
2063 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
2064 'duration': duration,
2065 'view_count': int_or_none(
2066 video_details.get('viewCount')
2067 or microformat.get('viewCount')
2068 or search_meta('interactionCount')),
2069 'average_rating': float_or_none(video_details.get('averageRating')),
2070 'age_limit': 18 if (
2071 microformat.get('isFamilySafe') is False
2072 or search_meta('isFamilyFriendly') == 'false'
2073 or search_meta('og:restrictions:age') == '18+') else 0,
2074 'webpage_url': webpage_url,
2075 'categories': [category] if category else None,
2078 'playable_in_embed': playability_status.get('playableInEmbed'),
2079 'was_live': video_details.get('isLiveContent'),
2084 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
2087 def process_language(container, base_url, lang_code, query):
2089 for fmt in self._SUBTITLE_FORMATS:
2095 'url': update_url_query(base_url, query),
2097 container[lang_code] = lang_subs
2099 for caption_track in (pctr.get('captionTracks') or []):
2100 base_url = caption_track.get('baseUrl')
2103 if caption_track.get('kind') != 'asr':
2104 lang_code = caption_track.get('languageCode')
2108 subtitles, base_url, lang_code, {})
2110 automatic_captions = {}
2111 for translation_language in (pctr.get('translationLanguages') or []):
2112 translation_language_code = translation_language.get('languageCode')
2113 if not translation_language_code:
2116 automatic_captions, base_url, translation_language_code,
2117 {'tlang': translation_language_code})
2118 info['automatic_captions'] = automatic_captions
2119 info['subtitles'] = subtitles
2121 parsed_url = compat_urllib_parse_urlparse(url)
2122 for component in [parsed_url.fragment, parsed_url.query]:
2123 query = compat_parse_qs(component)
2124 for k, v in query.items():
2125 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
2127 if d_k not in info and k in s_ks:
2128 info[d_k] = parse_duration(query[k][0])
2130 # Youtube Music Auto-generated description
2131 if video_description:
2132 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)
2134 release_year = mobj.group('release_year')
2135 release_date = mobj.group('release_date')
2137 release_date = release_date.replace('-', '')
2138 if not release_year:
2139 release_year = release_date[:4]
2141 'album': mobj.group('album'.strip()),
2142 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
2143 'track': mobj.group('track').strip(),
2144 'release_date': release_date,
2145 'release_year': int_or_none(release_year),
2150 initial_data = self._extract_yt_initial_variable(
2151 webpage, self._YT_INITIAL_DATA_RE, video_id,
2153 if not initial_data:
2154 initial_data = self._call_api(
2155 'next', {'videoId': video_id}, video_id, fatal=False)
2159 # This will error if there is no livechat
2160 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
2161 info['subtitles']['live_chat'] = [{
2162 'url': 'https://www.youtube.com/watch?v=%s' % video_id, # url is needed to set cookies
2163 'video_id': video_id,
2165 'protocol': 'youtube_live_chat_replay',
2167 except (KeyError, IndexError, TypeError):
2171 chapters = self._extract_chapters_from_json(
2172 initial_data, video_id, duration)
2174 for engagment_pannel in (initial_data.get('engagementPanels') or []):
2176 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
2181 def chapter_time(mmlir):
2182 return parse_duration(
2183 get_text(mmlir.get('timeDescription')))
2186 for next_num, content in enumerate(contents, start=1):
2187 mmlir = content.get('macroMarkersListItemRenderer') or {}
2188 start_time = chapter_time(mmlir)
2189 end_time = chapter_time(try_get(
2190 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
2191 if next_num < len(contents) else duration
2192 if start_time is None or end_time is None:
2195 'start_time': start_time,
2196 'end_time': end_time,
2197 'title': get_text(mmlir.get('title')),
2202 info['chapters'] = chapters
2206 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
2208 for content in contents:
2209 vpir = content.get('videoPrimaryInfoRenderer')
2211 stl = vpir.get('superTitleLink')
2216 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
2217 info['location'] = stl
2219 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
2222 'series': mobj.group(1),
2223 'season_number': int(mobj.group(2)),
2224 'episode_number': int(mobj.group(3)),
2226 for tlb in (try_get(
2228 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
2230 tbr = tlb.get('toggleButtonRenderer') or {}
2231 for getter, regex in [(
2232 lambda x: x['defaultText']['accessibility']['accessibilityData'],
2233 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
2234 lambda x: x['accessibility'],
2235 lambda x: x['accessibilityData']['accessibilityData'],
2236 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
2237 label = (try_get(tbr, getter, dict) or {}).get('label')
2239 mobj = re.match(regex, label)
2241 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
2243 sbr_tooltip = try_get(
2244 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
2246 like_count, dislike_count = sbr_tooltip.split(' / ')
2248 'like_count': str_to_int(like_count),
2249 'dislike_count': str_to_int(dislike_count),
2251 vsir = content.get('videoSecondaryInfoRenderer')
2253 info['channel'] = get_text(try_get(
2255 lambda x: x['owner']['videoOwnerRenderer']['title'],
2259 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
2261 multiple_songs = False
2263 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
2264 multiple_songs = True
2267 mrr = row.get('metadataRowRenderer') or {}
2268 mrr_title = mrr.get('title')
2271 mrr_title = get_text(mrr['title'])
2272 mrr_contents_text = get_text(mrr['contents'][0])
2273 if mrr_title == 'License':
2274 info['license'] = mrr_contents_text
2275 elif not multiple_songs:
2276 if mrr_title == 'Album':
2277 info['album'] = mrr_contents_text
2278 elif mrr_title == 'Artist':
2279 info['artist'] = mrr_contents_text
2280 elif mrr_title == 'Song':
2281 info['track'] = mrr_contents_text
2284 'channel': 'uploader',
2285 'channel_id': 'uploader_id',
2286 'channel_url': 'uploader_url',
2288 for to, frm in fallbacks.items():
2289 if not info.get(to):
2290 info[to] = info.get(frm)
2292 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
2297 is_private = bool_or_none(video_details.get('isPrivate'))
2298 is_unlisted = bool_or_none(microformat.get('isUnlisted'))
2299 is_membersonly = None
2300 if initial_data and is_private is not None:
2301 is_membersonly = False
2302 contents = try_get(initial_data, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'], list)
2303 for content in contents or []:
2304 badges = try_get(content, lambda x: x['videoPrimaryInfoRenderer']['badges'], list)
2305 for badge in badges or []:
2306 label = try_get(badge, lambda x: x['metadataBadgeRenderer']['label']) or ''
2307 if label.lower() == 'members only':
2308 is_membersonly = True
2313 # TODO: Add this for playlists
2314 info['availability'] = self._availability(
2315 is_private=is_private,
2316 needs_premium=False, # Youtube no longer have premium-only videos?
2317 needs_subscription=is_membersonly,
2318 needs_auth=info['age_limit'] >= 18,
2319 is_unlisted=None if is_private is None else is_unlisted)
2321 # get xsrf for annotations or comments
2322 get_annotations = self._downloader.params.get('writeannotations', False)
2323 get_comments = self._downloader.params.get('getcomments', False)
2324 if get_annotations or get_comments:
2326 ytcfg = self._extract_ytcfg(video_id, webpage)
2328 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2330 xsrf_token = self._search_regex(
2331 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2332 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2336 invideo_url = try_get(
2337 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2338 if xsrf_token and invideo_url:
2339 xsrf_field_name = None
2341 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2342 if not xsrf_field_name:
2343 xsrf_field_name = self._search_regex(
2344 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2345 webpage, 'xsrf field name',
2346 group='xsrf_field_name', default='session_token')
2347 info['annotations'] = self._download_webpage(
2348 self._proto_relative_url(invideo_url),
2349 video_id, note='Downloading annotations',
2350 errnote='Unable to download video annotations', fatal=False,
2351 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2354 info['__post_extractor'] = lambda: self._extract_comments(ytcfg, video_id, contents, webpage, xsrf_token)
2356 self.mark_watched(video_id, player_response)
2361 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2362 IE_DESC = 'YouTube.com tab'
2363 _VALID_URL = r'''(?x
)
2367 youtube(?
:kids
)?\
.com|
2371 (?
:channel|c|user
)/|
2374 (?
:playlist|watch
)\?.*?
\blist
=
2376 (?
!(?
:%s)\b) # Direct URLs
2379 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2380 IE_NAME = 'youtube:tab'
2383 # playlists, multipage
2384 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2385 'playlist_mincount': 94,
2387 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2388 'title': 'Игорь Клейнер - Playlists',
2389 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2390 'uploader': 'Игорь Клейнер',
2391 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2394 # playlists, multipage, different order
2395 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2396 'playlist_mincount': 94,
2398 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2399 'title': 'Игорь Клейнер - Playlists',
2400 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2401 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2402 'uploader': 'Игорь Клейнер',
2405 # playlists, singlepage
2406 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2407 'playlist_mincount': 4,
2409 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2410 'title': 'ThirstForScience - Playlists',
2411 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2412 'uploader': 'ThirstForScience',
2413 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2416 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2417 'only_matching': True,
2419 # basic, single video playlist
2420 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2422 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2423 'uploader': 'Sergey M.',
2424 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2425 'title': 'youtube-dl public playlist',
2427 'playlist_count': 1,
2430 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2432 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2433 'uploader': 'Sergey M.',
2434 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2435 'title': 'youtube-dl empty playlist',
2437 'playlist_count': 0,
2440 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2442 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2443 'title': 'lex will - Home',
2444 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2445 'uploader': 'lex will',
2446 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2448 'playlist_mincount': 2,
2451 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2453 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2454 'title': 'lex will - Videos',
2455 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2456 'uploader': 'lex will',
2457 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2459 'playlist_mincount': 975,
2461 # Videos tab, sorted by popular
2462 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2464 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2465 'title': 'lex will - Videos',
2466 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2467 'uploader': 'lex will',
2468 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2470 'playlist_mincount': 199,
2473 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2475 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2476 'title': 'lex will - Playlists',
2477 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2478 'uploader': 'lex will',
2479 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2481 'playlist_mincount': 17,
2484 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2486 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2487 'title': 'lex will - Community',
2488 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2489 'uploader': 'lex will',
2490 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2492 'playlist_mincount': 18,
2495 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2497 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2498 'title': 'lex will - Channels',
2499 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2500 'uploader': 'lex will',
2501 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2503 'playlist_mincount': 12,
2505 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2506 'only_matching': True,
2508 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2509 'only_matching': True,
2511 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2512 'only_matching': True,
2514 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2515 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2517 'title': '29C3: Not my department',
2518 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2519 'uploader': 'Christiaan008',
2520 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2521 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2523 'playlist_count': 96,
2525 'note': 'Large playlist',
2526 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2528 'title': 'Uploads from Cauchemar',
2529 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2530 'uploader': 'Cauchemar',
2531 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2533 'playlist_mincount': 1123,
2535 # even larger playlist, 8832 videos
2536 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2537 'only_matching': True,
2539 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2540 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2542 'title': 'Uploads from Interstellar Movie',
2543 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2544 'uploader': 'Interstellar Movie',
2545 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2547 'playlist_mincount': 21,
2549 # https://github.com/ytdl-org/youtube-dl/issues/21844
2550 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2552 'title': 'Data Analysis with Dr Mike Pound',
2553 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2554 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2555 'uploader': 'Computerphile',
2556 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2558 'playlist_mincount': 11,
2560 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2561 'only_matching': True,
2563 # Playlist URL that does not actually serve a playlist
2564 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2566 'id': 'FqZTN594JQw',
2568 'title': "Smiley's People 01 detective, Adventure Series, Action",
2569 'uploader': 'STREEM',
2570 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2571 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2572 'upload_date': '20150526',
2573 'license': 'Standard YouTube License',
2574 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2575 'categories': ['People & Blogs'],
2579 'dislike_count': int,
2582 'skip_download': True,
2584 'skip': 'This video is not available.',
2585 'add_ie': [YoutubeIE.ie_key()],
2587 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2588 'only_matching': True,
2590 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2591 'only_matching': True,
2593 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2595 'id': '9Auq9mYxFEE',
2597 'title': compat_str,
2598 'uploader': 'Sky News',
2599 'uploader_id': 'skynews',
2600 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2601 'upload_date': '20191102',
2602 'description': 'md5:85ddd75d888674631aaf9599a9a0b0ae',
2603 'categories': ['News & Politics'],
2606 'dislike_count': int,
2609 'skip_download': True,
2612 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2614 'id': 'a48o2S1cPoo',
2616 'title': 'The Young Turks - Live Main Show',
2617 'uploader': 'The Young Turks',
2618 'uploader_id': 'TheYoungTurks',
2619 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2620 'upload_date': '20150715',
2621 'license': 'Standard YouTube License',
2622 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2623 'categories': ['News & Politics'],
2624 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2626 'dislike_count': int,
2629 'skip_download': True,
2631 'only_matching': True,
2633 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2634 'only_matching': True,
2636 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2637 'only_matching': True,
2639 'url': 'https://www.youtube.com/feed/trending',
2640 'only_matching': True,
2643 'url': 'https://www.youtube.com/feed/library',
2644 'only_matching': True,
2647 'url': 'https://www.youtube.com/feed/history',
2648 'only_matching': True,
2651 'url': 'https://www.youtube.com/feed/subscriptions',
2652 'only_matching': True,
2655 'url': 'https://www.youtube.com/feed/watch_later',
2656 'only_matching': True,
2658 # no longer available?
2659 'url': 'https://www.youtube.com/feed/recommended',
2660 'only_matching': True,
2662 # inline playlist with not always working continuations
2663 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2664 'only_matching': True,
2666 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2667 'only_matching': True,
2669 'url': 'https://www.youtube.com/course',
2670 'only_matching': True,
2672 'url': 'https://www.youtube.com/zsecurity',
2673 'only_matching': True,
2675 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2676 'only_matching': True,
2678 'url': 'https://www.youtube.com/TheYoungTurks/live',
2679 'only_matching': True,
2683 def suitable(cls, url):
2684 return False if YoutubeIE.suitable(url) else super(
2685 YoutubeTabIE, cls).suitable(url)
2687 def _extract_channel_id(self, webpage):
2688 channel_id = self._html_search_meta(
2689 'channelId', webpage, 'channel id', default=None)
2692 channel_url = self._html_search_meta(
2693 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2694 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2695 'twitter:app:url:googleplay'), webpage, 'channel url')
2696 return self._search_regex(
2697 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2698 channel_url, 'channel id')
2701 def _extract_basic_item_renderer(item):
2702 # Modified from _extract_grid_item_renderer
2704 'playlistRenderer', 'videoRenderer', 'channelRenderer',
2705 'gridPlaylistRenderer', 'gridVideoRenderer', 'gridChannelRenderer'
2707 for key, renderer in item.items():
2708 if key not in known_renderers:
2712 def _grid_entries(self, grid_renderer):
2713 for item in grid_renderer['items']:
2714 if not isinstance(item, dict):
2716 renderer = self._extract_basic_item_renderer(item)
2717 if not isinstance(renderer, dict):
2720 renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2722 playlist_id = renderer.get('playlistId')
2724 yield self.url_result(
2725 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2726 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2729 video_id = renderer.get('videoId')
2731 yield self._extract_video(renderer)
2733 channel_id = renderer.get('channelId')
2736 renderer, lambda x: x['title']['simpleText'], compat_str)
2737 yield self.url_result(
2738 'https://www.youtube.com/channel/%s' % channel_id,
2739 ie=YoutubeTabIE.ie_key(), video_title=title)
2741 def _shelf_entries_from_content(self, shelf_renderer):
2742 content = shelf_renderer.get('content')
2743 if not isinstance(content, dict):
2745 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
2747 # TODO: add support for nested playlists so each shelf is processed
2748 # as separate playlist
2749 # TODO: this includes only first N items
2750 for entry in self._grid_entries(renderer):
2752 renderer = content.get('horizontalListRenderer')
2757 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2759 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2761 shelf_url = urljoin('https://www.youtube.com', ep)
2763 # Skipping links to another channels, note that checking for
2764 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2766 if skip_channels and '/channels?' in shelf_url:
2769 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2770 yield self.url_result(shelf_url, video_title=title)
2771 # Shelf may not contain shelf URL, fallback to extraction from content
2772 for entry in self._shelf_entries_from_content(shelf_renderer):
2775 def _playlist_entries(self, video_list_renderer):
2776 for content in video_list_renderer['contents']:
2777 if not isinstance(content, dict):
2779 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2780 if not isinstance(renderer, dict):
2782 video_id = renderer.get('videoId')
2785 yield self._extract_video(renderer)
2787 def _rich_entries(self, rich_grid_renderer):
2789 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
2790 video_id = renderer.get('videoId')
2793 yield self._extract_video(renderer)
2795 def _video_entry(self, video_renderer):
2796 video_id = video_renderer.get('videoId')
2798 return self._extract_video(video_renderer)
2800 def _post_thread_entries(self, post_thread_renderer):
2801 post_renderer = try_get(
2802 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2803 if not post_renderer:
2806 video_renderer = try_get(
2807 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2810 entry = self._video_entry(video_renderer)
2813 # inline video links
2814 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2816 if not isinstance(run, dict):
2819 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2822 if not YoutubeIE.suitable(ep_url):
2824 ep_video_id = YoutubeIE._match_id(ep_url)
2825 if video_id == ep_video_id:
2827 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2829 def _post_thread_continuation_entries(self, post_thread_continuation):
2830 contents = post_thread_continuation.get('contents')
2831 if not isinstance(contents, list):
2833 for content in contents:
2834 renderer = content.get('backstagePostThreadRenderer')
2835 if not isinstance(renderer, dict):
2837 for entry in self._post_thread_entries(renderer):
2841 def _build_continuation_query(continuation, ctp=None):
2843 'ctoken': continuation,
2844 'continuation': continuation,
2851 def _extract_next_continuation_data(renderer):
2852 next_continuation = try_get(
2853 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2854 if not next_continuation:
2856 continuation = next_continuation.get('continuation')
2857 if not continuation:
2859 ctp = next_continuation.get('clickTrackingParams')
2860 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2863 def _extract_continuation(cls, renderer):
2864 next_continuation = cls._extract_next_continuation_data(renderer)
2865 if next_continuation:
2866 return next_continuation
2868 for key in ('contents', 'items'):
2869 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2870 for content in contents:
2871 if not isinstance(content, dict):
2873 continuation_ep = try_get(
2874 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2876 if not continuation_ep:
2878 continuation = try_get(
2879 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2880 if not continuation:
2882 ctp = continuation_ep.get('clickTrackingParams')
2883 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2885 def _entries(self, tab, item_id, identity_token, account_syncid):
2887 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
2888 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
2889 for content in contents:
2890 if not isinstance(content, dict):
2892 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
2894 renderer = content.get('richItemRenderer')
2896 for entry in self._rich_entries(renderer):
2898 continuation_list[0] = self._extract_continuation(parent_renderer)
2900 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2901 for isr_content in isr_contents:
2902 if not isinstance(isr_content, dict):
2906 'playlistVideoListRenderer': self._playlist_entries,
2907 'gridRenderer': self._grid_entries,
2908 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
2909 'backstagePostThreadRenderer': self._post_thread_entries,
2910 'videoRenderer': lambda x: [self._video_entry(x)],
2912 for key, renderer in isr_content.items():
2913 if key not in known_renderers:
2915 for entry in known_renderers[key](renderer):
2918 continuation_list[0] = self._extract_continuation(renderer)
2921 if not continuation_list[0]:
2922 continuation_list[0] = self._extract_continuation(is_renderer)
2924 if not continuation_list[0]:
2925 continuation_list[0] = self._extract_continuation(parent_renderer)
2927 continuation_list = [None] # Python 2 doesnot support nonlocal
2928 tab_content = try_get(tab, lambda x: x['content'], dict)
2932 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
2933 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
2934 for entry in extract_entries(parent_renderer):
2936 continuation = continuation_list[0]
2939 'x-youtube-client-name': '1',
2940 'x-youtube-client-version': '2.20201112.04.01',
2943 headers['x-youtube-identity-token'] = identity_token
2946 headers['X-Goog-PageId'] = account_syncid
2947 headers['X-Goog-AuthUser'] = 0
2949 for page_num in itertools.count(1):
2950 if not continuation:
2952 retries = self._downloader.params.get('extractor_retries', 3)
2955 while count < retries:
2958 self.report_warning('%s. Retrying ...' % last_error)
2960 response = self._call_api(
2961 ep="browse", fatal=True, headers=headers,
2962 video_id='%s page %s' % (item_id, page_num),
2964 'continuation': continuation['continuation'],
2965 'clickTracking': {'clickTrackingParams': continuation['itct']},
2967 note='Downloading API JSON%s' % (' (retry #%d)' % count if count else ''))
2968 except ExtractorError as e:
2969 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
2970 # Downloading page may result in intermittent 5xx HTTP error
2971 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
2972 last_error = 'HTTP Error %s' % e.cause.code
2977 # Youtube sometimes sends incomplete data
2978 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
2979 if dict_get(response,
2980 ('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints')):
2983 # Youtube may send alerts if there was an issue with the continuation page
2984 self._extract_alerts(response, expected=False)
2986 last_error = 'Incomplete data received'
2987 if count >= retries:
2988 self._downloader.report_error(last_error)
2993 known_continuation_renderers = {
2994 'playlistVideoListContinuation': self._playlist_entries,
2995 'gridContinuation': self._grid_entries,
2996 'itemSectionContinuation': self._post_thread_continuation_entries,
2997 'sectionListContinuation': extract_entries, # for feeds
2999 continuation_contents = try_get(
3000 response, lambda x: x['continuationContents'], dict) or {}
3001 continuation_renderer = None
3002 for key, value in continuation_contents.items():
3003 if key not in known_continuation_renderers:
3005 continuation_renderer = value
3006 continuation_list = [None]
3007 for entry in known_continuation_renderers[key](continuation_renderer):
3009 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
3011 if continuation_renderer:
3015 'gridPlaylistRenderer': (self._grid_entries, 'items'),
3016 'gridVideoRenderer': (self._grid_entries, 'items'),
3017 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
3018 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
3019 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
3020 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents')
3022 on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3023 continuation_items = try_get(
3024 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
3025 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
3026 video_items_renderer = None
3027 for key, value in continuation_item.items():
3028 if key not in known_renderers:
3030 video_items_renderer = {known_renderers[key][1]: continuation_items}
3031 continuation_list = [None]
3032 for entry in known_renderers[key][0](video_items_renderer):
3034 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
3036 if video_items_renderer:
3041 def _extract_selected_tab(tabs):
3043 if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
3044 return tab['tabRenderer']
3046 raise ExtractorError('Unable to find selected tab')
3049 def _extract_uploader(data):
3051 sidebar_renderer = try_get(
3052 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3053 if sidebar_renderer:
3054 for item in sidebar_renderer:
3055 if not isinstance(item, dict):
3057 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
3058 if not isinstance(renderer, dict):
3061 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
3063 uploader['uploader'] = owner.get('text')
3064 uploader['uploader_id'] = try_get(
3065 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
3066 uploader['uploader_url'] = urljoin(
3067 'https://www.youtube.com/',
3068 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
3069 return {k: v for k, v in uploader.items() if v is not None}
3071 def _extract_from_tabs(self, item_id, webpage, data, tabs):
3072 playlist_id = title = description = channel_url = channel_name = channel_id = None
3073 thumbnails_list = tags = []
3075 selected_tab = self._extract_selected_tab(tabs)
3077 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
3079 channel_name = renderer.get('title')
3080 channel_url = renderer.get('channelUrl')
3081 channel_id = renderer.get('externalId')
3085 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
3087 title = renderer.get('title')
3088 description = renderer.get('description', '')
3089 playlist_id = channel_id
3090 tags = renderer.get('keywords', '').split()
3092 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
3095 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
3100 for t in thumbnails_list:
3101 if not isinstance(t, dict):
3103 thumbnail_url = url_or_none(t.get('url'))
3104 if not thumbnail_url:
3107 'url': thumbnail_url,
3108 'width': int_or_none(t.get('width')),
3109 'height': int_or_none(t.get('height')),
3112 if playlist_id is None:
3113 playlist_id = item_id
3116 title += format_field(selected_tab, 'title', ' - %s')
3119 'playlist_id': playlist_id,
3120 'playlist_title': title,
3121 'playlist_description': description,
3122 'uploader': channel_name,
3123 'uploader_id': channel_id,
3124 'uploader_url': channel_url,
3125 'thumbnails': thumbnails,
3129 metadata.update(self._extract_uploader(data))
3131 'channel': metadata['uploader'],
3132 'channel_id': metadata['uploader_id'],
3133 'channel_url': metadata['uploader_url']})
3134 return self.playlist_result(
3136 selected_tab, playlist_id,
3137 self._extract_identity_token(webpage, item_id),
3138 self._extract_account_syncid(data)),
3141 def _extract_mix_playlist(self, playlist, playlist_id):
3142 first_id = last_id = None
3143 for page_num in itertools.count(1):
3144 videos = list(self._playlist_entries(playlist))
3147 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
3148 if start >= len(videos):
3150 for video in videos[start:]:
3151 if video['id'] == first_id:
3152 self.to_screen('First video %s found again; Assuming end of Mix' % first_id)
3155 first_id = first_id or videos[0]['id']
3156 last_id = videos[-1]['id']
3158 _, data = self._extract_webpage(
3159 'https://www.youtube.com/watch?list=%s&v=%s' % (playlist_id, last_id),
3160 '%s page %d' % (playlist_id, page_num))
3162 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3164 def _extract_from_playlist(self, item_id, url, data, playlist):
3165 title = playlist.get('title') or try_get(
3166 data, lambda x: x['titleText']['simpleText'], compat_str)
3167 playlist_id = playlist.get('playlistId') or item_id
3169 # Delegating everything except mix playlists to regular tab-based playlist URL
3170 playlist_url = urljoin(url, try_get(
3171 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3173 if playlist_url and playlist_url != url:
3174 return self.url_result(
3175 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3178 return self.playlist_result(
3179 self._extract_mix_playlist(playlist, playlist_id),
3180 playlist_id=playlist_id, playlist_title=title)
3182 def _extract_alerts(self, data, expected=False):
3184 def _real_extract_alerts():
3185 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
3186 if not isinstance(alert_dict, dict):
3188 for alert in alert_dict.values():
3189 alert_type = alert.get('type')
3192 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str)
3194 yield alert_type, message
3195 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
3196 message = try_get(run, lambda x: x['text'], compat_str)
3198 yield alert_type, message
3201 for alert_type, alert_message in _real_extract_alerts():
3202 if alert_type.lower() == 'error':
3204 self._downloader.report_warning('YouTube said: %s - %s' % ('ERROR', err_msg))
3205 err_msg = alert_message
3207 self._downloader.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3210 raise ExtractorError('YouTube said: %s' % err_msg, expected=expected)
3212 def _extract_webpage(self, url, item_id):
3213 retries = self._downloader.params.get('extractor_retries', 3)
3215 last_error = 'Incomplete yt initial data recieved'
3216 while count < retries:
3218 # Sometimes youtube returns a webpage with incomplete ytInitialData
3219 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3221 self.report_warning('%s. Retrying ...' % last_error)
3222 webpage = self._download_webpage(
3224 'Downloading webpage%s' % (' (retry #%d)' % count if count else ''))
3225 data = self._extract_yt_initial_data(item_id, webpage)
3226 self._extract_alerts(data, expected=True)
3227 if data.get('contents') or data.get('currentVideoEndpoint'):
3229 if count >= retries:
3230 self._downloader.report_error(last_error)
3231 return webpage, data
3233 def _real_extract(self, url):
3234 item_id = self._match_id(url)
3235 url = compat_urlparse.urlunparse(
3236 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3238 # This is not matched in a channel page with a tab selected
3239 mobj = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
3240 mobj = mobj.groupdict() if mobj else {}
3241 if mobj and not mobj.get('not_channel'):
3242 self._downloader.report_warning(
3243 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3244 'To download only the videos in the home page, add a "/featured" to the URL')
3245 url = '%s/videos%s' % (mobj.get('pre'), mobj.get('post') or '')
3247 # Handle both video/playlist URLs
3248 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3249 video_id = qs.get('v', [None])[0]
3250 playlist_id = qs.get('list', [None])[0]
3252 if not video_id and (mobj.get('not_channel') or '').startswith('watch'):
3254 # If there is neither video or playlist ids,
3255 # youtube redirects to home page, which is undesirable
3256 raise ExtractorError('Unable to recognize tab page')
3257 self._downloader.report_warning('A video URL was given without video ID. Trying to download playlist %s' % playlist_id)
3258 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3260 if video_id and playlist_id:
3261 if self._downloader.params.get('noplaylist'):
3262 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3263 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3264 self.to_screen('Downloading playlist %s; add --no-playlist to just download video %s' % (playlist_id, video_id))
3266 webpage, data = self._extract_webpage(url, item_id)
3269 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3271 return self._extract_from_tabs(item_id, webpage, data, tabs)
3274 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3276 return self._extract_from_playlist(item_id, url, data, playlist)
3279 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3280 compat_str) or video_id
3282 self._downloader.report_warning('Unable to recognize playlist. Downloading just video %s' % video_id)
3283 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3285 raise ExtractorError('Unable to recognize tab page')
3288 class YoutubePlaylistIE(InfoExtractor):
3289 IE_DESC = 'YouTube.com playlists'
3290 _VALID_URL = r'''(?x
)(?
:
3295 youtube(?
:kids
)?\
.com|
3300 (?P
<id>%(playlist_id)s)
3301 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3302 IE_NAME = 'youtube:playlist'
3304 'note': 'issue #673',
3305 'url': 'PLBB231211A4F62143',
3307 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3308 'id': 'PLBB231211A4F62143',
3309 'uploader': 'Wickydoo',
3310 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3312 'playlist_mincount': 29,
3314 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3316 'title': 'YDL_safe_search',
3317 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3319 'playlist_count': 2,
3320 'skip': 'This playlist is private',
3323 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3324 'playlist_count': 4,
3327 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3328 'uploader': 'milan',
3329 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3332 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3333 'playlist_mincount': 982,
3335 'title': '2018 Chinese New Singles (11/6 updated)',
3336 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3338 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3341 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3342 'only_matching': True,
3344 # music album playlist
3345 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3346 'only_matching': True,
3350 def suitable(cls, url):
3351 return False if YoutubeTabIE.suitable(url) else super(
3352 YoutubePlaylistIE, cls).suitable(url)
3354 def _real_extract(self, url):
3355 playlist_id = self._match_id(url)
3356 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3358 qs = {'list': playlist_id}
3359 return self.url_result(
3360 update_url_query('https://www.youtube.com/playlist', qs),
3361 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3364 class YoutubeYtBeIE(InfoExtractor):
3365 IE_DESC = 'youtu.be'
3366 _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}
3368 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3370 'id': 'yeWKywCrFtk',
3372 'title': 'Small Scale Baler and Braiding Rugs',
3373 'uploader': 'Backus-Page House Museum',
3374 'uploader_id': 'backuspagemuseum',
3375 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3376 'upload_date': '20161008',
3377 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3378 'categories': ['Nonprofits & Activism'],
3381 'dislike_count': int,
3385 'skip_download': True,
3388 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3389 'only_matching': True,
3392 def _real_extract(self, url):
3393 mobj = re.match(self._VALID_URL, url)
3394 video_id = mobj.group('id')
3395 playlist_id = mobj.group('playlist_id')
3396 return self.url_result(
3397 update_url_query('https://www.youtube.com/watch', {
3399 'list': playlist_id,
3400 'feature': 'youtu.be',
3401 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3404 class YoutubeYtUserIE(InfoExtractor):
3405 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3406 _VALID_URL = r'ytuser:(?P<id>.+)'
3408 'url': 'ytuser:phihag',
3409 'only_matching': True,
3412 def _real_extract(self, url):
3413 user_id = self._match_id(url)
3414 return self.url_result(
3415 'https://www.youtube.com/user/%s' % user_id,
3416 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3419 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3420 IE_NAME = 'youtube:favorites'
3421 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3422 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3423 _LOGIN_REQUIRED = True
3426 'only_matching': True,
3428 'url': ':ytfavorites',
3429 'only_matching': True,
3432 def _real_extract(self, url):
3433 return self.url_result(
3434 'https://www.youtube.com/playlist?list=LL',
3435 ie=YoutubeTabIE.ie_key())
3438 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
3439 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3440 # there doesn't appear to be a real limit, for example if you search for
3441 # 'python' you get more than 8.000.000 results
3442 _MAX_RESULTS = float('inf')
3443 IE_NAME = 'youtube:search'
3444 _SEARCH_KEY = 'ytsearch'
3445 _SEARCH_PARAMS = None
3448 def _entries(self, query, n):
3449 data = {'query': query}
3450 if self._SEARCH_PARAMS:
3451 data['params'] = self._SEARCH_PARAMS
3453 for page_num in itertools.count(1):
3454 search = self._call_api(
3455 ep='search', video_id='query "%s"' % query, fatal=False,
3456 note='Downloading page %s' % page_num, query=data)
3459 slr_contents = try_get(
3461 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3462 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3464 if not slr_contents:
3467 # Youtube sometimes adds promoted content to searches,
3468 # changing the index location of videos and token.
3469 # So we search through all entries till we find them.
3470 continuation_token = None
3471 for slr_content in slr_contents:
3472 if continuation_token is None:
3473 continuation_token = try_get(
3475 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3478 isr_contents = try_get(
3480 lambda x: x['itemSectionRenderer']['contents'],
3482 if not isr_contents:
3484 for content in isr_contents:
3485 if not isinstance(content, dict):
3487 video = content.get('videoRenderer')
3488 if not isinstance(video, dict):
3490 video_id = video.get('videoId')
3494 yield self._extract_video(video)
3499 if not continuation_token:
3501 data['continuation'] = continuation_token
3503 def _get_n_results(self, query, n):
3504 """Get a specified number of results for a query"""
3505 return self.playlist_result(self._entries(query, n), query)
3508 class YoutubeSearchDateIE(YoutubeSearchIE):
3509 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3510 _SEARCH_KEY = 'ytsearchdate'
3511 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3512 _SEARCH_PARAMS = 'CAI%3D'
3515 class YoutubeSearchURLIE(YoutubeSearchIE):
3516 IE_DESC = 'YouTube.com search URLs'
3517 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
3518 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
3519 # _MAX_RESULTS = 100
3521 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3522 'playlist_mincount': 5,
3524 'title': 'youtube-dl test video',
3527 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3528 'only_matching': True,
3532 def _make_valid_url(cls):
3533 return cls._VALID_URL
3535 def _real_extract(self, url):
3536 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
3537 query = (qs.get('search_query') or qs.get('q'))[0]
3538 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
3539 return self._get_n_results(query, self._MAX_RESULTS)
3542 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3544 Base class for feed extractors
3545 Subclasses must define the _FEED_NAME property.
3547 _LOGIN_REQUIRED = True
3552 return 'youtube:%s' % self._FEED_NAME
3554 def _real_initialize(self):
3557 def _real_extract(self, url):
3558 return self.url_result(
3559 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3560 ie=YoutubeTabIE.ie_key())
3563 class YoutubeWatchLaterIE(InfoExtractor):
3564 IE_NAME = 'youtube:watchlater'
3565 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3566 _VALID_URL = r':ytwatchlater'
3568 'url': ':ytwatchlater',
3569 'only_matching': True,
3572 def _real_extract(self, url):
3573 return self.url_result(
3574 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3577 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3578 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3579 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
3580 _FEED_NAME = 'recommended'
3583 'only_matching': True,
3585 'url': ':ytrecommended',
3586 'only_matching': True,
3588 'url': 'https://youtube.com',
3589 'only_matching': True,
3593 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3594 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
3595 _VALID_URL = r':ytsub(?:scription)?s?'
3596 _FEED_NAME = 'subscriptions'
3599 'only_matching': True,
3601 'url': ':ytsubscriptions',
3602 'only_matching': True,
3606 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3607 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
3608 _VALID_URL = r':ythis(?:tory)?'
3609 _FEED_NAME = 'history'
3611 'url': ':ythistory',
3612 'only_matching': True,
3616 class YoutubeTruncatedURLIE(InfoExtractor):
3617 IE_NAME = 'youtube:truncated_url'
3618 IE_DESC = False # Do not list
3619 _VALID_URL = r'''(?x
)
3621 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
3624 annotation_id
=annotation_
[^
&]+|
3630 attribution_link
\?a
=[^
&]+
3636 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3637 'only_matching': True,
3639 'url': 'https://www.youtube.com/watch?',
3640 'only_matching': True,
3642 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3643 'only_matching': True,
3645 'url': 'https://www.youtube.com/watch?feature=foo',
3646 'only_matching': True,
3648 'url': 'https://www.youtube.com/watch?hl=en-GB',
3649 'only_matching': True,
3651 'url': 'https://www.youtube.com/watch?t=2372',
3652 'only_matching': True,
3655 def _real_extract(self, url):
3656 raise ExtractorError(
3657 'Did you forget to quote the URL? Remember that & is a meta '
3658 'character in most shells, so you want to put the URL in quotes, '
3660 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3661 ' or simply youtube-dl BaW_jenozKc .',
3665 class YoutubeTruncatedIDIE(InfoExtractor):
3666 IE_NAME = 'youtube:truncated_id'
3667 IE_DESC = False # Do not list
3668 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
3671 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
3672 'only_matching': True,
3675 def _real_extract(self, url):
3676 video_id = self._match_id(url)
3677 raise ExtractorError(
3678 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),