3 from __future__
import unicode_literals
14 from .common
import InfoExtractor
, SearchInfoExtractor
15 from ..compat
import (
21 compat_urllib_parse_unquote_plus
,
22 compat_urllib_parse_urlencode
,
23 compat_urllib_parse_urlparse
,
26 from ..jsinterp
import JSInterpreter
52 class YoutubeBaseInfoExtractor(InfoExtractor
):
53 """Provide base functions for Youtube extractors"""
54 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
55 _TWOFACTOR_URL
= 'https://accounts.google.com/signin/challenge'
57 _LOOKUP_URL
= 'https://accounts.google.com/_/signin/sl/lookup'
58 _CHALLENGE_URL
= 'https://accounts.google.com/_/signin/sl/challenge'
59 _TFA_URL
= 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
62 r
'embed|e|watch_popup|channel|c|user|playlist|watch|w|v|movies|results|shared|hashtag|'
63 r
'storefront|oops|index|account|reporthistory|t/terms|about|upload|signin|logout|'
64 r
'feed/(?:watch_later|history|subscriptions|library|trending|recommended)')
66 _NETRC_MACHINE
= 'youtube'
67 # If True it will raise an error if no login info is provided
68 _LOGIN_REQUIRED
= False
70 _PLAYLIST_ID_RE
= r
'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
72 def _ids_to_results(self
, ids
):
74 self
.url_result(vid_id
, 'Youtube', video_id
=vid_id
)
79 Attempt to log in to YouTube.
80 True is returned if successful or skipped.
81 False is returned if login failed.
83 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
85 username
, password
= self
._get
_login
_info
()
86 # No authentication to be performed
88 if self
._LOGIN
_REQUIRED
and self
._downloader
.params
.get('cookiefile') is None:
89 raise ExtractorError('No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
90 # if self._downloader.params.get('cookiefile'): # TODO remove 'and False' later - too many people using outdated cookies and open issues, remind them.
91 # self.to_screen('[Cookies] Reminder - Make sure to always use up to date cookies!')
94 login_page
= self
._download
_webpage
(
95 self
._LOGIN
_URL
, None,
96 note
='Downloading login page',
97 errnote
='unable to fetch login page', fatal
=False)
98 if login_page
is False:
101 login_form
= self
._hidden
_inputs
(login_page
)
103 def req(url
, f_req
, note
, errnote
):
104 data
= login_form
.copy()
107 'checkConnection': 'youtube',
108 'checkedDomains': 'youtube',
110 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
111 'f.req': json
.dumps(f_req
),
112 'flowName': 'GlifWebSignIn',
113 'flowEntry': 'ServiceLogin',
114 # TODO: reverse actual botguard identifier generation algo
115 'bgRequest': '["identifier",""]',
117 return self
._download
_json
(
118 url
, None, note
=note
, errnote
=errnote
,
119 transform_source
=lambda s
: re
.sub(r
'^[^[]*', '', s
),
121 data
=urlencode_postdata(data
), headers
={
122 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
123 'Google-Accounts-XSRF': 1,
127 self
._downloader
.report_warning(message
)
131 None, [], None, 'US', None, None, 2, False, True,
135 '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',
137 1, [None, None, []], None, None, None, True
142 lookup_results
= req(
143 self
._LOOKUP
_URL
, lookup_req
,
144 'Looking up account info', 'Unable to look up account info')
146 if lookup_results
is False:
149 user_hash
= try_get(lookup_results
, lambda x
: x
[0][2], compat_str
)
151 warn('Unable to extract user hash')
156 None, 1, None, [1, None, None, None, [password
, None, True]],
158 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],
159 1, [None, None, []], None, None, None, True
162 challenge_results
= req(
163 self
._CHALLENGE
_URL
, challenge_req
,
164 'Logging in', 'Unable to log in')
166 if challenge_results
is False:
169 login_res
= try_get(challenge_results
, lambda x
: x
[0][5], list)
171 login_msg
= try_get(login_res
, lambda x
: x
[5], compat_str
)
173 'Unable to login: %s' % 'Invalid password'
174 if login_msg
== 'INCORRECT_ANSWER_ENTERED' else login_msg
)
177 res
= try_get(challenge_results
, lambda x
: x
[0][-1], list)
179 warn('Unable to extract result entry')
182 login_challenge
= try_get(res
, lambda x
: x
[0][0], list)
184 challenge_str
= try_get(login_challenge
, lambda x
: x
[2], compat_str
)
185 if challenge_str
== 'TWO_STEP_VERIFICATION':
186 # SEND_SUCCESS - TFA code has been successfully sent to phone
187 # QUOTA_EXCEEDED - reached the limit of TFA codes
188 status
= try_get(login_challenge
, lambda x
: x
[5], compat_str
)
189 if status
== 'QUOTA_EXCEEDED':
190 warn('Exceeded the limit of TFA codes, try later')
193 tl
= try_get(challenge_results
, lambda x
: x
[1][2], compat_str
)
195 warn('Unable to extract TL')
198 tfa_code
= self
._get
_tfa
_info
('2-step verification code')
202 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
203 '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
206 tfa_code
= remove_start(tfa_code
, 'G-')
209 user_hash
, None, 2, None,
211 9, None, None, None, None, None, None, None,
212 [None, tfa_code
, True, 2]
216 self
._TFA
_URL
.format(tl
), tfa_req
,
217 'Submitting TFA code', 'Unable to submit TFA code')
219 if tfa_results
is False:
222 tfa_res
= try_get(tfa_results
, lambda x
: x
[0][5], list)
224 tfa_msg
= try_get(tfa_res
, lambda x
: x
[5], compat_str
)
226 'Unable to finish TFA: %s' % 'Invalid TFA code'
227 if tfa_msg
== 'INCORRECT_ANSWER_ENTERED' else tfa_msg
)
230 check_cookie_url
= try_get(
231 tfa_results
, lambda x
: x
[0][-1][2], compat_str
)
234 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
235 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
236 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
238 challenge
= CHALLENGES
.get(
240 '%s returned error %s.' % (self
.IE_NAME
, challenge_str
))
241 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge
)
244 check_cookie_url
= try_get(res
, lambda x
: x
[2], compat_str
)
246 if not check_cookie_url
:
247 warn('Unable to extract CheckCookie URL')
250 check_cookie_results
= self
._download
_webpage
(
251 check_cookie_url
, None, 'Checking cookie', fatal
=False)
253 if check_cookie_results
is False:
256 if 'https://myaccount.google.com/' not in check_cookie_results
:
257 warn('Unable to log in')
262 def _download_webpage_handle(self
, *args
, **kwargs
):
263 query
= kwargs
.get('query', {}).copy()
264 kwargs
['query'] = query
265 return super(YoutubeBaseInfoExtractor
, self
)._download
_webpage
_handle
(
266 *args
, **compat_kwargs(kwargs
))
268 def _real_initialize(self
):
269 if self
._downloader
is None:
271 if not self
._login
():
274 _DEFAULT_API_DATA
= {
278 'clientVersion': '2.20210301.08.00',
283 _YT_INITIAL_DATA_RE
= r
'(?:window\s*\[\s*["\']ytInitialData
["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
284 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
285 _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
287 def _generate_sapisidhash_header(self):
288 sapisid_cookie = self._get_cookies('https://www.youtube.com').get('SAPISID')
289 if sapisid_cookie is None:
291 time_now = round(time.time())
292 sapisidhash = hashlib.sha1((str(time_now) + " " + sapisid_cookie.value + " " + "https
://www
.youtube
.com
").encode("utf
-8")).hexdigest()
293 return "SAPISIDHASH
%s_%s" % (time_now, sapisidhash)
295 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
296 note='Downloading API JSON', errnote='Unable to download API page'):
297 data = self._DEFAULT_API_DATA.copy()
299 headers = headers or {}
300 headers.update({'content-type': 'application/json'})
301 auth = self._generate_sapisidhash_header()
303 headers.update({'Authorization': auth, 'X-Origin': 'https://www.youtube.com'})
305 return self._download_json(
306 'https://www.youtube.com/youtubei/v1/%s' % ep,
307 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
308 data=json.dumps(data).encode('utf8'), headers=headers,
309 query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
311 def _extract_yt_initial_data(self, video_id, webpage):
312 return self._parse_json(
314 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
315 self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
318 def _extract_ytcfg(self, video_id, webpage):
319 return self._parse_json(
321 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
322 default='{}'), video_id, fatal=False)
324 def _extract_video(self, renderer):
325 video_id = renderer.get('videoId')
328 (lambda x: x['title']['runs'][0]['text'],
329 lambda x: x['title']['simpleText']), compat_str)
330 description = try_get(
331 renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
333 duration = parse_duration(try_get(
334 renderer, lambda x: x['lengthText']['simpleText'], compat_str))
335 view_count_text = try_get(
336 renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
337 view_count = str_to_int(self._search_regex(
338 r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
339 'view count', default=None))
342 (lambda x: x['ownerText']['runs'][0]['text'],
343 lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
345 '_type': 'url_transparent',
346 'ie_key': YoutubeIE.ie_key(),
350 'description': description,
351 'duration': duration,
352 'view_count': view_count,
353 'uploader': uploader,
357 class YoutubeIE(YoutubeBaseInfoExtractor):
358 IE_DESC = 'YouTube.com'
360 # invidious-redirect websites
361 r'(?:www\.)?redirect\.invidious\.io',
362 r'(?:(?:www|dev)\.)?invidio\.us',
363 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
364 r'(?:www\.)?invidious\.pussthecat\.org',
365 r'(?:www\.)?invidious\.048596\.xyz',
366 r'(?:www\.)?invidious\.zee\.li',
367 r'(?:www\.)?vid\.puffyan\.us',
368 r'(?:(?:www|au)\.)?ytprivate\.com',
369 r'(?:www\.)?invidious\.namazso\.eu',
370 r'(?:www\.)?invidious\.ethibox\.fr',
371 r'(?:www\.)?inv\.skyn3t\.in',
372 r'(?:www\.)?invidious\.himiko\.cloud',
373 r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
374 r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
375 r'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
376 r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
377 # youtube-dl invidious instances list
378 r'(?:(?:www|no)\.)?invidiou\.sh',
379 r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
380 r'(?:www\.)?invidious\.kabi\.tk',
381 r'(?:www\.)?invidious\.13ad\.de',
382 r'(?:www\.)?invidious\.mastodon\.host',
383 r'(?:www\.)?invidious\.zapashcanon\.fr',
384 r'(?:www\.)?invidious\.kavin\.rocks',
385 r'(?:www\.)?invidious\.tube',
386 r'(?:www\.)?invidiou\.site',
387 r'(?:www\.)?invidious\.site',
388 r'(?:www\.)?invidious\.xyz',
389 r'(?:www\.)?invidious\.nixnet\.xyz',
390 r'(?:www\.)?invidious\.drycat\.fr',
391 r'(?:www\.)?tube\.poal\.co',
392 r'(?:www\.)?tube\.connect\.cafe',
393 r'(?:www\.)?vid\.wxzm\.sx',
394 r'(?:www\.)?vid\.mint\.lgbt',
395 r'(?:www\.)?yewtu\.be',
396 r'(?:www\.)?yt\.elukerio\.org',
397 r'(?:www\.)?yt\.lelux\.fi',
398 r'(?:www\.)?invidious\.ggc-project\.de',
399 r'(?:www\.)?yt\.maisputain\.ovh',
400 r'(?:www\.)?invidious\.toot\.koeln',
401 r'(?:www\.)?invidious\.fdn\.fr',
402 r'(?:www\.)?watch\.nettohikari\.com',
403 r'(?:www\.)?kgg2m7yk5aybusll\.onion',
404 r'(?:www\.)?qklhadlycap4cnod\.onion',
405 r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
406 r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
407 r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
408 r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
409 r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
410 r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
412 _VALID_URL = r"""(?x)^
414 (?:https?://|//) # http(s):// or protocol-independent URL
415 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
416 (?:www\.)?deturl\.com/www\.youtube\.com|
417 (?:www\.)?pwnyoutube\.com|
418 (?:www\.)?hooktube\.com|
419 (?:www\.)?yourepeat\.com|
422 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
423 (?:.*?\#/)? # handle anchor (#/) redirect urls
424 (?: # the various things that can precede the ID:
425 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
426 |(?: # or the v= param in all its forms
427 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
428 (?:\?|\#!?) # the params delimiter ? or # or #!
429 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&v=V36LpHqtcDY)
434 youtu\.be| # just youtu.be/xxxx
435 vid\.plus| # or vid.plus/xxxx
436 zwearz\.com/watch| # or zwearz.com/watch/xxxx
439 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
441 )? # all until now is optional -> you can pass the naked ID
442 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
445 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
446 WL # WL are handled by the watch later IE
449 (?(1).+)? # if we found the ID, everything can follow
451 'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE,
452 'invidious': '|'.join(_INVIDIOUS_SITES),
455 r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
456 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$',
457 r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
460 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
461 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
462 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
463 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
464 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
465 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
466 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
467 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
468 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
469 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
470 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
471 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
472 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
473 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
474 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
475 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
476 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
477 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
481 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
482 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
483 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
484 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
485 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
486 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
487 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
489 # Apple HTTP Live Streaming
490 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
491 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
492 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
493 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
494 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
495 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
496 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
497 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
500 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
501 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
502 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
503 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
504 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
505 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
506 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
507 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
508 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
509 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
510 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
511 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
514 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
515 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
516 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
517 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
518 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
519 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
520 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
523 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
524 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
525 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
526 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
527 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
528 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
529 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
530 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
531 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
532 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
533 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
534 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
535 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
536 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
537 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
538 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
539 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
540 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
541 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
542 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
543 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
544 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
547 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
548 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
550 # Dash webm audio with opus inside
551 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
552 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
553 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
556 '_rtmp': {'protocol': 'rtmp'},
558 # av01 video only formats sometimes served with "unknown
" codecs
559 '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
560 '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
561 '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
562 '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
564 _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
571 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
575 'title': 'youtube-dl test video "\'/\\ä↭𝕐
',
576 'uploader
': 'Philipp Hagemeister
',
577 'uploader_id
': 'phihag
',
578 'uploader_url
': r're
:https?
://(?
:www\
.)?youtube\
.com
/user
/phihag
',
579 'channel_id
': 'UCLqxVugv74EIW3VWh2NOa3Q
',
580 'channel_url
': r're
:https?
://(?
:www\
.)?youtube\
.com
/channel
/UCLqxVugv74EIW3VWh2NOa3Q
',
581 'upload_date
': '20121002',
582 '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 .',
583 'categories': ['Science & Technology'],
584 'tags': ['youtube-dl'],
588 'dislike_count': int,
594 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
595 'note': 'Embed-only video (#1746)',
599 'upload_date': '20120608',
600 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
601 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
602 'uploader': 'SET India',
603 'uploader_id': 'setindia',
604 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
607 'skip': 'Private video',
610 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
611 'note': 'Use the first video ID in the URL',
615 'title': 'youtube-dl test video "\'/\\ä↭𝕐
',
616 'uploader
': 'Philipp Hagemeister
',
617 'uploader_id
': 'phihag
',
618 'uploader_url
': r're
:https?
://(?
:www\
.)?youtube\
.com
/user
/phihag
',
619 'upload_date
': '20121002',
620 'description
': 'test chars
: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
621 'categories': ['Science & Technology'],
622 'tags': ['youtube-dl'],
626 'dislike_count': int,
629 'skip_download': True,
633 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
634 'note': '256k DASH audio (format 141) via DASH manifest',
638 'upload_date': '20121002',
639 'uploader_id': '8KVIDEO',
640 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
642 'uploader': '8KVIDEO',
643 'title': 'UHDTV TEST 8K VIDEO.mp4'
646 'youtube_include_dash_manifest': True,
649 'skip': 'format 141 not served anymore',
651 # DASH manifest with encrypted signature
653 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
657 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
658 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
660 'uploader': 'AfrojackVEVO',
661 'uploader_id': 'AfrojackVEVO',
662 'upload_date': '20131011',
666 'youtube_include_dash_manifest': True,
667 'format': '141/bestaudio[ext=m4a]',
672 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
677 'upload_date': '20100909',
678 'uploader': 'Amazing Atheist',
679 'uploader_id': 'TheAmazingAtheist',
680 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
681 'title': 'Burning Everyone\'s Koran',
682 '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',
685 # Normal age-gate video (embed allowed)
687 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
691 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
692 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
694 'uploader': 'The Witcher',
695 'uploader_id': 'WitcherGame',
696 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
697 'upload_date': '20140605',
701 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
702 # YouTube Red ad is not captured for creator
704 'url': '__2ABJjxzNo',
709 'upload_date': '20100430',
710 'uploader_id': 'deadmau5',
711 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
712 'creator': 'deadmau5',
713 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
714 'uploader': 'deadmau5',
715 'title': 'Deadmau5 - Some Chords (HD)',
716 'alt_title': 'Some Chords',
718 'expected_warnings': [
719 'DASH manifest missing',
722 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
724 'url': 'lqQg6PlCWgI',
729 'upload_date': '20150827',
730 'uploader_id': 'olympic',
731 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
732 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
733 'uploader': 'Olympic',
734 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
737 'skip_download': 'requires avconv',
742 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
746 'stretched_ratio': 16 / 9.,
748 'upload_date': '20110310',
749 'uploader_id': 'AllenMeow',
750 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
751 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
753 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
756 # url_encoded_fmt_stream_map is empty string
758 'url': 'qEJwOuvDf7I',
762 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
764 'upload_date': '20150404',
765 'uploader_id': 'spbelect',
766 'uploader': 'Наблюдатели Петербурга',
769 'skip_download': 'requires avconv',
771 'skip': 'This live event has ended.',
773 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
775 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
779 'title': 'md5:7b81415841e02ecd4313668cde88737a',
780 'description': 'md5:116377fd2963b81ec4ce64b542173306',
782 'upload_date': '20150625',
783 'uploader_id': 'dorappi2000',
784 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
785 'uploader': 'dorappi2000',
786 'formats': 'mincount:31',
788 'skip': 'not actual anymore',
790 # DASH manifest with segment_list
792 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
793 'md5': '8ce563a1d667b599d21064e982ab9e31',
797 'upload_date': '20150501', # According to '<meta itemprop="datePublished
"', but in other places it's 20150510
798 'uploader': 'Airtek',
799 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
800 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
801 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
804 'youtube_include_dash_manifest': True,
805 'format': '135', # bestvideo
807 'skip': 'This live event has ended.',
810 # Multifeed videos (multiple cameras), URL is for Main Camera
811 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
814 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
815 'description': 'md5:e03b909557865076822aa169218d6a5d',
821 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
822 'description': 'md5:e03b909557865076822aa169218d6a5d',
824 'upload_date': '20161111',
825 'uploader': 'Team PGP',
826 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
827 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
833 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
834 'description': 'md5:e03b909557865076822aa169218d6a5d',
836 'upload_date': '20161111',
837 'uploader': 'Team PGP',
838 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
839 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
845 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
846 'description': 'md5:e03b909557865076822aa169218d6a5d',
848 'upload_date': '20161111',
849 'uploader': 'Team PGP',
850 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
851 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
857 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
858 'description': 'md5:e03b909557865076822aa169218d6a5d',
860 'upload_date': '20161111',
861 'uploader': 'Team PGP',
862 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
863 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
867 'skip_download': True,
871 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
872 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
875 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
878 'skip': 'Not multifeed anymore',
881 'url': 'https://vid.plus/FlRa-iH7PGw',
882 'only_matching': True,
885 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
886 'only_matching': True,
889 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
890 # Also tests cut-off URL expansion in video description (see
891 # https://github.com/ytdl-org/youtube-dl/issues/1892,
892 # https://github.com/ytdl-org/youtube-dl/issues/8164)
893 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
897 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
898 'alt_title': 'Dark Walk - Position Music',
899 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
901 'upload_date': '20151119',
902 'uploader_id': 'IronSoulElf',
903 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
904 'uploader': 'IronSoulElf',
905 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
906 'track': 'Dark Walk - Position Music',
907 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
908 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
911 'skip_download': True,
915 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
916 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
917 'only_matching': True,
920 # Video with yt:stretch=17:0
921 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
925 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
926 'description': 'md5:ee18a25c350637c8faff806845bddee9',
927 'upload_date': '20151107',
928 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
929 'uploader': 'CH GAMER DROID',
932 'skip_download': True,
934 'skip': 'This video does not exist.',
937 # Video licensed under Creative Commons
938 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
942 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
943 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
945 'upload_date': '20150127',
946 'uploader_id': 'BerkmanCenter',
947 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
948 'uploader': 'The Berkman Klein Center for Internet & Society',
949 'license': 'Creative Commons Attribution license (reuse allowed)',
952 'skip_download': True,
956 # Channel-like uploader_url
957 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
961 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
962 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
964 'upload_date': '20151119',
965 'uploader': 'Bernie Sanders',
966 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
967 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
968 'license': 'Creative Commons Attribution license (reuse allowed)',
971 'skip_download': True,
975 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;v=V36LpHqtcDY',
976 'only_matching': True,
979 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
980 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
981 'only_matching': True,
984 # Rental video preview
985 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
989 'title': 'Piku - Trailer',
990 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
991 'upload_date': '20150811',
992 'uploader': 'FlixMatrix',
993 'uploader_id': 'FlixMatrixKaravan',
994 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
995 'license': 'Standard YouTube License',
998 'skip_download': True,
1000 'skip': 'This video is not available.',
1003 # YouTube Red video with episode data
1004 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1006 'id': 'iqKdEhx-dD4',
1008 'title': 'Isolation - Mind Field (Ep 1)',
1009 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
1011 'upload_date': '20170118',
1012 'uploader': 'Vsauce',
1013 'uploader_id': 'Vsauce',
1014 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
1015 'series': 'Mind Field',
1017 'episode_number': 1,
1020 'skip_download': True,
1022 'expected_warnings': [
1023 'Skipping DASH manifest',
1027 # The following content has been identified by the YouTube community
1028 # as inappropriate or offensive to some audiences.
1029 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1031 'id': '6SJNVb0GnPI',
1033 'title': 'Race Differences in Intelligence',
1034 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1036 'upload_date': '20140124',
1037 'uploader': 'New Century Foundation',
1038 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1039 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
1042 'skip_download': True,
1044 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
1048 'url': '1t24XAntNCY',
1049 'only_matching': True,
1052 # geo restricted to JP
1053 'url': 'sJL6WA-aGkQ',
1054 'only_matching': True,
1057 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1058 'only_matching': True,
1061 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1062 'only_matching': True,
1065 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1066 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1067 'only_matching': True,
1071 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1072 'only_matching': True,
1075 # Video with unsupported adaptive stream type formats
1076 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1078 'id': 'Z4Vy8R84T1U',
1080 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1081 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1083 'upload_date': '20130923',
1084 'uploader': 'Amelia Putri Harwita',
1085 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1086 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1087 'formats': 'maxcount:10',
1090 'skip_download': True,
1091 'youtube_include_dash_manifest': False,
1093 'skip': 'not actual anymore',
1096 # Youtube Music Auto-generated description
1097 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1099 'id': 'MgNrAu2pzNs',
1101 'title': 'Voyeur Girl',
1102 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1103 'upload_date': '20190312',
1104 'uploader': 'Stephen - Topic',
1105 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1106 'artist': 'Stephen',
1107 'track': 'Voyeur Girl',
1108 'album': 'it\'s too much love to know my dear',
1109 'release_date': '20190313',
1110 'release_year': 2019,
1113 'skip_download': True,
1117 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1118 'only_matching': True,
1121 # invalid -> valid video id redirection
1122 'url': 'DJztXj2GPfl',
1124 'id': 'DJztXj2GPfk',
1126 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1127 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1128 'upload_date': '20090125',
1129 'uploader': 'Prochorowka',
1130 'uploader_id': 'Prochorowka',
1131 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1132 'artist': 'Panjabi MC',
1133 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1134 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1137 'skip_download': True,
1139 'skip': 'Video unavailable',
1142 # empty description results in an empty string
1143 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1145 'id': 'x41yOUIvK2k',
1147 'title': 'IMG 3456',
1149 'upload_date': '20170613',
1150 'uploader_id': 'ElevageOrVert',
1151 'uploader': 'ElevageOrVert',
1154 'skip_download': True,
1158 # with '};' inside yt initial data (see [1])
1159 # see [2] for an example with '};' inside ytInitialPlayerResponse
1160 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1161 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1162 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1164 'id': 'CHqg6qOn4no',
1166 'title': 'Part 77 Sort a list of simple types in c#',
1167 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1168 'upload_date': '20130831',
1169 'uploader_id': 'kudvenkat',
1170 'uploader': 'kudvenkat',
1173 'skip_download': True,
1177 # another example of '};' in ytInitialData
1178 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1179 'only_matching': True,
1182 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1183 'only_matching': True,
1186 # https://github.com/ytdl-org/youtube-dl/pull/28094
1187 'url': 'OtqTfy26tG0',
1189 'id': 'OtqTfy26tG0',
1191 'title': 'Burn Out',
1192 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1193 'upload_date': '20141120',
1194 'uploader': 'The Cinematic Orchestra - Topic',
1195 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1196 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1197 'artist': 'The Cinematic Orchestra',
1198 'track': 'Burn Out',
1199 'album': 'Every Day',
1200 'release_data': None,
1201 'release_year': None,
1204 'skip_download': True,
1208 # controversial video, only works with bpctr when authenticated with cookies
1209 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1210 'only_matching': True,
1214 def __init__(self, *args, **kwargs):
1215 super(YoutubeIE, self).__init__(*args, **kwargs)
1216 self._code_cache = {}
1217 self._player_cache = {}
1219 def _signature_cache_id(self, example_sig):
1220 """ Return a string representation of a signature """
1221 return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
1224 def _extract_player_info(cls, player_url):
1225 for player_re in cls._PLAYER_INFO_RE:
1226 id_m = re.search(player_re, player_url)
1230 raise ExtractorError('Cannot identify player %r' % player_url)
1231 return id_m.group('id')
1233 def _extract_signature_function(self, video_id, player_url, example_sig):
1234 player_id = self._extract_player_info(player_url)
1236 # Read from filesystem cache
1237 func_id = 'js_%s_%s' % (
1238 player_id, self._signature_cache_id(example_sig))
1239 assert os.path.basename(func_id) == func_id
1241 cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
1242 if cache_spec is not None:
1243 return lambda s: ''.join(s[i] for i in cache_spec)
1245 if player_id not in self._code_cache:
1246 self._code_cache[player_id] = self._download_webpage(
1247 player_url, video_id,
1248 note='Downloading player ' + player_id,
1249 errnote='Download of %s failed' % player_url)
1250 code = self._code_cache[player_id]
1251 res = self._parse_sig_js(code)
1253 test_string = ''.join(map(compat_chr, range(len(example_sig))))
1254 cache_res = res(test_string)
1255 cache_spec = [ord(c) for c in cache_res]
1257 self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
1260 def _print_sig_code(self, func, example_sig):
1261 def gen_sig_code(idxs):
1262 def _genslice(start, end, step):
1263 starts = '' if start == 0 else str(start)
1264 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
1265 steps = '' if step == 1 else (':%d' % step)
1266 return 's[%s%s%s]' % (starts, ends, steps)
1269 # Quelch pyflakes warnings - start will be set when step is set
1270 start = '(Never used)'
1271 for i, prev in zip(idxs[1:], idxs[:-1]):
1272 if step is not None:
1273 if i - prev == step:
1275 yield _genslice(start, prev, step)
1278 if i - prev in [-1, 1]:
1283 yield 's[%d]' % prev
1287 yield _genslice(start, i, step)
1289 test_string = ''.join(map(compat_chr, range(len(example_sig))))
1290 cache_res = func(test_string)
1291 cache_spec = [ord(c) for c in cache_res]
1292 expr_code = ' + '.join(gen_sig_code(cache_spec))
1293 signature_id_tuple = '(%s)' % (
1294 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
1295 code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1296 ' return %s\n') % (signature_id_tuple, expr_code)
1297 self.to_screen('Extracted signature function:\n' + code)
1299 def _parse_sig_js(self, jscode):
1300 funcname = self._search_regex(
1301 (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1302 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1303 r'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1304 r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1305 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+\)',
1306 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*\)',
1307 r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1309 r'(["\'])signature\
1\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1310 r'\
.sig\|\|
(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1311 r'yt\
.akamaized\
.net
/\
)\s
*\|\|\s
*.*?\s
*[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?
:encodeURIComponent\s
*\
()?\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1312 r'\b[cs
]\s
*&&\s
*[adf
]\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1313 r'\b[a
-zA
-Z0
-9]+\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1314 r'\bc\s
*&&\s
*a\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1315 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
(',
1316 r'\bc\s
*&&\s
*[a
-zA
-Z0
-9]+\
.set\
([^
,]+\s
*,\s
*\
([^
)]*\
)\s
*\
(\s
*(?P
<sig
>[a
-zA
-Z0
-9$
]+)\
('),
1317 jscode, 'Initial JS player signature function name
', group='sig
')
1319 jsi = JSInterpreter(jscode)
1320 initial_function = jsi.extract_function(funcname)
1321 return lambda s: initial_function([s])
1323 def _decrypt_signature(self, s, video_id, player_url):
1324 """Turn the encrypted s field into a working signature"""
1326 if player_url is None:
1327 raise ExtractorError('Cannot decrypt signature without player_url
')
1329 if player_url.startswith('//'):
1330 player_url = 'https
:' + player_url
1331 elif not re.match(r'https?
://', player_url):
1332 player_url = compat_urlparse.urljoin(
1333 'https
://www
.youtube
.com
', player_url)
1335 player_id = (player_url, self._signature_cache_id(s))
1336 if player_id not in self._player_cache:
1337 func = self._extract_signature_function(
1338 video_id, player_url, s
1340 self._player_cache[player_id] = func
1341 func = self._player_cache[player_id]
1342 if self._downloader.params.get('youtube_print_sig_code
'):
1343 self._print_sig_code(func, s)
1345 except Exception as e:
1346 tb = traceback.format_exc()
1347 raise ExtractorError(
1348 'Signature extraction failed
: ' + tb, cause=e)
1350 def _mark_watched(self, video_id, player_response):
1351 playback_url = url_or_none(try_get(
1353 lambda x: x['playbackTracking
']['videostatsPlaybackUrl
']['baseUrl
']))
1354 if not playback_url:
1356 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1357 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1359 # cpn generation algorithm is reverse engineered from base.js.
1360 # In fact it works even with dummy cpn.
1361 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
-_
'
1362 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1368 playback_url = compat_urlparse.urlunparse(
1369 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1371 self._download_webpage(
1372 playback_url, video_id, 'Marking watched
',
1373 'Unable to mark watched
', fatal=False)
1376 def _extract_urls(webpage):
1377 # Embedded YouTube player
1379 unescapeHTML(mobj.group('url
'))
1380 for mobj in re.finditer(r'''(?x)
1390 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1391 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1394 # lazyYT YouTube embed
1395 entries.extend(list(map(
1397 re.findall(r'class="lazyYT" data
-youtube
-id="([^"]+)"', webpage))))
1399 # Wordpress "YouTube Video Importer
" plugin
1400 matches = re.findall(r'''(?x)<div[^>]+
1401 class=(?P<q1>[\'"])[^
\'"]*\byvii_single_video_player\b[^\'"]*(?P
=q1
)[^
>]+
1402 data
-video_id
=(?P
<q2
>[\'"])([^\'"]+)(?P
=q2
)''', webpage)
1403 entries.extend(m[-1] for m in matches)
1408 def _extract_url(webpage):
1409 urls = YoutubeIE._extract_urls(webpage)
1410 return urls[0] if urls else None
1413 def extract_id(cls, url):
1414 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1416 raise ExtractorError('Invalid URL: %s' % url)
1417 video_id = mobj.group(2)
1420 def _extract_chapters_from_json(self, data, video_id, duration):
1421 chapters_list = try_get(
1423 lambda x: x['playerOverlays']
1424 ['playerOverlayRenderer']
1425 ['decoratedPlayerBarRenderer']
1426 ['decoratedPlayerBarRenderer']
1428 ['chapteredPlayerBarRenderer']
1431 if not chapters_list:
1434 def chapter_time(chapter):
1435 return float_or_none(
1438 lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1442 for next_num, chapter in enumerate(chapters_list, start=1):
1443 start_time = chapter_time(chapter)
1444 if start_time is None:
1446 end_time = (chapter_time(chapters_list[next_num])
1447 if next_num < len(chapters_list) else duration)
1448 if end_time is None:
1451 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1454 'start_time': start_time,
1455 'end_time': end_time,
1460 def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1461 return self._parse_json(self._search_regex(
1462 (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1463 regex), webpage, name, default='{}'), video_id, fatal=False)
1465 def _real_extract(self, url):
1466 url, smuggled_data = unsmuggle_url(url, {})
1467 video_id = self._match_id(url)
1468 base_url = self.http_scheme() + '//www.youtube.com/'
1469 webpage_url = base_url + 'watch?v=' + video_id
1470 webpage = self._download_webpage(
1471 webpage_url + '&has_verified=1&bpctr=9999999999',
1472 video_id, fatal=False)
1474 player_response = None
1476 player_response = self._extract_yt_initial_variable(
1477 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1478 video_id, 'initial player response')
1479 if not player_response:
1480 player_response = self._call_api(
1481 'player', {'videoId': video_id}, video_id)
1483 playability_status = player_response.get('playabilityStatus') or {}
1484 if playability_status.get('reason') == 'Sign in to confirm your age':
1485 pr = self._parse_json(try_get(compat_parse_qs(
1486 self._download_webpage(
1487 base_url + 'get_video_info', video_id,
1488 'Refetching age-gated info webpage',
1489 'unable to download video info webpage', query={
1490 'video_id': video_id,
1491 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1493 lambda x: x['player_response'][0],
1494 compat_str) or '{}', video_id)
1496 player_response = pr
1498 trailer_video_id = try_get(
1500 lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1502 if trailer_video_id:
1503 return self.url_result(
1504 trailer_video_id, self.ie_key(), trailer_video_id)
1509 return x.get('simpleText') or ''.join([r['text'] for r in x['runs']])
1512 lambda x: self._html_search_meta(x, webpage, default=None)) \
1513 if webpage else lambda x: None
1515 video_details = player_response.get('videoDetails') or {}
1516 microformat = try_get(
1518 lambda x: x['microformat']['playerMicroformatRenderer'],
1520 video_title = video_details.get('title') \
1521 or get_text(microformat.get('title')) \
1522 or search_meta(['og:title', 'twitter:title', 'title'])
1523 video_description = video_details.get('shortDescription')
1525 if not smuggled_data.get('force_singlefeed', False):
1526 if not self._downloader.params.get('noplaylist'):
1527 multifeed_metadata_list = try_get(
1529 lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1531 if multifeed_metadata_list:
1534 for feed in multifeed_metadata_list.split(','):
1535 # Unquote should take place before split on comma (,) since textual
1536 # fields may contain comma as well (see
1537 # https://github.com/ytdl-org/youtube-dl/issues/8536)
1538 feed_data = compat_parse_qs(
1539 compat_urllib_parse_unquote_plus(feed))
1541 def feed_entry(name):
1543 feed_data, lambda x: x[name][0], compat_str)
1545 feed_id = feed_entry('id')
1548 feed_title = feed_entry('title')
1551 title += ' (%s)' % feed_title
1553 '_type': 'url_transparent',
1554 'ie_key': 'Youtube',
1556 base_url + 'watch?v=' + feed_data['id'][0],
1557 {'force_singlefeed': True}),
1560 feed_ids.append(feed_id)
1562 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1563 % (', '.join(feed_ids), video_id))
1564 return self.playlist_result(
1565 entries, video_id, video_title, video_description)
1567 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1573 q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1574 streaming_data = player_response.get('streamingData') or {}
1575 streaming_formats = streaming_data.get('formats') or []
1576 streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1577 for fmt in streaming_formats:
1578 if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1581 itag = str_or_none(fmt.get('itag'))
1582 quality = fmt.get('quality')
1583 if itag and quality:
1584 itag_qualities[itag] = quality
1585 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1586 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1587 # number of fragment that would subsequently requested with (`&sq=N`)
1588 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1591 fmt_url = fmt.get('url')
1593 sc = compat_parse_qs(fmt.get('signatureCipher'))
1594 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1595 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1596 if not (sc and fmt_url and encrypted_sig):
1601 player_url = self._search_regex(
1602 r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1603 webpage, 'player URL', fatal=False)
1606 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1607 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1608 fmt_url += '&' + sp + '=' + signature
1612 tbr = float_or_none(
1613 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1615 'asr': int_or_none(fmt.get('audioSampleRate')),
1616 'filesize': int_or_none(fmt.get('contentLength')),
1618 'format_note': fmt.get('qualityLabel') or quality,
1619 'fps': int_or_none(fmt.get('fps')),
1620 'height': int_or_none(fmt.get('height')),
1621 'quality': q(quality),
1624 'width': fmt.get('width'),
1626 mimetype = fmt.get('mimeType')
1629 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1631 dct['ext'] = mimetype2ext(mobj.group(1))
1632 dct.update(parse_codecs(mobj.group(2)))
1633 no_audio = dct.get('acodec') == 'none'
1634 no_video = dct.get('vcodec') == 'none'
1639 if no_audio or no_video:
1640 dct['downloader_options'] = {
1641 # Youtube throttles chunks >~10M
1642 'http_chunk_size': 10485760,
1645 dct['container'] = dct['ext'] + '_dash'
1648 hls_manifest_url = streaming_data.get('hlsManifestUrl')
1649 if hls_manifest_url:
1650 for f in self._extract_m3u8_formats(
1651 hls_manifest_url, video_id, 'mp4', fatal=False):
1652 itag = self._search_regex(
1653 r'/itag/(\d+)', f['url'], 'itag', default=None)
1655 f['format_id'] = itag
1658 if self._downloader.params.get('youtube_include_dash_manifest'):
1659 dash_manifest_url = streaming_data.get('dashManifestUrl')
1660 if dash_manifest_url:
1661 for f in self._extract_mpd_formats(
1662 dash_manifest_url, video_id, fatal=False):
1663 itag = f['format_id']
1666 if itag in itag_qualities:
1667 # Not actually usefull since the sorting is already done with "quality,res,fps,codec"
1668 # but kept to maintain feature parity (and code similarity) with youtube-dl
1669 # Remove if this causes any issues with sorting in future
1670 f['quality'] = q(itag_qualities[itag])
1671 filesize = int_or_none(self._search_regex(
1672 r'/clen/(\d+)', f.get('fragment_base_url')
1673 or f['url'], 'file size', default=None))
1675 f['filesize'] = filesize
1679 if not self._downloader.params.get('allow_unplayable_formats') and streaming_data.get('licenseInfos'):
1680 raise ExtractorError(
1681 'This video is DRM protected.', expected=True)
1684 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
1686 reason = get_text(pemr.get('reason')) or playability_status.get('reason')
1687 subreason = pemr.get('subreason')
1689 subreason = clean_html(get_text(subreason))
1690 if subreason == 'The uploader has not made this video available in your country.':
1691 countries = microformat.get('availableCountries')
1693 regions_allowed = search_meta('regionsAllowed')
1694 countries = regions_allowed.split(',') if regions_allowed else None
1695 self.raise_geo_restricted(
1696 subreason, countries)
1697 reason += '\n' + subreason
1699 raise ExtractorError(reason, expected=True)
1701 self._sort_formats(formats)
1703 keywords = video_details.get('keywords') or []
1704 if not keywords and webpage:
1706 unescapeHTML(m.group('content'))
1707 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
1708 for keyword in keywords:
1709 if keyword.startswith('yt:stretch='):
1710 w, h = keyword.split('=')[1].split(':')
1711 w, h = int(w), int(h)
1715 if f.get('vcodec') != 'none':
1716 f['stretched_ratio'] = ratio
1719 for container in (video_details, microformat):
1720 for thumbnail in (try_get(
1722 lambda x: x['thumbnail']['thumbnails'], list) or []):
1723 thumbnail_url = thumbnail.get('url')
1724 if not thumbnail_url:
1727 'height': int_or_none(thumbnail.get('height')),
1728 'url': thumbnail_url,
1729 'width': int_or_none(thumbnail.get('width')),
1734 thumbnail = search_meta(['og:image', 'twitter:image'])
1736 thumbnails = [{'url': thumbnail}]
1738 category = microformat.get('category') or search_meta('genre')
1739 channel_id = video_details.get('channelId') \
1740 or microformat.get('externalChannelId') \
1741 or search_meta('channelId')
1742 duration = int_or_none(
1743 video_details.get('lengthSeconds')
1744 or microformat.get('lengthSeconds')) \
1745 or parse_duration(search_meta('duration'))
1746 is_live = video_details.get('isLive')
1747 owner_profile_url = microformat.get('ownerProfileUrl')
1751 'title': self._live_title(video_title) if is_live else video_title,
1753 'thumbnails': thumbnails,
1754 'description': video_description,
1755 'upload_date': unified_strdate(
1756 microformat.get('uploadDate')
1757 or search_meta('uploadDate')),
1758 'uploader': video_details['author'],
1759 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
1760 'uploader_url': owner_profile_url,
1761 'channel_id': channel_id,
1762 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
1763 'duration': duration,
1764 'view_count': int_or_none(
1765 video_details.get('viewCount')
1766 or microformat.get('viewCount')
1767 or search_meta('interactionCount')),
1768 'average_rating': float_or_none(video_details.get('averageRating')),
1769 'age_limit': 18 if (
1770 microformat.get('isFamilySafe') is False
1771 or search_meta('isFamilyFriendly') == 'false'
1772 or search_meta('og:restrictions:age') == '18+') else 0,
1773 'webpage_url': webpage_url,
1774 'categories': [category] if category else None,
1777 'playable_in_embed': playability_status.get('playableInEmbed'),
1778 'was_live': video_details.get('isLiveContent')
1783 lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
1786 def process_language(container, base_url, lang_code, query):
1788 for fmt in self._SUBTITLE_FORMATS:
1794 'url': update_url_query(base_url, query),
1796 container[lang_code] = lang_subs
1798 for caption_track in (pctr.get('captionTracks') or []):
1799 base_url = caption_track.get('baseUrl')
1802 if caption_track.get('kind') != 'asr':
1803 lang_code = caption_track.get('languageCode')
1807 subtitles, base_url, lang_code, {})
1809 automatic_captions = {}
1810 for translation_language in (pctr.get('translationLanguages') or []):
1811 translation_language_code = translation_language.get('languageCode')
1812 if not translation_language_code:
1815 automatic_captions, base_url, translation_language_code,
1816 {'tlang': translation_language_code})
1817 info['automatic_captions'] = automatic_captions
1818 info['subtitles'] = subtitles
1820 parsed_url = compat_urllib_parse_urlparse(url)
1821 for component in [parsed_url.fragment, parsed_url.query]:
1822 query = compat_parse_qs(component)
1823 for k, v in query.items():
1824 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
1826 if d_k not in info and k in s_ks:
1827 info[d_k] = parse_duration(query[k][0])
1829 # Youtube Music Auto-generated description
1830 if video_description:
1831 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)
1833 release_year = mobj.group('release_year')
1834 release_date = mobj.group('release_date')
1836 release_date = release_date.replace('-', '')
1837 if not release_year:
1838 release_year = release_date[:4]
1840 'album': mobj.group('album'.strip()),
1841 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
1842 'track': mobj.group('track').strip(),
1843 'release_date': release_date,
1844 'release_year': int_or_none(release_year),
1849 initial_data = self._extract_yt_initial_variable(
1850 webpage, self._YT_INITIAL_DATA_RE, video_id,
1852 if not initial_data:
1853 initial_data = self._call_api(
1854 'next', {'videoId': video_id}, video_id, fatal=False)
1858 # This will error if there is no livechat
1859 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
1860 info['subtitles']['live_chat'] = [{
1861 'video_id': video_id,
1863 'protocol': 'youtube_live_chat_replay',
1865 except (KeyError, IndexError, TypeError):
1869 chapters = self._extract_chapters_from_json(
1870 initial_data, video_id, duration)
1872 for engagment_pannel in (initial_data.get('engagementPanels') or []):
1874 engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
1879 def chapter_time(mmlir):
1880 return parse_duration(
1881 get_text(mmlir.get('timeDescription')))
1884 for next_num, content in enumerate(contents, start=1):
1885 mmlir = content.get('macroMarkersListItemRenderer') or {}
1886 start_time = chapter_time(mmlir)
1887 end_time = chapter_time(try_get(
1888 contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
1889 if next_num < len(contents) else duration
1890 if start_time is None or end_time is None:
1893 'start_time': start_time,
1894 'end_time': end_time,
1895 'title': get_text(mmlir.get('title')),
1900 info['chapters'] = chapters
1904 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
1906 for content in contents:
1907 vpir = content.get('videoPrimaryInfoRenderer')
1909 stl = vpir.get('superTitleLink')
1914 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
1915 info['location'] = stl
1917 mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
1920 'series': mobj.group(1),
1921 'season_number': int(mobj.group(2)),
1922 'episode_number': int(mobj.group(3)),
1924 for tlb in (try_get(
1926 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
1928 tbr = tlb.get('toggleButtonRenderer') or {}
1929 for getter, regex in [(
1930 lambda x: x['defaultText']['accessibility']['accessibilityData'],
1931 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
1932 lambda x: x['accessibility'],
1933 lambda x: x['accessibilityData']['accessibilityData'],
1934 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
1935 label = (try_get(tbr, getter, dict) or {}).get('label')
1937 mobj = re.match(regex, label)
1939 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
1941 sbr_tooltip = try_get(
1942 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
1944 like_count, dislike_count = sbr_tooltip.split(' / ')
1946 'like_count': str_to_int(like_count),
1947 'dislike_count': str_to_int(dislike_count),
1949 vsir = content.get('videoSecondaryInfoRenderer')
1951 info['channel'] = get_text(try_get(
1953 lambda x: x['owner']['videoOwnerRenderer']['title'],
1957 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
1959 multiple_songs = False
1961 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
1962 multiple_songs = True
1965 mrr = row.get('metadataRowRenderer') or {}
1966 mrr_title = mrr.get('title')
1969 mrr_title = get_text(mrr['title'])
1970 mrr_contents_text = get_text(mrr['contents'][0])
1971 if mrr_title == 'License':
1972 info['license'] = mrr_contents_text
1973 elif not multiple_songs:
1974 if mrr_title == 'Album':
1975 info['album'] = mrr_contents_text
1976 elif mrr_title == 'Artist':
1977 info['artist'] = mrr_contents_text
1978 elif mrr_title == 'Song':
1979 info['track'] = mrr_contents_text
1982 'channel': 'uploader',
1983 'channel_id': 'uploader_id',
1984 'channel_url': 'uploader_url',
1986 for to, frm in fallbacks.items():
1987 if not info.get(to):
1988 info[to] = info.get(frm)
1990 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
1995 # get xsrf for annotations or comments
1996 get_annotations = self._downloader.params.get('writeannotations', False)
1997 get_comments = self._downloader.params.get('getcomments', False)
1998 if get_annotations or get_comments:
2000 ytcfg = self._extract_ytcfg(video_id, webpage)
2002 xsrf_token = try_get(ytcfg, lambda x: x['XSRF_TOKEN'], compat_str)
2004 xsrf_token = self._search_regex(
2005 r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>(?:(?!\2).)+)\2',
2006 webpage, 'xsrf token', group='xsrf_token', fatal=False)
2010 invideo_url = try_get(
2011 player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
2012 if xsrf_token and invideo_url:
2013 xsrf_field_name = None
2015 xsrf_field_name = try_get(ytcfg, lambda x: x['XSRF_FIELD_NAME'], compat_str)
2016 if not xsrf_field_name:
2017 xsrf_field_name = self._search_regex(
2018 r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
2019 webpage, 'xsrf field name',
2020 group='xsrf_field_name', default='session_token')
2021 info['annotations'] = self._download_webpage(
2022 self._proto_relative_url(invideo_url),
2023 video_id, note='Downloading annotations',
2024 errnote='Unable to download video annotations', fatal=False,
2025 data=urlencode_postdata({xsrf_field_name: xsrf_token}))
2028 # TODO: Refactor and move to seperate function
2029 def extract_comments():
2030 expected_video_comment_count = 0
2032 comment_xsrf = xsrf_token
2034 def find_value(html, key, num_chars=2, separator='"'):
2035 pos_begin = html.find(key) + len(key) + num_chars
2036 pos_end = html.find(separator, pos_begin)
2037 return html[pos_begin: pos_end]
2039 def search_dict(partial, key):
2040 if isinstance(partial, dict):
2041 for k, v in partial.items():
2045 for o in search_dict(v, key):
2047 elif isinstance(partial, list):
2049 for o in search_dict(i, key):
2055 ncd = next(search_dict(initial_data, 'nextContinuationData'))
2056 continuations = [ncd['continuation']]
2057 # Handle videos where comments have been disabled entirely
2058 except StopIteration:
2061 def get_continuation(continuation, session_token, replies=False):
2064 'ctoken': continuation,
2067 query['action_get_comment_replies'] = 1
2069 query['action_get_comments'] = 1
2072 content, handle = self._download_webpage_handle(
2073 'https://www.youtube.com/comment_service_ajax',
2076 expected_status=[413],
2077 data=urlencode_postdata({
2078 'session_token': session_token
2083 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
2084 'X-YouTube-Client-Name': '1',
2085 'X-YouTube-Client-Version': '2.20201202.06.01'
2089 response_code = handle.getcode()
2090 if (response_code == 200):
2091 return self._parse_json(content, video_id)
2092 if (response_code == 413):
2094 raise ExtractorError('Unexpected HTTP error code: %s' % response_code)
2096 first_continuation = True
2098 self.to_screen('Downloading comments')
2099 while continuations:
2100 continuation = continuations.pop()
2101 comment_response = get_continuation(continuation, comment_xsrf)
2102 if not comment_response:
2104 if list(search_dict(comment_response, 'externalErrorMessage')):
2105 raise ExtractorError('Error returned from server: ' + next(search_dict(comment_response, 'externalErrorMessage')))
2107 if 'continuationContents' not in comment_response['response']:
2108 # Something is wrong here. Youtube won't accept this continuation token for some reason and responds with a user satisfaction dialog (error?)
2110 # not sure if this actually helps
2111 if 'xsrf_token' in comment_response:
2112 comment_xsrf = comment_response['xsrf_token']
2114 item_section = comment_response['response']['continuationContents']['itemSectionContinuation']
2115 if first_continuation:
2116 expected_video_comment_count = int(item_section['header']['commentsHeaderRenderer']['countText']['runs'][0]['text'].replace(' Comments', '').replace('1 Comment', '1').replace(',', ''))
2117 first_continuation = False
2118 if 'contents' not in item_section:
2119 # continuation returned no comments?
2120 # set an empty array as to not break the for loop
2121 item_section['contents'] = []
2123 for meta_comment in item_section['contents']:
2124 comment = meta_comment['commentThreadRenderer']['comment']['commentRenderer']
2125 video_comments.append({
2126 'id': comment['commentId'],
2127 'text': ''.join([c['text'] for c in try_get(comment, lambda x: x['contentText']['runs'], list) or []]),
2128 'time_text': ''.join([c['text'] for c in comment['publishedTimeText']['runs']]),
2129 'author': comment.get('authorText', {}).get('simpleText', ''),
2130 'votes': comment.get('voteCount', {}).get('simpleText', '0'),
2131 'author_thumbnail': comment['authorThumbnail']['thumbnails'][-1]['url'],
2134 if 'replies' not in meta_comment['commentThreadRenderer']:
2137 reply_continuations = [rcn['nextContinuationData']['continuation'] for rcn in meta_comment['commentThreadRenderer']['replies']['commentRepliesRenderer']['continuations']]
2138 while reply_continuations:
2140 continuation = reply_continuations.pop()
2141 replies_data = get_continuation(continuation, comment_xsrf, True)
2142 if not replies_data or 'continuationContents' not in replies_data[1]['response']:
2145 if self._downloader.params.get('verbose', False):
2146 chain_msg = ' (chain %s)' % comment['commentId']
2147 self.to_screen('Comments downloaded: %d of ~%d%s' % (len(video_comments), expected_video_comment_count, chain_msg))
2148 reply_comment_meta = replies_data[1]['response']['continuationContents']['commentRepliesContinuation']
2149 for reply_meta in reply_comment_meta.get('contents', {}):
2150 reply_comment = reply_meta['commentRenderer']
2151 video_comments.append({
2152 'id': reply_comment['commentId'],
2153 'text': ''.join([c['text'] for c in reply_comment['contentText']['runs']]),
2154 'time_text': ''.join([c['text'] for c in reply_comment['publishedTimeText']['runs']]),
2155 'author': reply_comment.get('authorText', {}).get('simpleText', ''),
2156 'votes': reply_comment.get('voteCount', {}).get('simpleText', '0'),
2157 'author_thumbnail': reply_comment['authorThumbnail']['thumbnails'][-1]['url'],
2158 'parent': comment['commentId']
2160 if 'continuations' not in reply_comment_meta or len(reply_comment_meta['continuations']) == 0:
2162 reply_continuations += [rcn['nextContinuationData']['continuation'] for rcn in reply_comment_meta['continuations']]
2164 self.to_screen('Comments downloaded: %d of ~%d' % (len(video_comments), expected_video_comment_count))
2165 if 'continuations' in item_section:
2166 continuations += [ncd['nextContinuationData']['continuation'] for ncd in item_section['continuations']]
2169 self.to_screen('Total comments downloaded: %d of ~%d' % (len(video_comments), expected_video_comment_count))
2171 'comments': video_comments,
2172 'comment_count': expected_video_comment_count
2176 info['__post_extractor'] = extract_comments
2178 self.mark_watched(video_id, player_response)
2183 class YoutubeTabIE(YoutubeBaseInfoExtractor):
2184 IE_DESC = 'YouTube.com tab'
2185 _VALID_URL = r'''(?x
)
2189 youtube(?
:kids
)?\
.com|
2193 (?
:channel|c|user
)/|
2196 (?
:playlist|watch
)\?.*?
\blist
=
2198 (?
!(?
:%s)\b) # Direct URLs
2201 ''' % YoutubeBaseInfoExtractor._RESERVED_NAMES
2202 IE_NAME = 'youtube:tab'
2205 # playlists, multipage
2206 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2207 'playlist_mincount': 94,
2209 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2210 'title': 'Игорь Клейнер - Playlists',
2211 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2212 'uploader': 'Игорь Клейнер',
2213 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2216 # playlists, multipage, different order
2217 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2218 'playlist_mincount': 94,
2220 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2221 'title': 'Игорь Клейнер - Playlists',
2222 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2223 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
2224 'uploader': 'Игорь Клейнер',
2227 # playlists, singlepage
2228 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2229 'playlist_mincount': 4,
2231 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2232 'title': 'ThirstForScience - Playlists',
2233 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2234 'uploader': 'ThirstForScience',
2235 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2238 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2239 'only_matching': True,
2241 # basic, single video playlist
2242 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2244 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2245 'uploader': 'Sergey M.',
2246 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2247 'title': 'youtube-dl public playlist',
2249 'playlist_count': 1,
2252 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2254 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2255 'uploader': 'Sergey M.',
2256 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2257 'title': 'youtube-dl empty playlist',
2259 'playlist_count': 0,
2262 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2264 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2265 'title': 'lex will - Home',
2266 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2267 'uploader': 'lex will',
2268 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2270 'playlist_mincount': 2,
2273 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2275 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2276 'title': 'lex will - Videos',
2277 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2278 'uploader': 'lex will',
2279 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2281 'playlist_mincount': 975,
2283 # Videos tab, sorted by popular
2284 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2286 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2287 'title': 'lex will - Videos',
2288 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2289 'uploader': 'lex will',
2290 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2292 'playlist_mincount': 199,
2295 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2297 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2298 'title': 'lex will - Playlists',
2299 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2300 'uploader': 'lex will',
2301 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2303 'playlist_mincount': 17,
2306 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2308 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2309 'title': 'lex will - Community',
2310 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2311 'uploader': 'lex will',
2312 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2314 'playlist_mincount': 18,
2317 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2319 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2320 'title': 'lex will - Channels',
2321 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2322 'uploader': 'lex will',
2323 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2325 'playlist_mincount': 12,
2327 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2328 'only_matching': True,
2330 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2331 'only_matching': True,
2333 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2334 'only_matching': True,
2336 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2337 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2339 'title': '29C3: Not my department',
2340 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2341 'uploader': 'Christiaan008',
2342 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2343 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
2345 'playlist_count': 96,
2347 'note': 'Large playlist',
2348 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2350 'title': 'Uploads from Cauchemar',
2351 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2352 'uploader': 'Cauchemar',
2353 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2355 'playlist_mincount': 1123,
2357 # even larger playlist, 8832 videos
2358 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2359 'only_matching': True,
2361 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2362 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2364 'title': 'Uploads from Interstellar Movie',
2365 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2366 'uploader': 'Interstellar Movie',
2367 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2369 'playlist_mincount': 21,
2371 # https://github.com/ytdl-org/youtube-dl/issues/21844
2372 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2374 'title': 'Data Analysis with Dr Mike Pound',
2375 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2376 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2377 'uploader': 'Computerphile',
2378 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
2380 'playlist_mincount': 11,
2382 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2383 'only_matching': True,
2385 # Playlist URL that does not actually serve a playlist
2386 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2388 'id': 'FqZTN594JQw',
2390 'title': "Smiley's People 01 detective, Adventure Series, Action",
2391 'uploader': 'STREEM',
2392 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2393 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2394 'upload_date': '20150526',
2395 'license': 'Standard YouTube License',
2396 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2397 'categories': ['People & Blogs'],
2401 'dislike_count': int,
2404 'skip_download': True,
2406 'skip': 'This video is not available.',
2407 'add_ie': [YoutubeIE.ie_key()],
2409 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2410 'only_matching': True,
2412 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2413 'only_matching': True,
2415 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2417 'id': '9Auq9mYxFEE',
2419 'title': compat_str,
2420 'uploader': 'Sky News',
2421 'uploader_id': 'skynews',
2422 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2423 'upload_date': '20191102',
2424 'description': 'md5:85ddd75d888674631aaf9599a9a0b0ae',
2425 'categories': ['News & Politics'],
2428 'dislike_count': int,
2431 'skip_download': True,
2434 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2436 'id': 'a48o2S1cPoo',
2438 'title': 'The Young Turks - Live Main Show',
2439 'uploader': 'The Young Turks',
2440 'uploader_id': 'TheYoungTurks',
2441 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2442 'upload_date': '20150715',
2443 'license': 'Standard YouTube License',
2444 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2445 'categories': ['News & Politics'],
2446 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2448 'dislike_count': int,
2451 'skip_download': True,
2453 'only_matching': True,
2455 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2456 'only_matching': True,
2458 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2459 'only_matching': True,
2461 'url': 'https://www.youtube.com/feed/trending',
2462 'only_matching': True,
2465 'url': 'https://www.youtube.com/feed/library',
2466 'only_matching': True,
2469 'url': 'https://www.youtube.com/feed/history',
2470 'only_matching': True,
2473 'url': 'https://www.youtube.com/feed/subscriptions',
2474 'only_matching': True,
2477 'url': 'https://www.youtube.com/feed/watch_later',
2478 'only_matching': True,
2480 # no longer available?
2481 'url': 'https://www.youtube.com/feed/recommended',
2482 'only_matching': True,
2484 # inline playlist with not always working continuations
2485 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2486 'only_matching': True,
2488 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2489 'only_matching': True,
2491 'url': 'https://www.youtube.com/course',
2492 'only_matching': True,
2494 'url': 'https://www.youtube.com/zsecurity',
2495 'only_matching': True,
2497 'url': 'http://www.youtube.com/NASAgovVideo/videos',
2498 'only_matching': True,
2500 'url': 'https://www.youtube.com/TheYoungTurks/live',
2501 'only_matching': True,
2505 def suitable(cls, url):
2506 return False if YoutubeIE.suitable(url) else super(
2507 YoutubeTabIE, cls).suitable(url)
2509 def _extract_channel_id(self, webpage):
2510 channel_id = self._html_search_meta(
2511 'channelId', webpage, 'channel id', default=None)
2514 channel_url = self._html_search_meta(
2515 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2516 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2517 'twitter:app:url:googleplay'), webpage, 'channel url')
2518 return self._search_regex(
2519 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2520 channel_url, 'channel id')
2523 def _extract_grid_item_renderer(item):
2524 for item_kind in ('Playlist', 'Video', 'Channel'):
2525 renderer = item.get('grid%sRenderer' % item_kind)
2529 def _grid_entries(self, grid_renderer):
2530 for item in grid_renderer['items']:
2531 if not isinstance(item, dict):
2533 renderer = self._extract_grid_item_renderer(item)
2534 if not isinstance(renderer, dict):
2537 renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2539 playlist_id = renderer.get('playlistId')
2541 yield self.url_result(
2542 'https://www.youtube.com/playlist?list=%s' % playlist_id,
2543 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2546 video_id = renderer.get('videoId')
2548 yield self._extract_video(renderer)
2550 channel_id = renderer.get('channelId')
2553 renderer, lambda x: x['title']['simpleText'], compat_str)
2554 yield self.url_result(
2555 'https://www.youtube.com/channel/%s' % channel_id,
2556 ie=YoutubeTabIE.ie_key(), video_title=title)
2558 def _shelf_entries_from_content(self, shelf_renderer):
2559 content = shelf_renderer.get('content')
2560 if not isinstance(content, dict):
2562 renderer = content.get('gridRenderer')
2564 # TODO: add support for nested playlists so each shelf is processed
2565 # as separate playlist
2566 # TODO: this includes only first N items
2567 for entry in self._grid_entries(renderer):
2569 renderer = content.get('horizontalListRenderer')
2574 def _shelf_entries(self, shelf_renderer, skip_channels=False):
2576 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2578 shelf_url = urljoin('https://www.youtube.com', ep)
2580 # Skipping links to another channels, note that checking for
2581 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2583 if skip_channels and '/channels?' in shelf_url:
2586 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2587 yield self.url_result(shelf_url, video_title=title)
2588 # Shelf may not contain shelf URL, fallback to extraction from content
2589 for entry in self._shelf_entries_from_content(shelf_renderer):
2592 def _playlist_entries(self, video_list_renderer):
2593 for content in video_list_renderer['contents']:
2594 if not isinstance(content, dict):
2596 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2597 if not isinstance(renderer, dict):
2599 video_id = renderer.get('videoId')
2602 yield self._extract_video(renderer)
2604 r""" # Not needed in the new implementation
2605 def _itemSection_entries(self, item_sect_renderer):
2606 for content in item_sect_renderer['contents']:
2607 if not isinstance(content, dict):
2609 renderer = content.get('videoRenderer', {})
2610 if not isinstance(renderer, dict):
2612 video_id = renderer.get('videoId')
2615 yield self._extract_video(renderer)
2618 def _rich_entries(self, rich_grid_renderer):
2620 rich_grid_renderer, lambda x: x['content']['videoRenderer'], dict) or {}
2621 video_id = renderer.get('videoId')
2624 yield self._extract_video(renderer)
2626 def _video_entry(self, video_renderer):
2627 video_id = video_renderer.get('videoId')
2629 return self._extract_video(video_renderer)
2631 def _post_thread_entries(self, post_thread_renderer):
2632 post_renderer = try_get(
2633 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2634 if not post_renderer:
2637 video_renderer = try_get(
2638 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2641 entry = self._video_entry(video_renderer)
2644 # inline video links
2645 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2647 if not isinstance(run, dict):
2650 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2653 if not YoutubeIE.suitable(ep_url):
2655 ep_video_id = YoutubeIE._match_id(ep_url)
2656 if video_id == ep_video_id:
2658 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2660 def _post_thread_continuation_entries(self, post_thread_continuation):
2661 contents = post_thread_continuation.get('contents')
2662 if not isinstance(contents, list):
2664 for content in contents:
2665 renderer = content.get('backstagePostThreadRenderer')
2666 if not isinstance(renderer, dict):
2668 for entry in self._post_thread_entries(renderer):
2672 def _build_continuation_query(continuation, ctp=None):
2674 'ctoken': continuation,
2675 'continuation': continuation,
2682 def _extract_next_continuation_data(renderer):
2683 next_continuation = try_get(
2684 renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2685 if not next_continuation:
2687 continuation = next_continuation.get('continuation')
2688 if not continuation:
2690 ctp = next_continuation.get('clickTrackingParams')
2691 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2694 def _extract_continuation(cls, renderer):
2695 next_continuation = cls._extract_next_continuation_data(renderer)
2696 if next_continuation:
2697 return next_continuation
2699 for key in ('contents', 'items'):
2700 contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2701 for content in contents:
2702 if not isinstance(content, dict):
2704 continuation_ep = try_get(
2705 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2707 if not continuation_ep:
2709 continuation = try_get(
2710 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2711 if not continuation:
2713 ctp = continuation_ep.get('clickTrackingParams')
2714 return YoutubeTabIE._build_continuation_query(continuation, ctp)
2716 def _entries(self, tab, identity_token, item_id):
2718 def extract_entries(parent_renderer): # this needs to called again for continuation to work with feeds
2719 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
2720 for content in contents:
2721 if not isinstance(content, dict):
2723 is_renderer = try_get(content, lambda x: x['itemSectionRenderer'], dict)
2725 renderer = content.get('richItemRenderer')
2727 for entry in self._rich_entries(renderer):
2729 continuation_list[0] = self._extract_continuation(parent_renderer)
2731 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2732 for isr_content in isr_contents:
2733 if not isinstance(isr_content, dict):
2737 'playlistVideoListRenderer': self._playlist_entries,
2738 'gridRenderer': self._grid_entries,
2739 'shelfRenderer': lambda x: self._shelf_entries(x, tab.get('title') != 'Channels'),
2740 'backstagePostThreadRenderer': self._post_thread_entries,
2741 'videoRenderer': lambda x: [self._video_entry(x)],
2743 for key, renderer in isr_content.items():
2744 if key not in known_renderers:
2746 for entry in known_renderers[key](renderer):
2749 continuation_list[0] = self._extract_continuation(renderer)
2752 if not continuation_list[0]:
2753 continuation_list[0] = self._extract_continuation(is_renderer)
2755 if not continuation_list[0]:
2756 continuation_list[0] = self._extract_continuation(parent_renderer)
2758 continuation_list = [None] # Python 2 doesnot support nonlocal
2759 tab_content = try_get(tab, lambda x: x['content'], dict)
2763 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
2764 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
2765 for entry in extract_entries(parent_renderer):
2767 continuation = continuation_list[0]
2770 'x-youtube-client-name': '1',
2771 'x-youtube-client-version': '2.20201112.04.01',
2774 headers['x-youtube-identity-token'] = identity_token
2776 for page_num in itertools.count(1):
2777 if not continuation:
2779 retries = self._downloader.params.get('extractor_retries', 3)
2782 while count < retries:
2785 self.report_warning('%s. Retrying ...' % last_error)
2787 response = self._call_api(
2788 ep="browse", fatal=True, headers=headers,
2789 video_id='%s page %s' % (item_id, page_num),
2791 'continuation': continuation['continuation'],
2792 'clickTracking': {'clickTrackingParams': continuation['itct']},
2794 note='Downloading API JSON%s' % (' (retry #%d)' % count if count else ''))
2795 except ExtractorError as e:
2796 if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503, 404):
2797 # Downloading page may result in intermittent 5xx HTTP error
2798 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
2799 last_error = 'HTTP Error %s' % e.cause.code
2804 # Youtube sometimes sends incomplete data
2805 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
2806 if response.get('continuationContents') or response.get('onResponseReceivedActions'):
2808 last_error = 'Incomplete data recieved'
2809 if count >= retries:
2810 self._downloader.report_error(last_error)
2815 known_continuation_renderers = {
2816 'playlistVideoListContinuation': self._playlist_entries,
2817 'gridContinuation': self._grid_entries,
2818 'itemSectionContinuation': self._post_thread_continuation_entries,
2819 'sectionListContinuation': extract_entries, # for feeds
2821 continuation_contents = try_get(
2822 response, lambda x: x['continuationContents'], dict) or {}
2823 continuation_renderer = None
2824 for key, value in continuation_contents.items():
2825 if key not in known_continuation_renderers:
2827 continuation_renderer = value
2828 continuation_list = [None]
2829 for entry in known_continuation_renderers[key](continuation_renderer):
2831 continuation = continuation_list[0] or self._extract_continuation(continuation_renderer)
2833 if continuation_renderer:
2837 'gridPlaylistRenderer': (self._grid_entries, 'items'),
2838 'gridVideoRenderer': (self._grid_entries, 'items'),
2839 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
2840 'itemSectionRenderer': (self._playlist_entries, 'contents'),
2841 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
2843 continuation_items = try_get(
2844 response, lambda x: x['onResponseReceivedActions'][0]['appendContinuationItemsAction']['continuationItems'], list)
2845 continuation_item = try_get(continuation_items, lambda x: x[0], dict) or {}
2846 video_items_renderer = None
2847 for key, value in continuation_item.items():
2848 if key not in known_renderers:
2850 video_items_renderer = {known_renderers[key][1]: continuation_items}
2851 continuation_list = [None]
2852 for entry in known_renderers[key][0](video_items_renderer):
2854 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
2856 if video_items_renderer:
2861 def _extract_selected_tab(tabs):
2863 if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
2864 return tab['tabRenderer']
2866 raise ExtractorError('Unable to find selected tab')
2869 def _extract_uploader(data):
2871 sidebar_renderer = try_get(
2872 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
2873 if sidebar_renderer:
2874 for item in sidebar_renderer:
2875 if not isinstance(item, dict):
2877 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
2878 if not isinstance(renderer, dict):
2881 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
2883 uploader['uploader'] = owner.get('text')
2884 uploader['uploader_id'] = try_get(
2885 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
2886 uploader['uploader_url'] = urljoin(
2887 'https://www.youtube.com/',
2888 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
2889 return {k: v for k, v in uploader.items() if v is not None}
2891 def _extract_from_tabs(self, item_id, webpage, data, tabs, identity_token):
2892 playlist_id = title = description = channel_url = channel_name = channel_id = None
2893 thumbnails_list = tags = []
2895 selected_tab = self._extract_selected_tab(tabs)
2897 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
2899 channel_name = renderer.get('title')
2900 channel_url = renderer.get('channelUrl')
2901 channel_id = renderer.get('externalId')
2905 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
2907 title = renderer.get('title')
2908 description = renderer.get('description', '')
2909 playlist_id = channel_id
2910 tags = renderer.get('keywords', '').split()
2912 try_get(renderer, lambda x: x['avatar']['thumbnails'], list)
2915 lambda x: x['sidebar']['playlistSidebarRenderer']['items'][0]['playlistSidebarPrimaryInfoRenderer']['thumbnailRenderer']['playlistVideoThumbnailRenderer']['thumbnail']['thumbnails'],
2920 for t in thumbnails_list:
2921 if not isinstance(t, dict):
2923 thumbnail_url = url_or_none(t.get('url'))
2924 if not thumbnail_url:
2927 'url': thumbnail_url,
2928 'width': int_or_none(t.get('width')),
2929 'height': int_or_none(t.get('height')),
2932 if playlist_id is None:
2933 playlist_id = item_id
2936 title += format_field(selected_tab, 'title', ' - %s')
2939 'playlist_id': playlist_id,
2940 'playlist_title': title,
2941 'playlist_description': description,
2942 'uploader': channel_name,
2943 'uploader_id': channel_id,
2944 'uploader_url': channel_url,
2945 'thumbnails': thumbnails,
2949 metadata.update(self._extract_uploader(data))
2951 'channel': metadata['uploader'],
2952 'channel_id': metadata['uploader_id'],
2953 'channel_url': metadata['uploader_url']})
2954 return self.playlist_result(
2955 self._entries(selected_tab, identity_token, playlist_id),
2958 def _extract_from_playlist(self, item_id, url, data, playlist):
2959 title = playlist.get('title') or try_get(
2960 data, lambda x: x['titleText']['simpleText'], compat_str)
2961 playlist_id = playlist.get('playlistId') or item_id
2962 # Inline playlist rendition continuation does not always work
2963 # at Youtube side, so delegating regular tab-based playlist URL
2964 # processing whenever possible.
2965 playlist_url = urljoin(url, try_get(
2966 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2968 if playlist_url and playlist_url != url:
2969 return self.url_result(
2970 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2972 return self.playlist_result(
2973 self._playlist_entries(playlist), playlist_id=playlist_id,
2974 playlist_title=title)
2977 def _extract_alerts(data):
2978 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
2979 if not isinstance(alert_dict, dict):
2981 for renderer in alert_dict:
2982 alert = alert_dict[renderer]
2983 alert_type = alert.get('type')
2986 message = try_get(alert, lambda x: x['text']['simpleText'], compat_str)
2988 yield alert_type, message
2989 for run in try_get(alert, lambda x: x['text']['runs'], list) or []:
2990 message = try_get(run, lambda x: x['text'], compat_str)
2992 yield alert_type, message
2994 def _extract_identity_token(self, webpage, item_id):
2995 ytcfg = self._extract_ytcfg(item_id, webpage)
2997 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
3000 return self._search_regex(
3001 r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
3002 'identity token', default=None)
3004 def _real_extract(self, url):
3005 item_id = self._match_id(url)
3006 url = compat_urlparse.urlunparse(
3007 compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
3008 is_home = re.match(r'(?P<pre>%s)(?P<post>/?(?![^#?]).*$)' % self._VALID_URL, url)
3009 if is_home is not None and is_home.group('not_channel') is None and item_id != 'feed':
3010 self._downloader.report_warning(
3011 'A channel/user page was given. All the channel\'s videos will be downloaded. '
3012 'To download only the videos in the home page, add a "/featured" to the URL')
3013 url = '%s/videos%s' % (is_home.group('pre'), is_home.group('post') or '')
3015 # Handle both video/playlist URLs
3016 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3017 video_id = qs.get('v', [None])[0]
3018 playlist_id = qs.get('list', [None])[0]
3020 if is_home is not None and is_home.group('not_channel') is not None and is_home.group('not_channel').startswith('watch') and not video_id:
3022 self._downloader.report_warning('%s is not a valid Youtube URL. Trying to download playlist %s' % (url, playlist_id))
3023 url = 'https://www.youtube.com/playlist?list=%s' % playlist_id
3024 # return self.url_result(playlist_id, ie=YoutubePlaylistIE.ie_key())
3026 raise ExtractorError('Unable to recognize tab page')
3027 if video_id and playlist_id:
3028 if self._downloader.params.get('noplaylist'):
3029 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
3030 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3031 self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
3033 retries = self._downloader.params.get('extractor_retries', 3)
3035 last_error = 'Incomplete yt initial data recieved'
3036 while count < retries:
3038 # Sometimes youtube returns a webpage with incomplete ytInitialData
3039 # See: https://github.com/yt-dlp/yt-dlp/issues/116
3041 self.report_warning('%s. Retrying ...' % last_error)
3042 webpage = self._download_webpage(
3044 'Downloading webpage%s' % ' (retry #%d)' % count if count else '')
3045 identity_token = self._extract_identity_token(webpage, item_id)
3046 data = self._extract_yt_initial_data(item_id, webpage)
3048 for alert_type, alert_message in self._extract_alerts(data):
3049 if alert_type.lower() == 'error':
3051 self._downloader.report_warning('YouTube said: %s - %s' % ('ERROR', err_msg))
3052 err_msg = alert_message
3054 self._downloader.report_warning('YouTube said: %s - %s' % (alert_type, alert_message))
3056 raise ExtractorError('YouTube said: %s' % err_msg, expected=True)
3057 if data.get('contents') or data.get('currentVideoEndpoint'):
3059 if count >= retries:
3060 self._downloader.report_error(last_error)
3063 data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
3065 return self._extract_from_tabs(item_id, webpage, data, tabs, identity_token)
3067 data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
3069 return self._extract_from_playlist(item_id, url, data, playlist)
3070 # Fallback to video extraction if no playlist alike page is recognized.
3071 # First check for the current video then try the v attribute of URL query.
3073 data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
3074 compat_str) or video_id
3076 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
3077 # Failed to recognize
3078 raise ExtractorError('Unable to recognize tab page')
3081 class YoutubePlaylistIE(InfoExtractor):
3082 IE_DESC = 'YouTube.com playlists'
3083 _VALID_URL = r'''(?x
)(?
:
3088 youtube(?
:kids
)?\
.com|
3093 (?P
<id>%(playlist_id)s)
3094 )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
3095 IE_NAME = 'youtube:playlist'
3097 'note': 'issue #673',
3098 'url': 'PLBB231211A4F62143',
3100 'title': '[OLD]Team Fortress 2 (Class-based LP)',
3101 'id': 'PLBB231211A4F62143',
3102 'uploader': 'Wickydoo',
3103 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
3105 'playlist_mincount': 29,
3107 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3109 'title': 'YDL_safe_search',
3110 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
3112 'playlist_count': 2,
3113 'skip': 'This playlist is private',
3116 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3117 'playlist_count': 4,
3120 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
3121 'uploader': 'milan',
3122 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
3125 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3126 'playlist_mincount': 982,
3128 'title': '2018 Chinese New Singles (11/6 updated)',
3129 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
3131 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
3134 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
3135 'only_matching': True,
3137 # music album playlist
3138 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
3139 'only_matching': True,
3143 def suitable(cls, url):
3144 return False if YoutubeTabIE.suitable(url) else super(
3145 YoutubePlaylistIE, cls).suitable(url)
3147 def _real_extract(self, url):
3148 playlist_id = self._match_id(url)
3149 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
3151 qs = {'list': playlist_id}
3152 return self.url_result(
3153 update_url_query('https://www.youtube.com/playlist', qs),
3154 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3157 class YoutubeYtBeIE(InfoExtractor):
3158 IE_DESC = 'youtu.be'
3159 _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}
3161 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
3163 'id': 'yeWKywCrFtk',
3165 'title': 'Small Scale Baler and Braiding Rugs',
3166 'uploader': 'Backus-Page House Museum',
3167 'uploader_id': 'backuspagemuseum',
3168 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
3169 'upload_date': '20161008',
3170 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
3171 'categories': ['Nonprofits & Activism'],
3174 'dislike_count': int,
3178 'skip_download': True,
3181 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
3182 'only_matching': True,
3185 def _real_extract(self, url):
3186 mobj = re.match(self._VALID_URL, url)
3187 video_id = mobj.group('id')
3188 playlist_id = mobj.group('playlist_id')
3189 return self.url_result(
3190 update_url_query('https://www.youtube.com/watch', {
3192 'list': playlist_id,
3193 'feature': 'youtu.be',
3194 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
3197 class YoutubeYtUserIE(InfoExtractor):
3198 IE_DESC = 'YouTube.com user videos, URL or "ytuser" keyword'
3199 _VALID_URL = r'ytuser:(?P<id>.+)'
3201 'url': 'ytuser:phihag',
3202 'only_matching': True,
3205 def _real_extract(self, url):
3206 user_id = self._match_id(url)
3207 return self.url_result(
3208 'https://www.youtube.com/user/%s' % user_id,
3209 ie=YoutubeTabIE.ie_key(), video_id=user_id)
3212 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
3213 IE_NAME = 'youtube:favorites'
3214 IE_DESC = 'YouTube.com liked videos, ":ytfav" for short (requires authentication)'
3215 _VALID_URL = r':ytfav(?:ou?rite)?s?'
3216 _LOGIN_REQUIRED = True
3219 'only_matching': True,
3221 'url': ':ytfavorites',
3222 'only_matching': True,
3225 def _real_extract(self, url):
3226 return self.url_result(
3227 'https://www.youtube.com/playlist?list=LL',
3228 ie=YoutubeTabIE.ie_key())
3231 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
3232 IE_DESC = 'YouTube.com searches, "ytsearch" keyword'
3233 # there doesn't appear to be a real limit, for example if you search for
3234 # 'python' you get more than 8.000.000 results
3235 _MAX_RESULTS = float('inf')
3236 IE_NAME = 'youtube:search'
3237 _SEARCH_KEY = 'ytsearch'
3238 _SEARCH_PARAMS = None
3241 def _entries(self, query, n):
3242 data = {'query': query}
3243 if self._SEARCH_PARAMS:
3244 data['params'] = self._SEARCH_PARAMS
3246 for page_num in itertools.count(1):
3247 search = self._call_api(
3248 ep='search', video_id='query "%s"' % query, fatal=False,
3249 note='Downloading page %s' % page_num, query=data)
3252 slr_contents = try_get(
3254 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3255 lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3257 if not slr_contents:
3260 # Youtube sometimes adds promoted content to searches,
3261 # changing the index location of videos and token.
3262 # So we search through all entries till we find them.
3263 continuation_token = None
3264 for slr_content in slr_contents:
3265 if continuation_token is None:
3266 continuation_token = try_get(
3268 lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3271 isr_contents = try_get(
3273 lambda x: x['itemSectionRenderer']['contents'],
3275 if not isr_contents:
3277 for content in isr_contents:
3278 if not isinstance(content, dict):
3280 video = content.get('videoRenderer')
3281 if not isinstance(video, dict):
3283 video_id = video.get('videoId')
3287 yield self._extract_video(video)
3292 if not continuation_token:
3294 data['continuation'] = continuation_token
3296 def _get_n_results(self, query, n):
3297 """Get a specified number of results for a query"""
3298 return self.playlist_result(self._entries(query, n), query)
3301 class YoutubeSearchDateIE(YoutubeSearchIE):
3302 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3303 _SEARCH_KEY = 'ytsearchdate'
3304 IE_DESC = 'YouTube.com searches, newest videos first, "ytsearchdate" keyword'
3305 _SEARCH_PARAMS = 'CAI%3D'
3308 class YoutubeSearchURLIE(YoutubeSearchIE):
3309 IE_DESC = 'YouTube.com search URLs'
3310 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
3311 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
3312 # _MAX_RESULTS = 100
3314 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3315 'playlist_mincount': 5,
3317 'title': 'youtube-dl test video',
3320 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3321 'only_matching': True,
3325 def _make_valid_url(cls):
3326 return cls._VALID_URL
3328 def _real_extract(self, url):
3329 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
3330 query = (qs.get('search_query') or qs.get('q'))[0]
3331 self._SEARCH_PARAMS = qs.get('sp', ('',))[0]
3332 return self._get_n_results(query, self._MAX_RESULTS)
3335 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3337 Base class for feed extractors
3338 Subclasses must define the _FEED_NAME property.
3340 _LOGIN_REQUIRED = True
3346 return 'youtube:%s' % self._FEED_NAME
3348 def _real_initialize(self):
3351 def _real_extract(self, url):
3352 return self.url_result(
3353 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3354 ie=YoutubeTabIE.ie_key())
3357 class YoutubeWatchLaterIE(InfoExtractor):
3358 IE_NAME = 'youtube:watchlater'
3359 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3360 _VALID_URL = r':ytwatchlater'
3362 'url': ':ytwatchlater',
3363 'only_matching': True,
3366 def _real_extract(self, url):
3367 return self.url_result(
3368 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3371 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3372 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3373 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
3374 _FEED_NAME = 'recommended'
3377 'only_matching': True,
3379 'url': ':ytrecommended',
3380 'only_matching': True,
3382 'url': 'https://youtube.com',
3383 'only_matching': True,
3387 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3388 IE_DESC = 'YouTube.com subscriptions feed, ":ytsubs" for short (requires authentication)'
3389 _VALID_URL = r':ytsub(?:scription)?s?'
3390 _FEED_NAME = 'subscriptions'
3393 'only_matching': True,
3395 'url': ':ytsubscriptions',
3396 'only_matching': True,
3400 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3401 IE_DESC = 'Youtube watch history, ":ythis" for short (requires authentication)'
3402 _VALID_URL = r':ythis(?:tory)?'
3403 _FEED_NAME = 'history'
3405 'url': ':ythistory',
3406 'only_matching': True,
3410 class YoutubeTruncatedURLIE(InfoExtractor):
3411 IE_NAME = 'youtube:truncated_url'
3412 IE_DESC = False # Do not list
3413 _VALID_URL = r'''(?x
)
3415 (?
:\w
+\
.)?
[yY
][oO
][uU
][tT
][uU
][bB
][eE
](?
:-nocookie
)?\
.com
/
3418 annotation_id
=annotation_
[^
&]+|
3424 attribution_link
\?a
=[^
&]+
3430 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3431 'only_matching': True,
3433 'url': 'https://www.youtube.com/watch?',
3434 'only_matching': True,
3436 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3437 'only_matching': True,
3439 'url': 'https://www.youtube.com/watch?feature=foo',
3440 'only_matching': True,
3442 'url': 'https://www.youtube.com/watch?hl=en-GB',
3443 'only_matching': True,
3445 'url': 'https://www.youtube.com/watch?t=2372',
3446 'only_matching': True,
3449 def _real_extract(self, url):
3450 raise ExtractorError(
3451 'Did you forget to quote the URL? Remember that & is a meta '
3452 'character in most shells, so you want to put the URL in quotes, '
3454 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3455 ' or simply youtube-dl BaW_jenozKc .',
3459 class YoutubeTruncatedIDIE(InfoExtractor):
3460 IE_NAME = 'youtube:truncated_id'
3461 IE_DESC = False # Do not list
3462 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
3465 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
3466 'only_matching': True,
3469 def _real_extract(self, url):
3470 video_id = self._match_id(url)
3471 raise ExtractorError(
3472 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),