3 from __future__
import unicode_literals
15 from .common
import InfoExtractor
, SearchInfoExtractor
16 from ..compat
import (
21 compat_urllib_parse_unquote_plus
,
22 compat_urllib_parse_urlencode
,
23 compat_urllib_parse_urlparse
,
26 from ..jsinterp
import JSInterpreter
55 class YoutubeBaseInfoExtractor(InfoExtractor
):
56 """Provide base functions for Youtube extractors"""
57 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
58 _TWOFACTOR_URL
= 'https://accounts.google.com/signin/challenge'
60 _LOOKUP_URL
= 'https://accounts.google.com/_/signin/sl/lookup'
61 _CHALLENGE_URL
= 'https://accounts.google.com/_/signin/sl/challenge'
62 _TFA_URL
= 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
65 r
'channel|c|user|playlist|watch|w|v|embed|e|watch_popup|'
66 r
'movies|results|shared|hashtag|trending|feed|feeds|'
67 r
'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout')
69 _NETRC_MACHINE
= 'youtube'
70 # If True it will raise an error if no login info is provided
71 _LOGIN_REQUIRED
= False
73 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
75 def _ids_to_results(self
, ids
):
77 self
.url_result(vid_id
, 'Youtube', video_id
=vid_id
)
82 Attempt to log in to YouTube.
83 True is returned if successful or skipped.
84 False is returned if login failed.
86 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
88 username
, password
= self
._get
_login
_info
()
89 # No authentication to be performed
91 if self
._LOGIN
_REQUIRED
and self
._downloader
.params
.get('cookiefile') is None:
92 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
93 # if self._downloader.params.get('cookiefile'): # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
94 # self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
97 login_page
= self
._download
_webpage
(
98 self
._LOGIN
_URL
, None,
99 note
='Downloading login page',
100 errnote
='unable to fetch login page', fatal
=False)
101 if login_page
is False:
104 login_form
= self
._hidden
_inputs
(login_page
)
106 def req(url
, f_req
, note
, errnote
):
107 data
= login_form
.copy()
110 'checkConnection': 'youtube',
111 'checkedDomains': 'youtube',
113 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
114 'f.req': json
.dumps(f_req
),
115 'flowName': 'GlifWebSignIn',
116 'flowEntry': 'ServiceLogin',
117 # TODO: reverse actual botguard identifier generation algo
118 'bgRequest': '["identifier",""]',
120 return self
._download
_json
(
121 url
, None, note
=note
, errnote
=errnote
,
122 transform_source
=lambda s
: re
.sub(r
'^[^[]*', '', s
),
124 data
=urlencode_postdata(data
), headers
={
125 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
126 'Google-Accounts-XSRF': 1,
130 self
._downloader
.report_warning(message
)
134 None, [], None, 'US', None, None, 2, False, True,
138 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
140 1, [None, None, []], None, None, None, True
145 lookup_results
= req(
146 self
._LOOKUP
_URL
, lookup_req
,
147 'Looking up account info', 'Unable to look up account info')
149 if lookup_results
is False:
152 user_hash
= try_get(lookup_results
, lambda x
: x
[0][2], compat_str
)
154 warn('Unable to extract user hash')
159 None, 1, None, [1, None, None, None, [password
, None, True]],
161 None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
162 1, [None, None, []], None, None, None, True
165 challenge_results
= req(
166 self
._CHALLENGE
_URL
, challenge_req
,
167 'Logging in', 'Unable to log in')
169 if challenge_results
is False:
172 login_res
= try_get(challenge_results
, lambda x
: x
[0][5], list)
174 login_msg
= try_get(login_res
, lambda x
: x
[5], compat_str
)
176 'Unable to login: %s' % 'Invalid password'
177 if login_msg
== 'INCORRECT_ANSWER_ENTERED' else login_msg
)
180 res
= try_get(challenge_results
, lambda x
: x
[0][-1], list)
182 warn('Unable to extract result entry')
185 login_challenge
= try_get(res
, lambda x
: x
[0][0], list)
187 challenge_str
= try_get(login_challenge
, lambda x
: x
[2], compat_str
)
188 if challenge_str
== 'TWO_STEP_VERIFICATION':
189 # SEND_SUCCESS - TFA code has been successfully sent to phone
190 # QUOTA_EXCEEDED - reached the limit of TFA codes
191 status
= try_get(login_challenge
, lambda x
: x
[5], compat_str
)
192 if status
== 'QUOTA_EXCEEDED':
193 warn('Exceeded the limit of TFA codes, try later')
196 tl
= try_get(challenge_results
, lambda x
: x
[1][2], compat_str
)
198 warn('Unable to extract TL')
201 tfa_code
= self
._get
_tfa
_info
('2-step verification code')
205 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
206 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
209 tfa_code
= remove_start(tfa_code
, 'G-')
212 user_hash
, None, 2, None,
214 9, None, None, None, None, None, None, None,
215 [None, tfa_code
, True, 2]
219 self
._TFA
_URL
.format(tl
), tfa_req
,
220 'Submitting TFA code', 'Unable to submit TFA code')
222 if tfa_results
is False:
225 tfa_res
= try_get(tfa_results
, lambda x
: x
[0][5], list)
227 tfa_msg
= try_get(tfa_res
, lambda x
: x
[5], compat_str
)
229 'Unable to finish TFA: %s' % 'Invalid TFA code'
230 if tfa_msg
== 'INCORRECT_ANSWER_ENTERED' else tfa_msg
)
233 check_cookie_url
= try_get(
234 tfa_results
, lambda x
: x
[0][-1][2], compat_str
)
237 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
238 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
239 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
241 challenge
= CHALLENGES
.get(
243 '%s returned error %s.' % (self
.IE_NAME
, challenge_str
))
244 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge
)
247 check_cookie_url
= try_get(res
, lambda x
: x
[2], compat_str
)
249 if not check_cookie_url
:
250 warn('Unable to extract CheckCookie URL')
253 check_cookie_results
= self
._download
_webpage
(
254 check_cookie_url
, None, 'Checking cookie', fatal
=False)
256 if check_cookie_results
is False:
259 if 'https://myaccount.google.com/' not in check_cookie_results
:
260 warn('Unable to log in')
265 def _initialize_consent(self
):
266 cookies
= self
._get
_cookies
('https://www.youtube.com/')
267 if cookies
.get('__Secure-3PSID'):
270 consent
= cookies
.get('CONSENT')
272 if 'YES' in consent
.value
:
274 consent_id
= self
._search
_regex
(
275 r
'PENDING\+(\d+)', consent
.value
, 'consent', default
=None)
277 consent_id
= random
.randint(100, 999)
278 self
._set
_cookie
('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id
)
280 def _real_initialize(self
):
281 self
._initialize
_consent
()
282 if self
._downloader
is None:
284 if not self
._login
():
287 _YT_WEB_CLIENT_VERSION
= '2.20210407.08.00'
288 _YT_INNERTUBE_API_KEY
= 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
289 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
290 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
291 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
293 def _generate_sapisidhash_header(self):
294 sapisid_cookie = self._get_cookies('https://www.youtube.com').get('SAPISID')
295 if sapisid_cookie is None:
297 time_now = round(time.time())
298 sapisidhash = hashlib.sha1((str(time_now) + " " + sapisid_cookie.value + " " + "https
://www
.youtube
.com
").encode("utf
-8")).hexdigest()
299 return "SAPISIDHASH
%s_%s" % (time_now, sapisidhash)
301 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
302 note='Downloading API JSON', errnote='Unable to download API page',
303 context=None, api_key=None):
305 data = {'context': context} if context else {'context': self._extract_context()}
307 real_headers = self._generate_api_headers()
308 real_headers.update({'content-type': 'application/json'})
310 real_headers.update(headers)
311 return self._download_json(
312 'https://www.youtube.com/youtubei/v1/%s' % ep,
313 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
314 data=json.dumps(data).encode('utf8'), headers=real_headers,
315 query={'key': api_key or self._extract_api_key()})
317 def _extract_api_key(self, ytcfg=None):
318 return try_get(ytcfg, lambda x: x['INNERTUBE_API_KEY'], compat_str) or self._YT_INNERTUBE_API_KEY
320 def _extract_yt_initial_data(self, video_id, webpage):
321 return self._parse_json(
323 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
324 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
327 def _extract_identity_token(self, webpage, item_id):
328 ytcfg = self._extract_ytcfg(item_id, webpage)
330 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
333 return self._search_regex(
334 r'\bID_TOKEN["\']\s
*:\s
*["\'](.+?)["\']', webpage,
335 'identity token
', default=None)
338 def _extract_account_syncid(data):
340 Extract syncId required to download private playlists of secondary channels
341 @param data Either response or ytcfg
344 data, (lambda x: x['responseContext
']['mainAppWebResponseContext
']['datasyncId
'],
345 lambda x: x['DATASYNC_ID
']), compat_str) or '').split("||")
346 if len(sync_ids) >= 2 and sync_ids[1]:
347 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
348 # and just "user_syncid||" for primary channel. We only want the channel_syncid
350 # ytcfg includes channel_syncid if on secondary channel
351 return data.get('DELEGATED_SESSION_ID
')
353 def _extract_ytcfg(self, video_id, webpage):
354 return self._parse_json(
356 r'ytcfg\
.set\s
*\
(\s
*({.+?}
)\s
*\
)\s
*;', webpage, 'ytcfg
',
357 default='{}'), video_id, fatal=False) or {}
359 def __extract_client_version(self
, ytcfg
):
360 return try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_VERSION'], compat_str
) or self
._YT
_WEB
_CLIENT
_VERSION
362 def _extract_context(self
, ytcfg
=None):
363 context
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CONTEXT'], dict)
367 # Recreate the client context (required)
368 client_version
= self
.__extract
_client
_version
(ytcfg
)
369 client_name
= try_get(ytcfg
, lambda x
: x
['INNERTUBE_CLIENT_NAME'], compat_str
) or 'WEB'
372 'clientName': client_name
,
373 'clientVersion': client_version
,
376 visitor_data
= try_get(ytcfg
, lambda x
: x
['VISITOR_DATA'], compat_str
)
378 context
['client']['visitorData'] = visitor_data
381 def _generate_api_headers(self
, ytcfg
=None, identity_token
=None, account_syncid
=None, visitor_data
=None):
383 'X-YouTube-Client-Name': '1',
384 'X-YouTube-Client-Version': self
.__extract
_client
_version
(ytcfg
),
387 headers
['x-youtube-identity-token'] = identity_token
389 headers
['X-Goog-PageId'] = account_syncid
390 headers
['X-Goog-AuthUser'] = 0
392 headers
['x-goog-visitor-id'] = visitor_data
393 auth
= self
._generate
_sapisidhash
_header
()
395 headers
['Authorization'] = auth
396 headers
['X-Origin'] = 'https://www.youtube.com'
399 def _extract_video(self
, renderer
):
400 video_id
= renderer
.get('videoId')
403 (lambda x
: x
['title']['runs'][0]['text'],
404 lambda x
: x
['title']['simpleText']), compat_str
)
405 description
= try_get(
406 renderer
, lambda x
: x
['descriptionSnippet']['runs'][0]['text'],
408 duration
= parse_duration(try_get(
409 renderer
, lambda x
: x
['lengthText']['simpleText'], compat_str
))
410 view_count_text
= try_get(
411 renderer
, lambda x
: x
['viewCountText']['simpleText'], compat_str
) or ''
412 view_count
= str_to_int(self
._search
_regex
(
413 r
'^([\d,]+)', re
.sub(r
'\s', '', view_count_text
),
414 'view count', default
=None))
417 (lambda x
: x
['ownerText']['runs'][0]['text'],
418 lambda x
: x
['shortBylineText']['runs'][0]['text']), compat_str
)
421 'ie_key': YoutubeIE
.ie_key(),
425 'description': description
,
426 'duration': duration
,
427 'view_count': view_count
,
428 'uploader': uploader
,
432 class YoutubeIE(YoutubeBaseInfoExtractor
):
433 IE_DESC
= 'YouTube.com'
435 # invidious-redirect websites
436 r
'(?:www\.)?redirect\.invidious\.io',
437 r
'(?:(?:www|dev)\.)?invidio\.us',
438 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
439 r
'(?:www\.)?invidious\.pussthecat\.org',
440 r
'(?:www\.)?invidious\.048596\.xyz',
441 r
'(?:www\.)?invidious\.zee\.li',
442 r
'(?:www\.)?vid\.puffyan\.us',
443 r
'(?:(?:www|au)\.)?ytprivate\.com',
444 r
'(?:www\.)?invidious\.namazso\.eu',
445 r
'(?:www\.)?invidious\.ethibox\.fr',
446 r
'(?:www\.)?inv\.skyn3t\.in',
447 r
'(?:www\.)?invidious\.himiko\.cloud',
448 r
'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
449 r
'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
450 r
'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
451 r
'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
452 # youtube-dl invidious instances list
453 r
'(?:(?:www|no)\.)?invidiou\.sh',
454 r
'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
455 r
'(?:www\.)?invidious\.kabi\.tk',
456 r
'(?:www\.)?invidious\.13ad\.de',
457 r
'(?:www\.)?invidious\.mastodon\.host',
458 r
'(?:www\.)?invidious\.zapashcanon\.fr',
459 r
'(?:www\.)?invidious\.kavin\.rocks',
460 r
'(?:www\.)?invidious\.tube',
461 r
'(?:www\.)?invidiou\.site',
462 r
'(?:www\.)?invidious\.site',
463 r
'(?:www\.)?invidious\.xyz',
464 r
'(?:www\.)?invidious\.nixnet\.xyz',
465 r
'(?:www\.)?invidious\.drycat\.fr',
466 r
'(?:www\.)?tube\.poal\.co',
467 r
'(?:www\.)?tube\.connect\.cafe',
468 r
'(?:www\.)?vid\.wxzm\.sx',
469 r
'(?:www\.)?vid\.mint\.lgbt',
470 r
'(?:www\.)?yewtu\.be',
471 r
'(?:www\.)?yt\.elukerio\.org',
472 r
'(?:www\.)?yt\.lelux\.fi',
473 r
'(?:www\.)?invidious\.ggc-project\.de',
474 r
'(?:www\.)?yt\.maisputain\.ovh',
475 r
'(?:www\.)?invidious\.toot\.koeln',
476 r
'(?:www\.)?invidious\.fdn\.fr',
477 r
'(?:www\.)?watch\.nettohikari\.com',
478 r
'(?:www\.)?kgg2m7yk5aybusll\.onion',
479 r
'(?:www\.)?qklhadlycap4cnod\.onion',
480 r
'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
481 r
'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
482 r
'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
483 r
'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
484 r
'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
485 r
'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
487 _VALID_URL
= r
"""(?x)^
489 (?:https?://|//) # http(s):// or protocol-independent URL
490 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
491 (?:www\.)?deturl\.com/www\.youtube\.com|
492 (?:www\.)?pwnyoutube\.com|
493 (?:www\.)?hooktube\.com|
494 (?:www\.)?yourepeat\.com|
497 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
498 (?:.*?\#/)? # handle anchor (#/) redirect urls
499 (?: # the various things that can precede the ID:
500 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
501 |(?: # or the v= param in all its forms
502 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
503 (?:\?|\#!?) # the params delimiter ? or # or #!
504 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
509 youtu\.be| # just youtu.be/xxxx
510 vid\.plus| # or vid.plus/xxxx
511 zwearz\.com/watch| # or zwearz.com/watch/xxxx
514 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
516 )? # all until now is optional -> you can pass the naked ID
517 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
520 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
521 WL # WL are handled by the watch later IE
524 (?(1).+)? # if we found the ID, everything can follow
526 'playlist_id': YoutubeBaseInfoExtractor
._PLAYLIST
_ID
_RE
,
527 'invidious': '|'.join(_INVIDIOUS_SITES
),
530 r
'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
531 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$',
532 r
'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
535 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
536 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'}
,
537 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'}
,
538 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'}
,
539 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'}
,
540 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
541 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
542 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
543 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
544 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'}
,
545 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
546 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'}
,
547 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
548 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'}
,
549 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
550 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'}
,
551 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
552 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'}
,
556 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
557 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20}
,
558 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
559 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20}
,
560 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20}
,
561 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
562 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20}
,
564 # Apple HTTP Live Streaming
565 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
566 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
567 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
568 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10}
,
569 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
570 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10}
,
571 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10}
,
572 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10}
,
575 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
576 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
577 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
578 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
579 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
580 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}
, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
581 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
582 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
583 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
584 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
585 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60}
,
586 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'}
,
589 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'}
,
590 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'}
,
591 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'}
,
592 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
593 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'}
,
594 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'}
,
595 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'}
,
598 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
599 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
600 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
601 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
602 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
603 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'}
,
604 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'}
,
605 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
606 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
607 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
608 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
609 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
610 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
611 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
612 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
613 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
614 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
615 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
616 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
617 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
618 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'}
,
619 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60}
,
622 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128}
,
623 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256}
,
625 # Dash webm audio with opus inside
626 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50}
,
627 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70}
,
628 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160}
,
631 '_rtmp': {'protocol': 'rtmp'}
,
633 # av01 video only formats sometimes served with "unknown" codecs
634 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
635 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
636 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
637 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'}
,
639 _SUBTITLE_FORMATS
= ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
646 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
650 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
651 'uploader': 'Philipp Hagemeister',
652 'uploader_id': 'phihag',
653 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
654 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
655 'channel_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
656 'upload_date': '20121002',
657 '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 .',
658 'categories': ['Science & Technology'],
659 'tags': ['youtube-dl'],
663 'dislike_count': int,
669 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
670 'note': 'Embed-only video (#1746)',
674 'upload_date': '20120608',
675 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
676 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
677 'uploader': 'SET India',
678 'uploader_id': 'setindia',
679 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/setindia',
682 'skip': 'Private video',
685 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
686 'note': 'Use the first video ID in the URL',
690 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
691 'uploader': 'Philipp Hagemeister',
692 'uploader_id': 'phihag',
693 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/phihag',
694 'upload_date': '20121002',
695 '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 .',
696 'categories': ['Science & Technology'],
697 'tags': ['youtube-dl'],
701 'dislike_count': int,
704 'skip_download': True,
708 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
709 'note': '256k DASH audio (format 141) via DASH manifest',
713 'upload_date': '20121002',
714 'uploader_id': '8KVIDEO',
715 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
717 'uploader': '8KVIDEO',
718 'title': 'UHDTV TEST 8K VIDEO.mp4'
721 'youtube_include_dash_manifest': True,
724 'skip': 'format 141 not served anymore',
726 # DASH manifest with encrypted signature
728 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
732 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
733 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
735 'uploader': 'AfrojackVEVO',
736 'uploader_id': 'AfrojackVEVO',
737 'upload_date': '20131011',
741 'youtube_include_dash_manifest': True,
742 'format': '141/bestaudio[ext=m4a]',
747 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
752 'upload_date': '20100909',
753 'uploader': 'Amazing Atheist',
754 'uploader_id': 'TheAmazingAtheist',
755 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
756 'title': 'Burning Everyone\'s Koran',
757 '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',
760 # Normal age-gate video (embed allowed)
762 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
766 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
767 'description': r
're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
769 'uploader': 'The Witcher',
770 'uploader_id': 'WitcherGame',
771 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
772 'upload_date': '20140605',
776 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
777 # YouTube Red ad is not captured for creator
779 'url': '__2ABJjxzNo',
784 'upload_date': '20100430',
785 'uploader_id': 'deadmau5',
786 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/deadmau5',
787 'creator': 'deadmau5',
788 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
789 'uploader': 'deadmau5',
790 'title': 'Deadmau5 - Some Chords (HD)',
791 'alt_title': 'Some Chords',
793 'expected_warnings': [
794 'DASH manifest missing',
797 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
799 'url': 'lqQg6PlCWgI',
804 'upload_date': '20150827',
805 'uploader_id': 'olympic',
806 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/olympic',
807 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
808 'uploader': 'Olympic',
809 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
812 'skip_download': 'requires avconv',
817 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
821 'stretched_ratio': 16 / 9.,
823 'upload_date': '20110310',
824 'uploader_id': 'AllenMeow',
825 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
826 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
828 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
831 # url_encoded_fmt_stream_map is empty string
833 'url': 'qEJwOuvDf7I',
837 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
839 'upload_date': '20150404',
840 'uploader_id': 'spbelect',
841 'uploader': 'Наблюдатели Петербурга',
844 'skip_download': 'requires avconv',
846 'skip': 'This live event has ended.',
848 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
850 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
854 'title': 'md5:7b81415841e02ecd4313668cde88737a',
855 'description': 'md5:116377fd2963b81ec4ce64b542173306',
857 'upload_date': '20150625',
858 'uploader_id': 'dorappi2000',
859 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
860 'uploader': 'dorappi2000',
861 'formats': 'mincount:31',
863 'skip': 'not actual anymore',
865 # DASH manifest with segment_list
867 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
868 'md5': '8ce563a1d667b599d21064e982ab9e31',
872 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
873 'uploader': 'Airtek',
874 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
875 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
876 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
879 'youtube_include_dash_manifest': True,
880 'format': '135', # bestvideo
882 'skip': 'This live event has ended.',
885 # Multifeed videos (multiple cameras), URL is for Main Camera
886 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
889 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
890 'description': 'md5:e03b909557865076822aa169218d6a5d',
896 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
897 'description': 'md5:e03b909557865076822aa169218d6a5d',
899 'upload_date': '20161111',
900 'uploader': 'Team PGP',
901 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
902 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
908 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
909 'description': 'md5:e03b909557865076822aa169218d6a5d',
911 'upload_date': '20161111',
912 'uploader': 'Team PGP',
913 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
914 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
920 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
921 'description': 'md5:e03b909557865076822aa169218d6a5d',
923 'upload_date': '20161111',
924 'uploader': 'Team PGP',
925 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
926 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
932 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
933 'description': 'md5:e03b909557865076822aa169218d6a5d',
935 'upload_date': '20161111',
936 'uploader': 'Team PGP',
937 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
938 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
942 'skip_download': True,
946 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
947 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
950 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
953 'skip': 'Not multifeed anymore',
956 'url': 'https://vid.plus/FlRa-iH7PGw',
957 'only_matching': True,
960 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
961 'only_matching': True,
964 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
965 # Also tests cut-off URL expansion in video description (see
966 # https://github.com/ytdl-org/youtube-dl/issues/1892,
967 # https://github.com/ytdl-org/youtube-dl/issues/8164)
968 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
972 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
973 'alt_title': 'Dark Walk - Position Music',
974 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
976 'upload_date': '20151119',
977 'uploader_id': 'IronSoulElf',
978 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
979 'uploader': 'IronSoulElf',
980 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
981 'track': 'Dark Walk - Position Music',
982 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
983 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
986 'skip_download': True,
990 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
991 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
992 'only_matching': True,
995 # Video with yt:stretch=17:0
996 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
1000 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
1001 'description': 'md5:ee18a25c350637c8faff806845bddee9',
1002 'upload_date': '20151107',
1003 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
1004 'uploader': 'CH GAMER DROID',
1007 'skip_download': True,
1009 'skip': 'This video does not exist.',
1012 # Video licensed under Creative Commons
1013 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1015 'id': 'M4gD1WSo5mA',
1017 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1018 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
1020 'upload_date': '20150127',
1021 'uploader_id': 'BerkmanCenter',
1022 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
1023 'uploader': 'The Berkman Klein Center for Internet & Society',
1024 'license': 'Creative Commons Attribution license (reuse allowed)',
1027 'skip_download': True,
1031 # Channel-like uploader_url
1032 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1034 'id': 'eQcmzGIKrzg',
1036 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
1037 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
1039 'upload_date': '20151119',
1040 'uploader': 'Bernie Sanders',
1041 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1042 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
1043 'license': 'Creative Commons Attribution license (reuse allowed)',
1046 'skip_download': True,
1050 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
1051 'only_matching': True,
1054 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
1055 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1056 'only_matching': True,
1059 # Rental video preview
1060 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1062 'id': 'uGpuVWrhIzE',
1064 'title': 'Piku - Trailer',
1065 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1066 'upload_date': '20150811',
1067 'uploader': 'FlixMatrix',
1068 'uploader_id': 'FlixMatrixKaravan',
1069 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
1070 'license': 'Standard YouTube License',
1073 'skip_download': True,
1075 'skip': 'This video is not available.',
1078 # YouTube Red video with episode data
1079 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1081 'id': 'iqKdEhx-dD4',
1083 'title': 'Isolation - Mind Field (Ep 1)',
1084 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1086 'upload_date': '20170118',
1087 'uploader': 'Vsauce',
1088 'uploader_id': 'Vsauce',
1089 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1090 'series': 'Mind Field',
1092 'episode_number': 1,
1095 'skip_download': True,
1097 'expected_warnings': [
1098 'Skipping DASH manifest',
1102 # The following content has been identified by the YouTube community
1103 # as inappropriate or offensive to some audiences.
1104 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1106 'id': '6SJNVb0GnPI',
1108 'title': 'Race Differences in Intelligence',
1109 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1111 'upload_date': '20140124',
1112 'uploader': 'New Century Foundation',
1113 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1114 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1117 'skip_download': True,
1119 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1123 'url': '1t24XAntNCY',
1124 'only_matching': True,
1127 # geo restricted to JP
1128 'url': 'sJL6WA-aGkQ',
1129 'only_matching': True,
1132 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1133 'only_matching': True,
1136 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1137 'only_matching': True,
1140 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1141 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1142 'only_matching': True,
1146 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1147 'only_matching': True,
1150 # Video with unsupported adaptive stream type formats
1151 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1153 'id': 'Z4Vy8R84T1U',
1155 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1156 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1158 'upload_date': '20130923',
1159 'uploader': 'Amelia Putri Harwita',
1160 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1161 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1162 'formats': 'maxcount:10',
1165 'skip_download': True,
1166 'youtube_include_dash_manifest': False,
1168 'skip': 'not actual anymore',
1171 # Youtube Music Auto-generated description
1172 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1174 'id': 'MgNrAu2pzNs',
1176 'title': 'Voyeur Girl',
1177 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1178 'upload_date': '20190312',
1179 'uploader': 'Stephen - Topic',
1180 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1181 'artist': 'Stephen',
1182 'track': 'Voyeur Girl',
1183 'album': 'it\'s too much love to know my dear',
1184 'release_date': '20190313',
1185 'release_year': 2019,
1188 'skip_download': True,
1192 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1193 'only_matching': True,
1196 # invalid -> valid video id redirection
1197 'url': 'DJztXj2GPfl',
1199 'id': 'DJztXj2GPfk',
1201 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1202 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1203 'upload_date': '20090125',
1204 'uploader': 'Prochorowka',
1205 'uploader_id': 'Prochorowka',
1206 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1207 'artist': 'Panjabi MC',
1208 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1209 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1212 'skip_download': True,
1214 'skip': 'Video unavailable',
1217 # empty description results in an empty string
1218 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1220 'id': 'x41yOUIvK2k',
1222 'title': 'IMG 3456',
1224 'upload_date': '20170613',
1225 'uploader_id': 'ElevageOrVert',
1226 'uploader': 'ElevageOrVert',
1229 'skip_download': True,
1233 # with '};' inside yt initial data (see [1])
1234 # see [2] for an example with '};' inside ytInitialPlayerResponse
1235 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1236 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1237 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1239 'id': 'CHqg6qOn4no',
1241 'title': 'Part 77 Sort a list of simple types in c#',
1242 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1243 'upload_date': '20130831',
1244 'uploader_id': 'kudvenkat',
1245 'uploader': 'kudvenkat',
1248 'skip_download': True,
1252 # another example of '};' in ytInitialData
1253 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1254 'only_matching': True,
1257 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1258 'only_matching': True,
1261 # https://github.com/ytdl-org/youtube-dl/pull/28094
1262 'url': 'OtqTfy26tG0',
1264 'id': 'OtqTfy26tG0',
1266 'title': 'Burn Out',
1267 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1268 'upload_date': '20141120',
1269 'uploader': 'The Cinematic Orchestra - Topic',
1270 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1271 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1272 'artist': 'The Cinematic Orchestra',
1273 'track': 'Burn Out',
1274 'album': 'Every Day',
1275 'release_data': None,
1276 'release_year': None,
1279 'skip_download': True,
1283 # controversial video, only works with bpctr when authenticated with cookies
1284 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1285 'only_matching': True,
1288 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1289 'url': 'cBvYw8_A0vQ',
1291 'id': 'cBvYw8_A0vQ',
1293 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
1294 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1295 'upload_date': '20201120',
1296 'uploader': 'Walk around Japan',
1297 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1298 'uploader_url': r
're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1301 'skip_download': True,
1306 def __init__(self
, *args
, **kwargs
):
1307 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
1308 self
._code
_cache
= {}
1309 self
._player
_cache
= {}
1311 def _signature_cache_id(self
, example_sig
):
1312 """ Return a string representation of a signature """
1313 return '.'.join(compat_str(len(part
)) for part
in example_sig
.split('.'))
1316 def _extract_player_info(cls
, player_url
):
1317 for player_re
in cls
._PLAYER
_INFO
_RE
:
1318 id_m
= re
.search(player_re
, player_url
)
1322 raise ExtractorError('Cannot identify player %r' % player_url
)
1323 return id_m
.group('id')
1325 def _extract_signature_function(self
, video_id
, player_url
, example_sig
):
1326 player_id
= self
._extract
_player
_info
(player_url
)
1328 # Read from filesystem cache
1329 func_id
= 'js_%s_%s' % (
1330 player_id
, self
._signature
_cache
_id
(example_sig
))
1331 assert os
.path
.basename(func_id
) == func_id
1333 cache_spec
= self
._downloader
.cache
.load('youtube-sigfuncs', func_id
)
1334 if cache_spec
is not None:
1335 return lambda s
: ''.join(s
[i
] for i
in cache_spec
)
1337 if player_id
not in self
._code
_cache
:
1338 self
._code
_cache
[player_id
] = self
._download
_webpage
(
1339 player_url
, video_id
,
1340 note
='Downloading player ' + player_id
,
1341 errnote
='Download of %s failed' % player_url
)
1342 code
= self
._code
_cache
[player_id
]
1343 res
= self
._parse
_sig
_js
(code
)
1345 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1346 cache_res
= res(test_string
)
1347 cache_spec
= [ord(c
) for c
in cache_res
]
1349 self
._downloader
.cache
.store('youtube-sigfuncs', func_id
, cache_spec
)
1352 def _print_sig_code(self
, func
, example_sig
):
1353 def gen_sig_code(idxs
):
1354 def _genslice(start
, end
, step
):
1355 starts
= '' if start
== 0 else str(start
)
1356 ends
= (':%d' % (end
+ step
)) if end
+ step
>= 0 else ':'
1357 steps
= '' if step
== 1 else (':%d' % step
)
1358 return 's[%s%s%s]' % (starts
, ends
, steps
)
1361 # Quelch pyflakes warnings - start will be set when step is set
1362 start
= '(Never used)'
1363 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
1364 if step
is not None:
1365 if i
- prev
== step
:
1367 yield _genslice(start
, prev
, step
)
1370 if i
- prev
in [-1, 1]:
1375 yield 's[%d]' % prev
1379 yield _genslice(start
, i
, step
)
1381 test_string
= ''.join(map(compat_chr
, range(len(example_sig
))))
1382 cache_res
= func(test_string
)
1383 cache_spec
= [ord(c
) for c
in cache_res
]
1384 expr_code
= ' + '.join(gen_sig_code(cache_spec
))
1385 signature_id_tuple
= '(%s)' % (
1386 ', '.join(compat_str(len(p
)) for p
in example_sig
.split('.')))
1387 code
= ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1388 ' return %s\n') % (signature_id_tuple
, expr_code
)
1389 self
.to_screen('Extracted signature function:\n' + code
)
1391 def _parse_sig_js(self
, jscode
):
1392 funcname
= self
._search
_regex
(
1393 (r
'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1394 r
'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1395 r
'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1396 r
'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1397 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+\)',
1398 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*\)',
1399 r
'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1401 r
'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1402 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1403 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1404 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1405 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1406 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1407 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1408 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1409 jscode, 'Initial JS player signature function name
', group='sig
')
1411 jsi = JSInterpreter(jscode)
1412 initial_function = jsi.extract_function(funcname)
1413 return lambda s: initial_function([s])
1415 def _decrypt_signature(self, s, video_id, player_url):
1416 """Turn the encrypted s field into a working signature"""
1418 if player_url is None:
1419 raise ExtractorError('Cannot decrypt signature without player_url
')
1421 if player_url.startswith('//'):
1422 player_url = 'https
:' + player_url
1423 elif not re.match(r'https?
://', player_url):
1424 player_url = compat_urlparse.urljoin(
1425 'https
://www
.youtube
.com
', player_url)
1427 player_id = (player_url, self._signature_cache_id(s))
1428 if player_id not in self._player_cache:
1429 func = self._extract_signature_function(
1430 video_id, player_url, s
1432 self._player_cache[player_id] = func
1433 func = self._player_cache[player_id]
1434 if self._downloader.params.get('youtube_print_sig_code
'):
1435 self._print_sig_code(func, s)
1437 except Exception as e:
1438 tb = traceback.format_exc()
1439 raise ExtractorError(
1440 'Signature extraction failed
: ' + tb, cause=e)
1442 def _mark_watched(self, video_id, player_response):
1443 playback_url = url_or_none(try_get(
1445 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1446 if not playback_url:
1448 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1449 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1451 # cpn generation algorithm is reverse engineered from base.js.
1452 # In fact it works even with dummy cpn.
1453 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1454 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1460 playback_url = compat_urlparse.urlunparse(
1461 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1463 self._download_webpage(
1464 playback_url, video_id, 'Marking watched
',
1465 'Unable to mark watched
', fatal=False)
1468 def _extract_urls(webpage):
1469 # Embedded YouTube player
1471 unescapeHTML(mobj.group('url
'))
1472 for mobj in re.finditer(r'''(?x)
1482 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1483 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1486 # lazyYT YouTube embed
1487 entries.extend(list(map(
1489 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1491 # Wordpress "YouTube Video Importer
" plugin
1492 matches = re.findall(r'''(?x)<div[^>]+
1493 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1494 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1495 entries.extend(m[-1] for m in matches)
1500 def _extract_url(webpage):
1501 urls = YoutubeIE._extract_urls(webpage)
1502 return urls[0] if urls else None
1505 def extract_id(cls, url):
1506 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1508 raise ExtractorError('Invalid URL: %s' % url)
1509 video_id = mobj.group(2)
1512 def _extract_chapters_from_json(self, data, video_id, duration):
1513 chapters_list = try_get(
1515 lambda x: x['playerOverlays']
1516 ['playerOverlayRenderer']
1517 ['decoratedPlayerBarRenderer']
1518 ['decoratedPlayerBarRenderer']
1520 ['chapteredPlayerBarRenderer']
1523 if not chapters_list:
1526 def chapter_time(chapter):
1527 return float_or_none(
1530 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1534 for next_num, chapter in enumerate(chapters_list, start=1):
1535 start_time = chapter_time(chapter)
1536 if start_time is None:
1538 end_time = (chapter_time(chapters_list[next_num])
1539 if next_num < len(chapters_list) else duration)
1540 if end_time is None:
1543 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1546 'start_time': start_time,
1547 'end_time': end_time,
1552 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1553 return self._parse_json(self._search_regex(
1554 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1555 regex), webpage, name, default='{}'), video_id, fatal=False)
1558 def parse_time_text(time_text):
1560 Parse the comment time text
1561 time_text is in the format 'X units ago (edited)'
1563 time_text_split = time_text.split(' ')
1564 if len(time_text_split) >= 3:
1565 return datetime_from_str('now-%s%s' % (time_text_split[0], time_text_split[1]), precision='auto')
1568 def _join_text_entries(runs):
1571 if not isinstance(run, dict):
1573 sub_text = try_get(run, lambda x: x['text'], compat_str)
1581 def _extract_comment(self, comment_renderer, parent=None):
1582 comment_id = comment_renderer.get('commentId')
1585 comment_text_runs = try_get(comment_renderer, lambda x: x['contentText']['runs']) or []
1586 text = self._join_text_entries(comment_text_runs) or ''
1587 comment_time_text = try_get(comment_renderer, lambda x: x['publishedTimeText']['runs']) or []
1588 time_text = self._join_text_entries(comment_time_text)
1589 timestamp = calendar.timegm(self.parse_time_text(time_text).timetuple())
1590 author = try_get(comment_renderer, lambda x: x['authorText']['simpleText'], compat_str)
1591 author_id = try_get(comment_renderer,
1592 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], compat_str)
1593 votes = str_to_int(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
1594 lambda x: x['likeCount']), compat_str)) or 0
1595 author_thumbnail = try_get(comment_renderer,
1596 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], compat_str)
1598 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
1599 is_liked = try_get(comment_renderer, lambda x: x['isLiked'], bool)
1603 'timestamp': timestamp,
1604 'time_text': time_text,
1605 'like_count': votes,
1606 'is_favorited': is_liked,
1608 'author_id': author_id,
1609 'author_thumbnail': author_thumbnail,
1610 'author_is_uploader': author_is_uploader,
1611 'parent': parent or 'root'
1614 def _comment_entries(self, root_continuation_data, identity_token, account_syncid,
1615 ytcfg, session_token_list, parent=None, comment_counts=None):
1617 def extract_thread(parent_renderer):
1618 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
1620 comment_counts[2] = 0
1621 for content in contents:
1622 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
1623 comment_renderer = try_get(
1624 comment_thread_renderer, (lambda x: x['comment']['commentRenderer'], dict)) or try_get(
1625 content, (lambda x: x['commentRenderer'], dict))
1627 if not comment_renderer:
1629 comment = self._extract_comment(comment_renderer, parent)
1632 comment_counts[0] += 1
1634 # Attempt to get the replies
1635 comment_replies_renderer = try_get(
1636 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
1638 if comment_replies_renderer:
1639 comment_counts[2] += 1
1640 comment_entries_iter = self._comment_entries(
1641 comment_replies_renderer, identity_token, account_syncid, ytcfg,
1642 parent=comment.get('id'), session_token_list=session_token_list,
1643 comment_counts=comment_counts)
1645 for reply_comment in comment_entries_iter:
1648 if not comment_counts:
1649 # comment so far, est. total comments, current comment thread #
1650 comment_counts = [0, 0, 0]
1652 # TODO: Generalize the download code with TabIE
1653 context = self._extract_context(ytcfg)
1654 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
1655 continuation = YoutubeTabIE._extract_continuation(root_continuation_data) # TODO
1656 first_continuation = False
1658 first_continuation = True
1660 for page_num in itertools.count(0):
1661 if not continuation:
1663 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
1664 retries = self._downloader.params.get('extractor_retries', 3)
1668 while count < retries:
1671 self.report_warning('%s. Retrying ...' % last_error)
1674 'ctoken': continuation['ctoken'],
1679 query['action_get_comment_replies'] = 1
1681 query['action_get_comments'] = 1
1683 comment_prog_str = '(%d/%d)' % (comment_counts[0], comment_counts[1])
1685 if first_continuation:
1686 note_prefix = 'Downloading initial comment continuation page'
1688 note_prefix = ' Downloading comment reply thread %d %s' % (comment_counts[2], comment_prog_str)
1690 note_prefix = '%sDownloading comment%s page %d %s' % (
1691 ' ' if parent else '',
1692 ' replies' if parent else '',
1696 browse = self._download_json(
1697 'https://www.youtube.com/comment_service_ajax', None,
1698 '%s %s' % (note_prefix, '(retry #%d)' % count if count else ''),
1699 headers=headers, query=query,
1700 data=urlencode_postdata({
1701 'session_token': session_token_list[0]
1703 except ExtractorError as e:
1704 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404, 413):
1705 if e.cause.code == 413:
1706 self.report_warning('Assumed end of comments (received HTTP Error 413)')
1708 # Downloading page may result in intermittent 5xx HTTP error
1709 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
1710 last_error = 'HTTP Error %s' % e.cause.code
1711 if e.cause.code == 404:
1712 last_error = last_error + ' (this API is probably deprecated)'
1717 session_token = try_get(browse, lambda x: x['xsrf_token'], compat_str)
1719 session_token_list[0] = session_token
1721 response = try_get(browse,
1722 (lambda x: x['response'],
1723 lambda x: x[1]['response'])) or {}
1725 if response.get('continuationContents'):
1728 # YouTube sometimes gives reload: now json if something went wrong (e.g. bad auth)
1729 if browse.get('reload'):
1730 raise ExtractorError('Invalid or missing params in continuation request', expected=False)
1732 # TODO: not tested, merged from old extractor
1733 err_msg = browse.get('externalErrorMessage')
1735 raise ExtractorError('YouTube said: %s' % err_msg, expected=False)
1737 # Youtube sometimes sends incomplete data
1738 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
1739 last_error = 'Incomplete data received'
1740 if count >= retries:
1741 self._downloader.report_error(last_error)
1745 visitor_data = try_get(
1747 lambda x: x['responseContext']['webResponseContextExtensionData']['ytConfigData']['visitorData'],
1748 compat_str) or visitor_data
1750 known_continuation_renderers = {
1751 'itemSectionContinuation': extract_thread,
1752 'commentRepliesContinuation': extract_thread
1755 # extract next root continuation from the results
1756 continuation_contents = try_get(
1757 response, lambda x: x['continuationContents'], dict) or {}
1759 for key, value in continuation_contents.items():
1760 if key not in known_continuation_renderers:
1762 continuation_renderer = value
1764 if first_continuation:
1765 first_continuation = False
1766 expected_comment_count = try_get(
1767 continuation_renderer,
1768 (lambda x: x['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'],
1769 lambda x: x['header']['commentsHeaderRenderer']['commentsCount']['runs'][0]['text']),
1772 if expected_comment_count:
1773 comment_counts[1] = str_to_int(expected_comment_count)
1774 self.to_screen('Downloading ~%d comments' % str_to_int(expected_comment_count))
1775 yield comment_counts[1]
1778 # 1/True for newest, 0/False for popular (default)
1779 comment_sort_index = int(True)
1780 sort_continuation_renderer = try_get(
1781 continuation_renderer,
1782 lambda x: x['header']['commentsHeaderRenderer']['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems']
1783 [comment_sort_index]['continuation']['reloadContinuationData'], dict)
1784 # If this fails, the initial continuation page
1785 # starts off with popular anyways.
1786 if sort_continuation_renderer:
1787 continuation = YoutubeTabIE._build_continuation_query(
1788 continuation=sort_continuation_renderer.get('continuation'),
1789 ctp=sort_continuation_renderer.get('clickTrackingParams'))
1790 self.to_screen('Sorting comments by %s' % ('popular' if comment_sort_index == 0 else 'newest'))
1793 for entry in known_continuation_renderers[key](continuation_renderer):
1796 continuation = YoutubeTabIE._extract_continuation(continuation_renderer) # TODO
1799 def _extract_comments(self, ytcfg, video_id, contents, webpage, xsrf_token):
1800 """Entry for comment extraction"""
1802 known_entry_comment_renderers = (
1803 'itemSectionRenderer',
1806 for entry in contents:
1807 for key, renderer in entry.items():
1808 if key not in known_entry_comment_renderers:
1811 comment_iter = self._comment_entries(
1813 identity_token=self._extract_identity_token(webpage, item_id=video_id),
1814 account_syncid=self._extract_account_syncid(ytcfg),
1816 session_token_list=[xsrf_token])
1818 for comment in comment_iter:
1819 if isinstance(comment, int):
1820 estimated_total = comment
1822 comments.append(comment)
1824 self.to_screen('Downloaded %d/%d comments' % (len(comments), estimated_total))
1826 'comments': comments,
1827 'comment_count': len(comments),
1830 def _real_extract(self, url):
1831 url, smuggled_data = unsmuggle_url(url, {})
1832 video_id = self._match_id(url)
1833 base_url = self.http_scheme() + '//www.youtube.com/'
1834 webpage_url = base_url + 'watch?v=' + video_id
1835 webpage = self._download_webpage(
1836 webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1838 player_response = None
1840 player_response = self._extract_yt_initial_variable(
1841 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1842 video_id, 'initial player response')
1844 ytcfg = self._extract_ytcfg(video_id, webpage)
1845 if not player_response:
1846 player_response = self._call_api(
1847 'player', {'videoId': video_id}, video_id, api_key=self._extract_api_key(ytcfg))
1849 playability_status = player_response.get('playabilityStatus') or {}
1850 if playability_status.get('reason') == 'Sign in to confirm your age':
1851 pr = self._parse_json(try_get(compat_parse_qs(
1852 self._download_webpage(
1853 base_url + 'get_video_info', video_id,
1854 'Refetching age-gated info webpage',
1855 'unable to download video info webpage', query={
1856 'video_id': video_id,
1857 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1859 lambda x: x['player_response'][0],
1860 compat_str) or '{}', video_id)
1862 player_response = pr
1864 trailer_video_id = try_get(
1866 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1868 if trailer_video_id:
1869 return self.url_result(
1870 trailer_video_id, self.ie_key(), trailer_video_id)
1875 text = x.get('simpleText')
1876 if text and isinstance(text, compat_str):
1878 runs = x.get('runs')
1879 if not isinstance(runs, list):
1881 return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1884 lambda x: self._html_search_meta(x, webpage, default=None)) \
1885 if webpage else lambda x: None
1887 video_details = player_response.get('videoDetails') or {}
1888 microformat = try_get(
1890 lambda x: x['microformat']['playerMicroformatRenderer'],
1892 video_title = video_details.get('title') \
1893 or get_text(microformat.get('title')) \
1894 or search_meta(['og:title', 'twitter:title', 'title'])
1895 video_description = video_details.get('shortDescription')
1897 if not smuggled_data.get('force_singlefeed', False):
1898 if not self._downloader.params.get('noplaylist'):
1899 multifeed_metadata_list = try_get(
1901 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1903 if multifeed_metadata_list:
1906 for feed in multifeed_metadata_list.split(','):
1907 # Unquote should take place before split on comma (,) since textual
1908 # fields may contain comma as well (see
1909 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1910 feed_data = compat_parse_qs(
1911 compat_urllib_parse_unquote_plus(feed))
1913 def feed_entry(name):
1915 feed_data, lambda x: x[name][0], compat_str)
1917 feed_id = feed_entry('id')
1920 feed_title = feed_entry('title')
1923 title += ' (%s)' % feed_title
1925 '_type': 'url_transparent',
1926 'ie_key': 'Youtube',
1928 base_url + 'watch?v=' + feed_data['id'][0],
1929 {'force_singlefeed': True}),
1932 feed_ids.append(feed_id)
1934 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1935 % (', '.join(feed_ids), video_id))
1936 return self.playlist_result(
1937 entries, video_id, video_title, video_description)
1939 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1945 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1946 streaming_data = player_response.get('streamingData') or {}
1947 streaming_formats = streaming_data.get('formats') or []
1948 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1949 for fmt in streaming_formats:
1950 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1953 itag = str_or_none(fmt.get('itag'))
1954 quality = fmt.get('quality')
1955 if itag and quality:
1956 itag_qualities[itag] = quality
1957 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1958 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1959 # number of fragment that would subsequently requested with (`&sq=N`)
1960 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1963 fmt_url = fmt.get('url')
1965 sc = compat_parse_qs(fmt.get('signatureCipher'))
1966 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1967 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1968 if not (sc and fmt_url and encrypted_sig):
1973 player_url = self._search_regex(
1974 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1975 webpage, 'player URL', fatal=False)
1978 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1979 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1980 fmt_url += '&' + sp + '=' + signature
1984 tbr = float_or_none(
1985 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1987 'asr': int_or_none(fmt.get('audioSampleRate')),
1988 'filesize': int_or_none(fmt.get('contentLength')),
1990 'format_note': fmt.get('qualityLabel') or quality,
1991 'fps': int_or_none(fmt.get('fps')),
1992 'height': int_or_none(fmt.get('height')),
1993 'quality': q(quality),
1996 'width': fmt.get('width'),
1998 mimetype = fmt.get('mimeType')
2001 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
2003 dct['ext'] = mimetype2ext(mobj.group(1))
2004 dct.update(parse_codecs(mobj.group(2)))
2005 no_audio = dct.get('acodec') == 'none'
2006 no_video = dct.get('vcodec') == 'none'
2011 if no_audio or no_video:
2012 dct['downloader_options'] = {
2013 # Youtube throttles chunks >~10M
2014 'http_chunk_size': 10485760,
2017 dct['container'] = dct['ext'] + '_dash'
2020 hls_manifest_url = streaming_data.get('hlsManifestUrl')
2021 if hls_manifest_url:
2022 for f in self._extract_m3u8_formats(
2023 hls_manifest_url, video_id, 'mp4', fatal=False):
2024 itag = self._search_regex(
2025 r'/itag/(\d+)', f['url'], 'itag', default=None)
2027 f['format_id'] = itag
2030 if self._downloader.params.get('youtube_include_dash_manifest', True):
2031 dash_manifest_url = streaming_data.get('dashManifestUrl')
2032 if dash_manifest_url:
2033 for f in self._extract_mpd_formats(
2034 dash_manifest_url, video_id, fatal=False):
2035 itag = f['format_id']
2038 if itag in itag_qualities:
2039 # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
2040 # but kept to maintain feature parity (and code similarity) with youtube-dl
2041 # Remove if this causes any issues with sorting in future
2042 f['quality'] = q(itag_qualities[itag])
2043 filesize = int_or_none(self._search_regex(
2044 r'/clen/(\d+)', f.get('fragment_base_url')
2045 or f['url'], 'file size', default=None))
2047 f['filesize'] = filesize
2051 if not self._downloader.params.get('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
2052 raise ExtractorError(
2053 'This video is DRM protected.', expected=True)
2056 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
2058 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
2059 subreason = pemr.get('subreason')
2061 subreason = clean_html(get_text(subreason))
2062 if subreason == 'The uploader has not made this video available in your country.':
2063 countries = microformat.get('availableCountries')
2065 regions_allowed = search_meta('regionsAllowed')
2066 countries = regions_allowed.split(',') if regions_allowed else None
2067 self.raise_geo_restricted(
2068 subreason, countries)
2069 reason += '\n' + subreason
2071 raise ExtractorError(reason, expected=True)
2073 self._sort_formats(formats)
2075 keywords = video_details.get('keywords') or []
2076 if not keywords and webpage:
2078 unescapeHTML(m.group('content'))
2079 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
2080 for keyword in keywords:
2081 if keyword.startswith('yt:stretch='):
2082 stretch_ratio = map(
2083 lambda x: int_or_none(x, default=0),
2084 keyword.split('=')[1].split(':'))
2085 w, h = (list(stretch_ratio) + [0])[:2]
2089 if f.get('vcodec') != 'none':
2090 f['stretched_ratio'] = ratio
2093 for container in (video_details, microformat):
2094 for thumbnail in (try_get(
2096 lambda x: x['thumbnail']['thumbnails'], list) or []):
2097 thumbnail_url = thumbnail.get('url')
2098 if not thumbnail_url:
2100 # Sometimes youtube gives a wrong thumbnail URL. See:
2101 # https://github.com/yt-dlp/yt-dlp/issues/233
2102 # https://github.com/ytdl-org/youtube-dl/issues/28023
2103 if 'maxresdefault' in thumbnail_url:
2104 thumbnail_url = thumbnail_url.split('?')[0]
2106 'height': int_or_none(thumbnail.get('height')),
2107 'url': thumbnail_url,
2108 'width': int_or_none(thumbnail.get('width')),
2113 thumbnail = search_meta(['og:image', 'twitter:image'])
2115 thumbnails = [{'url': thumbnail}]
2117 category = microformat.get('category') or search_meta('genre')
2118 channel_id = video_details.get('channelId') \
2119 or microformat.get('externalChannelId') \
2120 or search_meta('channelId')
2121 duration = int_or_none(
2122 video_details.get('lengthSeconds')
2123 or microformat.get('lengthSeconds')) \
2124 or parse_duration(search_meta('duration'))
2125 is_live = video_details.get('isLive')
2126 owner_profile_url = microformat.get('ownerProfileUrl')
2130 'title': self._live_title(video_title) if is_live else video_title,
2132 'thumbnails': thumbnails,
2133 'description': video_description,
2134 'upload_date': unified_strdate(
2135 microformat.get('uploadDate')
2136 or search_meta('uploadDate')),
2137 'uploader': video_details['author'],
2138 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
2139 'uploader_url': owner_profile_url,
2140 'channel_id': channel_id,
2141 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
2142 'duration': duration,
2143 'view_count': int_or_none(
2144 video_details.get('viewCount')
2145 or microformat.get('viewCount')
2146 or search_meta('interactionCount')),
2147 'average_rating': float_or_none(video_details.get('averageRating')),
2148 'age_limit': 18 if (
2149 microformat.get('isFamilySafe') is False
2150 or search_meta('isFamilyFriendly') == 'false'
2151 or search_meta('og:restrictions:age') == '18+') else 0,
2152 'webpage_url': webpage_url,
2153 'categories': [category] if category else None,
2156 'playable_in_embed': playability_status.get('playableInEmbed'),
2157 'was_live': video_details.get('isLiveContent'),
2162 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
2165 def process_language(container, base_url, lang_code, query):
2167 for fmt in self._SUBTITLE_FORMATS:
2173 'url': update_url_query(base_url, query),
2175 container[lang_code] = lang_subs
2177 for caption_track in (pctr.get('captionTracks') or []):
2178 base_url = caption_track.get('baseUrl')
2181 if caption_track.get('kind') != 'asr':
2182 lang_code = caption_track.get('languageCode')
2186 subtitles, base_url, lang_code, {})
2188 automatic_captions = {}
2189 for translation_language in (pctr.get('translationLanguages') or []):
2190 translation_language_code = translation_language.get('languageCode')
2191 if not translation_language_code:
2194 automatic_captions, base_url, translation_language_code,
2195 {'tlang': translation_language_code})
2196 info['automatic_captions'] = automatic_captions
2197 info['subtitles'] = subtitles
2199 parsed_url = compat_urllib_parse_urlparse(url)
2200 for component in [parsed_url.fragment, parsed_url.query]:
2201 query = compat_parse_qs(component)
2202 for k, v in query.items():
2203 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
2205 if d_k not in info and k in s_ks:
2206 info[d_k] = parse_duration(query[k][0])
2208 # Youtube Music Auto-generated description
2209 if video_description:
2210 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)
2212 release_year = mobj.group('release_year')
2213 release_date = mobj.group('release_date')
2215 release_date = release_date.replace('-', '')
2216 if not release_year:
2217 release_year = release_date[:4]
2219 'album': mobj.group('album'.strip()),
2220 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
2221 'track': mobj.group('track').strip(),
2222 'release_date': release_date,
2223 'release_year': int_or_none(release_year),
2228 initial_data = self._extract_yt_initial_variable(
2229 webpage, self._YT_INITIAL_DATA_RE, video_id,
2231 if not initial_data:
2232 initial_data = self._call_api(
2233 'next', {'videoId': video_id}, video_id, fatal=False, api_key=self._extract_api_key(ytcfg))
2237 # This will error if there is no livechat
2238 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
2239 info['subtitles']['live_chat'] = [{
2240 'url': 'https://www.youtube.com/watch?v=%s' % video_id, # url is needed to set cookies
2241 'video_id': video_id,
2243 'protocol': 'youtube_live_chat_replay',
2245 except (KeyError, IndexError, TypeError):
2249 chapters = self._extract_chapters_from_json(
2250 initial_data, video_id, duration)
2252 for engagment_pannel in (initial_data.get('engagementPanels') or []):
2254 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
2259 def chapter_time(mmlir):
2260 return parse_duration(
2261 get_text(mmlir.get('timeDescription')))
2264 for next_num, content in enumerate(contents, start=1):
2265 mmlir = content.get('macroMarkersListItemRenderer') or {}
2266 start_time = chapter_time(mmlir)
2267 end_time = chapter_time(try_get(
2268 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
2269 if next_num < len(contents) else duration
2270 if start_time is None or end_time is None:
2273 'start_time': start_time,
2274 'end_time': end_time,
2275 'title': get_text(mmlir.get('title')),
2280 info['chapters'] = chapters
2284 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
2286 for content in contents:
2287 vpir = content.get('videoPrimaryInfoRenderer')
2289 stl = vpir.get('superTitleLink')
2294 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
2295 info['location'] = stl
2297 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
2300 'series': mobj.group(1),
2301 'season_number': int(mobj.group(2)),
2302 'episode_number': int(mobj.group(3)),
2304 for tlb in (try_get(
2306 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
2308 tbr = tlb.get('toggleButtonRenderer') or {}
2309 for getter, regex in [(
2310 lambda x: x['defaultText']['accessibility']['accessibilityData'],
2311 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
2312 lambda x: x['accessibility'],
2313 lambda x: x['accessibilityData']['accessibilityData'],
2314 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
2315 label = (try_get(tbr, getter, dict) or {}).get('label')
2317 mobj = re.match(regex, label)
2319 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
2321 sbr_tooltip = try_get(
2322 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
2324 like_count, dislike_count = sbr_tooltip.split(' / ')
2326 'like_count': str_to_int(like_count),
2327 'dislike_count': str_to_int(dislike_count),
2329 vsir = content.get('videoSecondaryInfoRenderer')
2331 info['channel'] = get_text(try_get(
2333 lambda x: x['owner']['videoOwnerRenderer']['title'],
2337 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
2339 multiple_songs = False
2341 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
2342 multiple_songs = True
2345 mrr = row.get('metadataRowRenderer') or {}
2346 mrr_title = mrr.get('title')
2349 mrr_title = get_text(mrr['title'])
2350 mrr_contents_text = get_text(mrr['contents'][0])
2351 if mrr_title == 'License':
2352 info['license'] = mrr_contents_text
2353 elif not multiple_songs:
2354 if mrr_title == 'Album':
2355 info['album'] = mrr_contents_text
2356 elif mrr_title == 'Artist':
2357 info['artist'] = mrr_contents_text
2358 elif mrr_title == 'Song':
2359 info['track'] = mrr_contents_text
2362 'channel': 'uploader',
2363 'channel_id': 'uploader_id',
2364 'channel_url': 'uploader_url',
2366 for to, frm in fallbacks.items():
2367 if not info.get(to):
2368 info[to] = info.get(frm)
2370 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
2375 is_private = bool_or_none(video_details.get('isPrivate'))
2376 is_unlisted = bool_or_none(microformat.get('isUnlisted'))
2377 is_membersonly = None
2379 if initial_data and is_private is not None:
2380 is_membersonly = False
2382 contents = try_get(initial_data, lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'], list)
2383 for content in contents or []:
2384 badges = try_get(content, lambda x: x['videoPrimaryInfoRenderer']['badges'], list)
2385 for badge in badges or []:
2386 label = try_get(badge, lambda x: x['metadataBadgeRenderer']['label']) or ''
2387 if label.lower() == 'members only':
2388 is_membersonly = True
2390 elif label.lower() == 'premium':
2393 if is_membersonly or is_premium:
2396 # TODO: Add this for playlists
2397 info['availability'] = self._availability(
2398 is_private=is_private,
2399 needs_premium=is_premium,
2400 needs_subscription=is_membersonly,
2401 needs_auth=info['age_limit'] >= 18,
2402 is_unlisted=None if is_private is None else is_unlisted)
2404 # get xsrf for annotations or comments
2405 get_annotations = self._downloader.params.get('writeannotations', False)
2406 get_comments = self._downloader.params.get('getcomments', False)
2407 if get_annotations or get_comments:
2409 ytcfg = self._extract_ytcfg(video_id, webpage)
2411 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2413 xsrf_token = self._search_regex(
2414 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2415 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2419 invideo_url = try_get(
2420 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2421 if xsrf_token and invideo_url:
2422 xsrf_field_name = None
2424 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2425 if not xsrf_field_name:
2426 xsrf_field_name = self._search_regex(
2427 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2428 webpage, 'xsrf field name',
2429 group='xsrf_field_name', default='session_token')
2430 info['annotations'] = self._download_webpage(
2431 self._proto_relative_url(invideo_url),
2432 video_id, note='Downloading annotations',
2433 errnote='Unable to download video annotations', fatal=False,
2434 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2437 info['__post_extractor'] = lambda: self._extract_comments(ytcfg, video_id, contents, webpage, xsrf_token)
2439 self.mark_watched(video_id, player_response)
2444 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2445 IE_DESC = 'YouTube.com tab'
2446 _VALID_URL = r'''(?x
)
2450 youtube(?
:kids
)?\
.com|
2454 (?
:channel|c|user
)/|
2457 (?
:playlist|watch
)\?.*?
\blist
=
2459 (?
!(?
:%s)\b) # Direct URLs
2462 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2463 IE_NAME = 'youtube:tab'
2466 # playlists, multipage
2467 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2468 'playlist_mincount': 94,
2470 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2471 'title': 'Игорь Клейнер - Playlists',
2472 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2473 'uploader': 'Игорь Клейнер',
2474 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2477 # playlists, multipage, different order
2478 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2479 'playlist_mincount': 94,
2481 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2482 'title': 'Игорь Клейнер - Playlists',
2483 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2484 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2485 'uploader': 'Игорь Клейнер',
2488 # playlists, singlepage
2489 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2490 'playlist_mincount': 4,
2492 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2493 'title': 'ThirstForScience - Playlists',
2494 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2495 'uploader': 'ThirstForScience',
2496 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2499 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2500 'only_matching': True,
2502 # basic, single video playlist
2503 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2505 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2506 'uploader': 'Sergey M.',
2507 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2508 'title': 'youtube-dl public playlist',
2510 'playlist_count': 1,
2513 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2515 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2516 'uploader': 'Sergey M.',
2517 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2518 'title': 'youtube-dl empty playlist',
2520 'playlist_count': 0,
2523 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2525 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2526 'title': 'lex will - Home',
2527 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2528 'uploader': 'lex will',
2529 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2531 'playlist_mincount': 2,
2534 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2536 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2537 'title': 'lex will - Videos',
2538 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2539 'uploader': 'lex will',
2540 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2542 'playlist_mincount': 975,
2544 # Videos tab, sorted by popular
2545 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2547 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2548 'title': 'lex will - Videos',
2549 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2550 'uploader': 'lex will',
2551 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2553 'playlist_mincount': 199,
2556 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2558 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2559 'title': 'lex will - Playlists',
2560 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2561 'uploader': 'lex will',
2562 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2564 'playlist_mincount': 17,
2567 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2569 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2570 'title': 'lex will - Community',
2571 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2572 'uploader': 'lex will',
2573 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2575 'playlist_mincount': 18,
2578 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2580 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2581 'title': 'lex will - Channels',
2582 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2583 'uploader': 'lex will',
2584 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2586 'playlist_mincount': 12,
2588 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2589 'only_matching': True,
2591 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2592 'only_matching': True,
2594 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2595 'only_matching': True,
2597 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2598 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2600 'title': '29C3: Not my department',
2601 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2602 'uploader': 'Christiaan008',
2603 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2604 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2606 'playlist_count': 96,
2608 'note': 'Large playlist',
2609 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2611 'title': 'Uploads from Cauchemar',
2612 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2613 'uploader': 'Cauchemar',
2614 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2616 'playlist_mincount': 1123,
2618 # even larger playlist, 8832 videos
2619 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2620 'only_matching': True,
2622 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2623 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2625 'title': 'Uploads from Interstellar Movie',
2626 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2627 'uploader': 'Interstellar Movie',
2628 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2630 'playlist_mincount': 21,
2632 # https://github.com/ytdl-org/youtube-dl/issues/21844
2633 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2635 'title': 'Data Analysis with Dr Mike Pound',
2636 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2637 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2638 'uploader': 'Computerphile',
2639 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2641 'playlist_mincount': 11,
2643 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2644 'only_matching': True,
2646 # Playlist URL that does not actually serve a playlist
2647 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2649 'id': 'FqZTN594JQw',
2651 'title': "Smiley's People 01 detective, Adventure Series, Action",
2652 'uploader': 'STREEM',
2653 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2654 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2655 'upload_date': '20150526',
2656 'license': 'Standard YouTube License',
2657 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2658 'categories': ['People & Blogs'],
2662 'dislike_count': int,
2665 'skip_download': True,
2667 'skip': 'This video is not available.',
2668 'add_ie': [YoutubeIE.ie_key()],
2670 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2671 'only_matching': True,
2673 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2674 'only_matching': True,
2676 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2678 'id': '9Auq9mYxFEE',
2680 'title': compat_str,
2681 'uploader': 'Sky News',
2682 'uploader_id': 'skynews',
2683 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2684 'upload_date': '20191102',
2685 'description': 'md5:85ddd75d888674631aaf9599a9a0b0ae',
2686 'categories': ['News & Politics'],
2689 'dislike_count': int,
2692 'skip_download': True,
2695 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2697 'id': 'a48o2S1cPoo',
2699 'title': 'The Young Turks - Live Main Show',
2700 'uploader': 'The Young Turks',
2701 'uploader_id': 'TheYoungTurks',
2702 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2703 'upload_date': '20150715',
2704 'license': 'Standard YouTube License',
2705 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2706 'categories': ['News & Politics'],
2707 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2709 'dislike_count': int,
2712 'skip_download': True,
2714 'only_matching': True,
2716 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2717 'only_matching': True,
2719 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2720 'only_matching': True,
2722 'url': 'https://www.youtube.com/feed/trending',
2723 'only_matching': True,
2726 'url': 'https://www.youtube.com/feed/library',
2727 'only_matching': True,
2730 'url': 'https://www.youtube.com/feed/history',
2731 'only_matching': True,
2734 'url': 'https://www.youtube.com/feed/subscriptions',
2735 'only_matching': True,
2738 'url': 'https://www.youtube.com/feed/watch_later',
2739 'only_matching': True,
2741 # no longer available?
2742 'url': 'https://www.youtube.com/feed/recommended',
2743 'only_matching': True,
2745 # inline playlist with not always working continuations
2746 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2747 'only_matching': True,
2749 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2750 'only_matching': True,
2752 'url': 'https://www.youtube.com/course',
2753 'only_matching': True,
2755 'url': 'https://www.youtube.com/zsecurity',
2756 'only_matching': True,
2758 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2759 'only_matching': True,
2761 'url': 'https://www.youtube.com/TheYoungTurks/live',
2762 'only_matching': True,
2764 'url': 'https://www.youtube.com/hashtag/cctv9',
2769 'playlist_mincount': 350,
2773 def suitable(cls, url):
2774 return False if YoutubeIE.suitable(url) else super(
2775 YoutubeTabIE, cls).suitable(url)
2777 def _extract_channel_id(self, webpage):
2778 channel_id = self._html_search_meta(
2779 'channelId', webpage, 'channel id', default=None)
2782 channel_url = self._html_search_meta(
2783 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2784 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2785 'twitter:app:url:googleplay'), webpage, 'channel url')
2786 return self._search_regex(
2787 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2788 channel_url, 'channel id')
2791 def _extract_basic_item_renderer(item):
2792 # Modified from _extract_grid_item_renderer
2794 'playlistRenderer', 'videoRenderer', 'channelRenderer',
2795 'gridPlaylistRenderer', 'gridVideoRenderer', 'gridChannelRenderer'
2797 for key, renderer in item.items():
2798 if key not in known_renderers:
2802 def _grid_entries(self, grid_renderer):
2803 for item in grid_renderer['items']:
2804 if not isinstance(item, dict):
2806 renderer = self._extract_basic_item_renderer(item)
2807 if not isinstance(renderer, dict):
2810 renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2812 playlist_id = renderer.get('playlistId')
2814 yield self.url_result(
2815 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2816 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2819 video_id = renderer.get('videoId')
2821 yield self._extract_video(renderer)
2823 channel_id = renderer.get('channelId')
2826 renderer, lambda x: x['title']['simpleText'], compat_str)
2827 yield self.url_result(
2828 'https://www.youtube.com/channel/%s' % channel_id,
2829 ie=YoutubeTabIE.ie_key(), video_title=title)
2831 def _shelf_entries_from_content(self, shelf_renderer):
2832 content = shelf_renderer.get('content')
2833 if not isinstance(content, dict):
2835 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
2837 # TODO: add support for nested playlists so each shelf is processed
2838 # as separate playlist
2839 # TODO: this includes only first N items
2840 for entry in self._grid_entries(renderer):
2842 renderer = content.get('horizontalListRenderer')
2847 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2849 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2851 shelf_url = urljoin('https://www.youtube.com', ep)
2853 # Skipping links to another channels, note that checking for
2854 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2856 if skip_channels and '/channels?' in shelf_url:
2859 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2860 yield self.url_result(shelf_url, video_title=title)
2861 # Shelf may not contain shelf URL, fallback to extraction from content
2862 for entry in self._shelf_entries_from_content(shelf_renderer):
2865 def _playlist_entries(self, video_list_renderer):
2866 for content in video_list_renderer['contents']:
2867 if not isinstance(content, dict):
2869 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2870 if not isinstance(renderer, dict):
2872 video_id = renderer.get('videoId')
2875 yield self._extract_video(renderer)
2877 def _rich_entries(self, rich_grid_renderer):
2879 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
2880 video_id = renderer.get('videoId')
2883 yield self._extract_video(renderer)
2885 def _video_entry(self, video_renderer):
2886 video_id = video_renderer.get('videoId')
2888 return self._extract_video(video_renderer)
2890 def _post_thread_entries(self, post_thread_renderer):
2891 post_renderer = try_get(
2892 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2893 if not post_renderer:
2896 video_renderer = try_get(
2897 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2900 entry = self._video_entry(video_renderer)
2903 # inline video links
2904 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2906 if not isinstance(run, dict):
2909 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2912 if not YoutubeIE.suitable(ep_url):
2914 ep_video_id = YoutubeIE._match_id(ep_url)
2915 if video_id == ep_video_id:
2917 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2919 def _post_thread_continuation_entries(self, post_thread_continuation):
2920 contents = post_thread_continuation.get('contents')
2921 if not isinstance(contents, list):
2923 for content in contents:
2924 renderer = content.get('backstagePostThreadRenderer')
2925 if not isinstance(renderer, dict):
2927 for entry in self._post_thread_entries(renderer):
2931 def _rich_grid_entries(self
, contents
):
2932 for content
in contents
:
2933 video_renderer
= try_get(content
, lambda x
: x
['richItemRenderer']['content']['videoRenderer'], dict)
2935 entry
= self
._video
_entry
(video_renderer
)
2941 def _build_continuation_query(continuation, ctp=None):
2943 'ctoken': continuation,
2944 'continuation': continuation,
2951 def _extract_next_continuation_data(renderer):
2952 next_continuation = try_get(
2953 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2954 if not next_continuation:
2956 continuation = next_continuation.get('continuation')
2957 if not continuation:
2959 ctp = next_continuation.get('clickTrackingParams')
2960 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2963 def _extract_continuation(cls, renderer):
2964 next_continuation = cls._extract_next_continuation_data(renderer)
2965 if next_continuation:
2966 return next_continuation
2968 for key in ('contents', 'items'):
2969 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2970 for content in contents:
2971 if not isinstance(content, dict):
2973 continuation_ep = try_get(
2974 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2976 if not continuation_ep:
2978 continuation = try_get(
2979 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2980 if not continuation:
2982 ctp = continuation_ep.get('clickTrackingParams')
2983 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2985 def _entries(self, tab, item_id, identity_token, account_syncid, ytcfg):
2987 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
2988 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
2989 for content in contents:
2990 if not isinstance(content, dict):
2992 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
2994 renderer = content.get('richItemRenderer')
2996 for entry in self._rich_entries(renderer):
2998 continuation_list[0] = self._extract_continuation(parent_renderer)
3000 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
3001 for isr_content in isr_contents:
3002 if not isinstance(isr_content, dict):
3006 'playlistVideoListRenderer': self._playlist_entries,
3007 'gridRenderer': self._grid_entries,
3008 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
3009 'backstagePostThreadRenderer': self._post_thread_entries,
3010 'videoRenderer': lambda x: [self._video_entry(x)],
3012 for key, renderer in isr_content.items():
3013 if key not in known_renderers:
3015 for entry in known_renderers[key](renderer):
3018 continuation_list[0] = self._extract_continuation(renderer)
3021 if not continuation_list[0]:
3022 continuation_list[0] = self._extract_continuation(is_renderer)
3024 if not continuation_list[0]:
3025 continuation_list[0] = self._extract_continuation(parent_renderer)
3027 continuation_list = [None] # Python 2 doesnot support nonlocal
3028 tab_content = try_get(tab, lambda x: x['content'], dict)
3032 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
3033 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
3034 for entry in extract_entries(parent_renderer):
3036 continuation = continuation_list[0]
3037 context = self._extract_context(ytcfg)
3038 visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
3040 for page_num in itertools.count(1):
3041 if not continuation:
3044 'continuation': continuation['continuation'],
3045 'clickTracking': {'clickTrackingParams': continuation['itct']}
3047 headers = self._generate_api_headers(ytcfg, identity_token, account_syncid, visitor_data)
3048 response = self._extract_response(
3049 item_id='%s page %s' % (item_id, page_num),
3050 query=query, headers=headers, ytcfg=ytcfg,
3051 check_get_keys=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3055 visitor_data = try_get(
3056 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
3058 known_continuation_renderers = {
3059 'playlistVideoListContinuation': self._playlist_entries,
3060 'gridContinuation': self._grid_entries,
3061 'itemSectionContinuation': self._post_thread_continuation_entries,
3062 'sectionListContinuation': extract_entries, # for feeds
3064 continuation_contents = try_get(
3065 response, lambda x: x['continuationContents'], dict) or {}
3066 continuation_renderer = None
3067 for key, value in continuation_contents.items():
3068 if key not in known_continuation_renderers:
3070 continuation_renderer = value
3071 continuation_list = [None]
3072 for entry in known_continuation_renderers[key](continuation_renderer):
3074 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
3076 if continuation_renderer:
3080 'gridPlaylistRenderer': (self._grid_entries, 'items'),
3081 'gridVideoRenderer': (self._grid_entries, 'items'),
3082 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
3083 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
3084 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
3085 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents')
3087 on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
3088 continuation_items = try_get(
3089 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
3090 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
3091 video_items_renderer = None
3092 for key, value in continuation_item.items():
3093 if key not in known_renderers:
3095 video_items_renderer = {known_renderers[key][1]: continuation_items}
3096 continuation_list = [None]
3097 for entry in known_renderers[key][0](video_items_renderer):
3099 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
3101 if video_items_renderer:
3106 def _extract_selected_tab(tabs):
3108 if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
3109 return tab['tabRenderer']
3111 raise ExtractorError('Unable to find selected tab')
3114 def _extract_uploader(data):
3116 sidebar_renderer = try_get(
3117 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
3118 if sidebar_renderer:
3119 for item in sidebar_renderer:
3120 if not isinstance(item, dict):
3122 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
3123 if not isinstance(renderer, dict):
3126 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
3128 uploader['uploader'] = owner.get('text')
3129 uploader['uploader_id'] = try_get(
3130 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
3131 uploader['uploader_url'] = urljoin(
3132 'https://www.youtube.com/',
3133 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
3134 return {k: v for k, v in uploader.items() if v is not None}
3136 def _extract_from_tabs(self, item_id, webpage, data, tabs):
3137 playlist_id = title = description = channel_url = channel_name = channel_id = None
3138 thumbnails_list = tags = []
3140 selected_tab = self._extract_selected_tab(tabs)
3142 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
3144 channel_name = renderer.get('title')
3145 channel_url = renderer.get('channelUrl')
3146 channel_id = renderer.get('externalId')
3149 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
3152 title = renderer.get('title')
3153 description = renderer.get('description', '')
3154 playlist_id = channel_id
3155 tags = renderer.get('keywords', '').split()
3157 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
3160 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
3165 for t in thumbnails_list:
3166 if not isinstance(t, dict):
3168 thumbnail_url = url_or_none(t.get('url'))
3169 if not thumbnail_url:
3172 'url': thumbnail_url,
3173 'width': int_or_none(t.get('width')),
3174 'height': int_or_none(t.get('height')),
3176 if playlist_id is None:
3177 playlist_id = item_id
3180 try_get(data, lambda x: x['header']['hashtagHeaderRenderer']['hashtag']['simpleText'])
3182 title += format_field(selected_tab, 'title', ' - %s')
3185 'playlist_id': playlist_id,
3186 'playlist_title': title,
3187 'playlist_description': description,
3188 'uploader': channel_name,
3189 'uploader_id': channel_id,
3190 'uploader_url': channel_url,
3191 'thumbnails': thumbnails,
3195 metadata.update(self._extract_uploader(data))
3197 'channel': metadata['uploader'],
3198 'channel_id': metadata['uploader_id'],
3199 'channel_url': metadata['uploader_url']})
3200 return self.playlist_result(
3202 selected_tab, playlist_id,
3203 self._extract_identity_token(webpage, item_id),
3204 self._extract_account_syncid(data),
3205 self._extract_ytcfg(item_id, webpage)),
3208 def _extract_mix_playlist(self, playlist, playlist_id, data, webpage):
3209 first_id = last_id = None
3210 ytcfg = self._extract_ytcfg(playlist_id, webpage)
3211 headers = self._generate_api_headers(
3212 ytcfg, account_syncid=self._extract_account_syncid(data),
3213 identity_token=self._extract_identity_token(webpage, item_id=playlist_id),
3214 visitor_data=try_get(self._extract_context(ytcfg), lambda x: x['client']['visitorData'], compat_str))
3215 for page_num in itertools.count(1):
3216 videos = list(self._playlist_entries(playlist))
3219 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
3220 if start >= len(videos):
3222 for video in videos[start:]:
3223 if video['id'] == first_id:
3224 self.to_screen('First video %s found again; Assuming end of Mix' % first_id)
3227 first_id = first_id or videos[0]['id']
3228 last_id = videos[-1]['id']
3229 watch_endpoint = try_get(
3230 playlist, lambda x: x['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
3232 'playlistId': playlist_id,
3233 'videoId': watch_endpoint.get('videoId') or last_id,
3234 'index': watch_endpoint.get('index') or len(videos),
3235 'params': watch_endpoint.get('params') or 'OAE%3D'
3237 response = self._extract_response(
3238 item_id='%s page %d' % (playlist_id, page_num),
3242 check_get_keys='contents'
3245 response, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3247 def _extract_from_playlist(self, item_id, url, data, playlist, webpage):
3248 title = playlist.get('title') or try_get(
3249 data, lambda x: x['titleText']['simpleText'], compat_str)
3250 playlist_id = playlist.get('playlistId') or item_id
3252 # Delegating everything except mix playlists to regular tab-based playlist URL
3253 playlist_url = urljoin(url, try_get(
3254 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
3256 if playlist_url and playlist_url != url:
3257 return self.url_result(
3258 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
3261 return self.playlist_result(
3262 self._extract_mix_playlist(playlist, playlist_id, data, webpage),
3263 playlist_id=playlist_id, playlist_title=title)
3265 def _extract_alerts(self, data, expected=False):
3267 def _real_extract_alerts():
3268 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
3269 if not isinstance(alert_dict, dict):
3271 for alert in alert_dict.values():
3272 alert_type = alert.get('type')
3275 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str) or ''
3277 yield alert_type, message
3278 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
3279 message += try_get(run, lambda x: x['text'], compat_str)
3281 yield alert_type, message
3285 for alert_type, alert_message in _real_extract_alerts():
3286 if alert_type.lower() == 'error':
3287 errors.append([alert_type, alert_message])
3289 warnings.append([alert_type, alert_message])
3291 for alert_type, alert_message in (warnings + errors[:-1]):
3292 self._downloader.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3294 raise ExtractorError('YouTube said: %s' % errors[-1][1], expected=expected)
3296 def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
3297 ytcfg=None, check_get_keys=None, ep='browse'):
3301 retries = self._downloader.params.get('extractor_retries', 3)
3302 if check_get_keys is None:
3304 while count < retries:
3307 self.report_warning('%s. Retrying ...' % last_error)
3309 response = self._call_api(
3310 ep=ep, fatal=True, headers=headers,
3313 context=self._extract_context(ytcfg),
3314 api_key=self._extract_api_key(ytcfg),
3315 note='%s%s' % (note, ' (retry #%d)' % count if count else ''))
3316 except ExtractorError as e:
3317 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
3318 # Downloading page may result in intermittent 5xx HTTP error
3319 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
3320 last_error = 'HTTP Error %s' % e.cause.code
3325 # Youtube may send alerts if there was an issue with the continuation page
3326 self._extract_alerts(response, expected=False)
3327 if not check_get_keys or dict_get(response, check_get_keys):
3329 # Youtube sometimes sends incomplete data
3330 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
3331 last_error = 'Incomplete data received'
3332 if count >= retries:
3333 self._downloader.report_error(last_error)
3336 def _extract_webpage(self, url, item_id):
3337 retries = self._downloader.params.get('extractor_retries', 3)
3339 last_error = 'Incomplete yt initial data recieved'
3340 while count < retries:
3342 # Sometimes youtube returns a webpage with incomplete ytInitialData
3343 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3345 self.report_warning('%s. Retrying ...' % last_error)
3346 webpage = self._download_webpage(
3348 'Downloading webpage%s' % (' (retry #%d)' % count if count else ''))
3349 data = self._extract_yt_initial_data(item_id, webpage)
3350 self._extract_alerts(data, expected=True)
3351 if data.get('contents') or data.get('currentVideoEndpoint'):
3353 if count >= retries:
3354 self._downloader.report_error(last_error)
3355 return webpage, data
3357 def _real_extract(self, url):
3358 item_id = self._match_id(url)
3359 url = compat_urlparse.urlunparse(
3360 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3362 # This is not matched in a channel page with a tab selected
3363 mobj = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
3364 mobj = mobj.groupdict() if mobj else {}
3365 if mobj and not mobj.get('not_channel'):
3366 self._downloader.report_warning(
3367 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3368 'To download only the videos in the home page, add a "/featured" to the URL')
3369 url = '%s/videos%s' % (mobj.get('pre'), mobj.get('post') or '')
3371 # Handle both video/playlist URLs
3372 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3373 video_id = qs.get('v', [None])[0]
3374 playlist_id = qs.get('list', [None])[0]
3376 if not video_id and (mobj.get('not_channel') or '').startswith('watch'):
3378 # If there is neither video or playlist ids,
3379 # youtube redirects to home page, which is undesirable
3380 raise ExtractorError('Unable to recognize tab page')
3381 self._downloader.report_warning('A video URL was given without video ID. Trying to download playlist %s' % playlist_id)
3382 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3384 if video_id and playlist_id:
3385 if self._downloader.params.get('noplaylist'):
3386 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3387 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3388 self.to_screen('Downloading playlist %s; add --no-playlist to just download video %s' % (playlist_id, video_id))
3390 webpage, data = self._extract_webpage(url, item_id)
3393 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3395 return self._extract_from_tabs(item_id, webpage, data, tabs)
3398 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3400 return self._extract_from_playlist(item_id, url, data, playlist, webpage)
3403 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3404 compat_str) or video_id
3406 self._downloader.report_warning('Unable to recognize playlist. Downloading just video %s' % video_id)
3407 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3409 raise ExtractorError('Unable to recognize tab page')
3412 class YoutubePlaylistIE(InfoExtractor):
3413 IE_DESC = 'YouTube.com playlists'
3414 _VALID_URL = r'''(?x
)(?
:
3419 youtube(?
:kids
)?\
.com|
3424 (?P
<id>%(playlist_id)s)
3425 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3426 IE_NAME = 'youtube:playlist'
3428 'note': 'issue #673',
3429 'url': 'PLBB231211A4F62143',
3431 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3432 'id': 'PLBB231211A4F62143',
3433 'uploader': 'Wickydoo',
3434 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3436 'playlist_mincount': 29,
3438 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3440 'title': 'YDL_safe_search',
3441 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3443 'playlist_count': 2,
3444 'skip': 'This playlist is private',
3447 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3448 'playlist_count': 4,
3451 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3452 'uploader': 'milan',
3453 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3456 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3457 'playlist_mincount': 982,
3459 'title': '2018 Chinese New Singles (11/6 updated)',
3460 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3462 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3465 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3466 'only_matching': True,
3468 # music album playlist
3469 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3470 'only_matching': True,
3474 def suitable(cls, url):
3475 return False if YoutubeTabIE.suitable(url) else super(
3476 YoutubePlaylistIE, cls).suitable(url)
3478 def _real_extract(self, url):
3479 playlist_id = self._match_id(url)
3480 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3482 qs = {'list': playlist_id}
3483 return self.url_result(
3484 update_url_query('https://www.youtube.com/playlist', qs),
3485 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3488 class YoutubeYtBeIE(InfoExtractor):
3489 IE_DESC = 'youtu.be'
3490 _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}
3492 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3494 'id': 'yeWKywCrFtk',
3496 'title': 'Small Scale Baler and Braiding Rugs',
3497 'uploader': 'Backus-Page House Museum',
3498 'uploader_id': 'backuspagemuseum',
3499 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3500 'upload_date': '20161008',
3501 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3502 'categories': ['Nonprofits & Activism'],
3505 'dislike_count': int,
3509 'skip_download': True,
3512 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3513 'only_matching': True,
3516 def _real_extract(self, url):
3517 mobj = re.match(self._VALID_URL, url)
3518 video_id = mobj.group('id')
3519 playlist_id = mobj.group('playlist_id')
3520 return self.url_result(
3521 update_url_query('https://www.youtube.com/watch', {
3523 'list': playlist_id,
3524 'feature': 'youtu.be',
3525 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3528 class YoutubeYtUserIE(InfoExtractor):
3529 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3530 _VALID_URL = r'ytuser:(?P<id>.+)'
3532 'url': 'ytuser:phihag',
3533 'only_matching': True,
3536 def _real_extract(self, url):
3537 user_id = self._match_id(url)
3538 return self.url_result(
3539 'https://www.youtube.com/user/%s' % user_id,
3540 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3543 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3544 IE_NAME = 'youtube:favorites'
3545 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3546 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3547 _LOGIN_REQUIRED = True
3550 'only_matching': True,
3552 'url': ':ytfavorites',
3553 'only_matching': True,
3556 def _real_extract(self, url):
3557 return self.url_result(
3558 'https://www.youtube.com/playlist?list=LL',
3559 ie=YoutubeTabIE.ie_key())
3562 class YoutubeSearchIE(SearchInfoExtractor, YoutubeTabIE):
3563 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3564 # there doesn't appear to be a real limit, for example if you search for
3565 # 'python' you get more than 8.000.000 results
3566 _MAX_RESULTS = float('inf')
3567 IE_NAME = 'youtube:search'
3568 _SEARCH_KEY = 'ytsearch'
3569 _SEARCH_PARAMS = None
3572 def _entries(self, query, n):
3573 data = {'query': query}
3574 if self._SEARCH_PARAMS:
3575 data['params'] = self._SEARCH_PARAMS
3577 for page_num in itertools.count(1):
3578 search = self._extract_response(
3579 item_id='query "%s" page %s' % (query, page_num), ep='search', query=data,
3580 check_get_keys=('contents', 'onResponseReceivedCommands')
3584 slr_contents = try_get(
3586 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3587 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3589 if not slr_contents:
3592 # Youtube sometimes adds promoted content to searches,
3593 # changing the index location of videos and token.
3594 # So we search through all entries till we find them.
3595 continuation_token = None
3596 for slr_content in slr_contents:
3597 if continuation_token is None:
3598 continuation_token = try_get(
3600 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3603 isr_contents = try_get(
3605 lambda x: x['itemSectionRenderer']['contents'],
3607 if not isr_contents:
3609 for content in isr_contents:
3610 if not isinstance(content, dict):
3612 video = content.get('videoRenderer')
3613 if not isinstance(video, dict):
3615 video_id = video.get('videoId')
3619 yield self._extract_video(video)
3624 if not continuation_token:
3626 data['continuation'] = continuation_token
3628 def _get_n_results(self, query, n):
3629 """Get a specified number of results for a query"""
3630 return self.playlist_result(self._entries(query, n), query)
3633 class YoutubeSearchDateIE(YoutubeSearchIE):
3634 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3635 _SEARCH_KEY = 'ytsearchdate'
3636 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3637 _SEARCH_PARAMS = 'CAI%3D'
3640 class YoutubeSearchURLIE(YoutubeSearchIE):
3641 IE_DESC = 'YouTube.com search URLs'
3642 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
3643 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
3644 # _MAX_RESULTS = 100
3646 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3647 'playlist_mincount': 5,
3649 'title': 'youtube-dl test video',
3652 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3653 'only_matching': True,
3657 def _make_valid_url(cls):
3658 return cls._VALID_URL
3660 def _real_extract(self, url):
3661 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
3662 query = (qs.get('search_query') or qs.get('q'))[0]
3663 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
3664 return self._get_n_results(query, self._MAX_RESULTS)
3667 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3669 Base class for feed extractors
3670 Subclasses must define the _FEED_NAME property.
3672 _LOGIN_REQUIRED = True
3677 return 'youtube:%s' % self._FEED_NAME
3679 def _real_initialize(self):
3682 def _real_extract(self, url):
3683 return self.url_result(
3684 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3685 ie=YoutubeTabIE.ie_key())
3688 class YoutubeWatchLaterIE(InfoExtractor):
3689 IE_NAME = 'youtube:watchlater'
3690 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3691 _VALID_URL = r':ytwatchlater'
3693 'url': ':ytwatchlater',
3694 'only_matching': True,
3697 def _real_extract(self, url):
3698 return self.url_result(
3699 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3702 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3703 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3704 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
3705 _FEED_NAME = 'recommended'
3708 'only_matching': True,
3710 'url': ':ytrecommended',
3711 'only_matching': True,
3713 'url': 'https://youtube.com',
3714 'only_matching': True,
3718 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3719 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
3720 _VALID_URL = r':ytsub(?:scription)?s?'
3721 _FEED_NAME = 'subscriptions'
3724 'only_matching': True,
3726 'url': ':ytsubscriptions',
3727 'only_matching': True,
3731 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3732 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
3733 _VALID_URL = r':ythis(?:tory)?'
3734 _FEED_NAME = 'history'
3736 'url': ':ythistory',
3737 'only_matching': True,
3741 class YoutubeTruncatedURLIE(InfoExtractor):
3742 IE_NAME = 'youtube:truncated_url'
3743 IE_DESC = False # Do not list
3744 _VALID_URL = r'''(?x
)
3746 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
3749 annotation_id
=annotation_
[^
&]+|
3755 attribution_link
\?a
=[^
&]+
3761 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3762 'only_matching': True,
3764 'url': 'https://www.youtube.com/watch?',
3765 'only_matching': True,
3767 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3768 'only_matching': True,
3770 'url': 'https://www.youtube.com/watch?feature=foo',
3771 'only_matching': True,
3773 'url': 'https://www.youtube.com/watch?hl=en-GB',
3774 'only_matching': True,
3776 'url': 'https://www.youtube.com/watch?t=2372',
3777 'only_matching': True,
3780 def _real_extract(self, url):
3781 raise ExtractorError(
3782 'Did you forget to quote the URL? Remember that & is a meta '
3783 'character in most shells, so you want to put the URL in quotes, '
3785 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3786 ' or simply youtube-dl BaW_jenozKc .',
3790 class YoutubeTruncatedIDIE(InfoExtractor):
3791 IE_NAME = 'youtube:truncated_id'
3792 IE_DESC = False # Do not list
3793 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
3796 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
3797 'only_matching': True,
3800 def _real_extract(self, url):
3801 video_id = self._match_id(url)
3802 raise ExtractorError(
3803 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),