]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/youtube.py
[eroprofile] Skip test
[youtube-dl.git] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 from __future__ import unicode_literals
4
5 import itertools
6 import json
7 import os.path
8 import random
9 import re
10 import traceback
11
12 from .common import InfoExtractor, SearchInfoExtractor
13 from ..compat import (
14     compat_chr,
15     compat_HTTPError,
16     compat_parse_qs,
17     compat_str,
18     compat_urllib_parse_unquote_plus,
19     compat_urllib_parse_urlencode,
20     compat_urllib_parse_urlparse,
21     compat_urlparse,
22 )
23 from ..jsinterp import JSInterpreter
24 from ..utils import (
25     ExtractorError,
26     clean_html,
27     dict_get,
28     float_or_none,
29     int_or_none,
30     mimetype2ext,
31     parse_codecs,
32     parse_duration,
33     qualities,
34     remove_start,
35     smuggle_url,
36     str_or_none,
37     str_to_int,
38     try_get,
39     unescapeHTML,
40     unified_strdate,
41     unsmuggle_url,
42     update_url_query,
43     url_or_none,
44     urlencode_postdata,
45     urljoin,
46 )
47
48
49 def parse_qs(url):
50     return compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
51
52
53 class YoutubeBaseInfoExtractor(InfoExtractor):
54     """Provide base functions for Youtube extractors"""
55     _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
56     _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
57
58     _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
59     _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
60     _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
61
62     _NETRC_MACHINE = 'youtube'
63     # If True it will raise an error if no login info is provided
64     _LOGIN_REQUIRED = False
65
66     _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
67
68     def _login(self):
69         """
70         Attempt to log in to YouTube.
71         True is returned if successful or skipped.
72         False is returned if login failed.
73
74         If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
75         """
76         username, password = self._get_login_info()
77         # No authentication to be performed
78         if username is None:
79             if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
80                 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
81             return True
82
83         login_page = self._download_webpage(
84             self._LOGIN_URL, None,
85             note='Downloading login page',
86             errnote='unable to fetch login page', fatal=False)
87         if login_page is False:
88             return
89
90         login_form = self._hidden_inputs(login_page)
91
92         def req(url, f_req, note, errnote):
93             data = login_form.copy()
94             data.update({
95                 'pstMsg': 1,
96                 'checkConnection': 'youtube',
97                 'checkedDomains': 'youtube',
98                 'hl': 'en',
99                 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
100                 'f.req': json.dumps(f_req),
101                 'flowName': 'GlifWebSignIn',
102                 'flowEntry': 'ServiceLogin',
103                 # TODO: reverse actual botguard identifier generation algo
104                 'bgRequest': '["identifier",""]',
105             })
106             return self._download_json(
107                 url, None, note=note, errnote=errnote,
108                 transform_source=lambda s: re.sub(r'^[^[]*', '', s),
109                 fatal=False,
110                 data=urlencode_postdata(data), headers={
111                     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
112                     'Google-Accounts-XSRF': 1,
113                 })
114
115         def warn(message):
116             self._downloader.report_warning(message)
117
118         lookup_req = [
119             username,
120             None, [], None, 'US', None, None, 2, False, True,
121             [
122                 None, None,
123                 [2, 1, None, 1,
124                  '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',
125                  None, [], 4],
126                 1, [None, None, []], None, None, None, True
127             ],
128             username,
129         ]
130
131         lookup_results = req(
132             self._LOOKUP_URL, lookup_req,
133             'Looking up account info', 'Unable to look up account info')
134
135         if lookup_results is False:
136             return False
137
138         user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
139         if not user_hash:
140             warn('Unable to extract user hash')
141             return False
142
143         challenge_req = [
144             user_hash,
145             None, 1, None, [1, None, None, None, [password, None, True]],
146             [
147                 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],
148                 1, [None, None, []], None, None, None, True
149             ]]
150
151         challenge_results = req(
152             self._CHALLENGE_URL, challenge_req,
153             'Logging in', 'Unable to log in')
154
155         if challenge_results is False:
156             return
157
158         login_res = try_get(challenge_results, lambda x: x[0][5], list)
159         if login_res:
160             login_msg = try_get(login_res, lambda x: x[5], compat_str)
161             warn(
162                 'Unable to login: %s' % 'Invalid password'
163                 if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
164             return False
165
166         res = try_get(challenge_results, lambda x: x[0][-1], list)
167         if not res:
168             warn('Unable to extract result entry')
169             return False
170
171         login_challenge = try_get(res, lambda x: x[0][0], list)
172         if login_challenge:
173             challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
174             if challenge_str == 'TWO_STEP_VERIFICATION':
175                 # SEND_SUCCESS - TFA code has been successfully sent to phone
176                 # QUOTA_EXCEEDED - reached the limit of TFA codes
177                 status = try_get(login_challenge, lambda x: x[5], compat_str)
178                 if status == 'QUOTA_EXCEEDED':
179                     warn('Exceeded the limit of TFA codes, try later')
180                     return False
181
182                 tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
183                 if not tl:
184                     warn('Unable to extract TL')
185                     return False
186
187                 tfa_code = self._get_tfa_info('2-step verification code')
188
189                 if not tfa_code:
190                     warn(
191                         'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
192                         '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
193                     return False
194
195                 tfa_code = remove_start(tfa_code, 'G-')
196
197                 tfa_req = [
198                     user_hash, None, 2, None,
199                     [
200                         9, None, None, None, None, None, None, None,
201                         [None, tfa_code, True, 2]
202                     ]]
203
204                 tfa_results = req(
205                     self._TFA_URL.format(tl), tfa_req,
206                     'Submitting TFA code', 'Unable to submit TFA code')
207
208                 if tfa_results is False:
209                     return False
210
211                 tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
212                 if tfa_res:
213                     tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
214                     warn(
215                         'Unable to finish TFA: %s' % 'Invalid TFA code'
216                         if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
217                     return False
218
219                 check_cookie_url = try_get(
220                     tfa_results, lambda x: x[0][-1][2], compat_str)
221             else:
222                 CHALLENGES = {
223                     'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
224                     'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
225                     'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
226                 }
227                 challenge = CHALLENGES.get(
228                     challenge_str,
229                     '%s returned error %s.' % (self.IE_NAME, challenge_str))
230                 warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
231                 return False
232         else:
233             check_cookie_url = try_get(res, lambda x: x[2], compat_str)
234
235         if not check_cookie_url:
236             warn('Unable to extract CheckCookie URL')
237             return False
238
239         check_cookie_results = self._download_webpage(
240             check_cookie_url, None, 'Checking cookie', fatal=False)
241
242         if check_cookie_results is False:
243             return False
244
245         if 'https://myaccount.google.com/' not in check_cookie_results:
246             warn('Unable to log in')
247             return False
248
249         return True
250
251     def _initialize_consent(self):
252         cookies = self._get_cookies('https://www.youtube.com/')
253         if cookies.get('__Secure-3PSID'):
254             return
255         consent_id = None
256         consent = cookies.get('CONSENT')
257         if consent:
258             if 'YES' in consent.value:
259                 return
260             consent_id = self._search_regex(
261                 r'PENDING\+(\d+)', consent.value, 'consent', default=None)
262         if not consent_id:
263             consent_id = random.randint(100, 999)
264         self._set_cookie('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id)
265
266     def _real_initialize(self):
267         self._initialize_consent()
268         if self._downloader is None:
269             return
270         if not self._login():
271             return
272
273     _DEFAULT_API_DATA = {
274         'context': {
275             'client': {
276                 'clientName': 'WEB',
277                 'clientVersion': '2.20201021.03.00',
278             }
279         },
280     }
281
282     _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
283     _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
284     _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
285
286     def _call_api(self, ep, query, video_id, fatal=True):
287         data = self._DEFAULT_API_DATA.copy()
288         data.update(query)
289
290         return self._download_json(
291             'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
292             note='Downloading API JSON', errnote='Unable to download API page',
293             data=json.dumps(data).encode('utf8'), fatal=fatal,
294             headers={'content-type': 'application/json'},
295             query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
296
297     def _extract_yt_initial_data(self, video_id, webpage):
298         return self._parse_json(
299             self._search_regex(
300                 (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
301                  self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
302             video_id)
303
304     def _extract_ytcfg(self, video_id, webpage):
305         return self._parse_json(
306             self._search_regex(
307                 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
308                 default='{}'), video_id, fatal=False) or {}
309
310     def _extract_video(self, renderer):
311         video_id = renderer['videoId']
312         title = try_get(
313             renderer,
314             (lambda x: x['title']['runs'][0]['text'],
315              lambda x: x['title']['simpleText']), compat_str)
316         description = try_get(
317             renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
318             compat_str)
319         duration = parse_duration(try_get(
320             renderer, lambda x: x['lengthText']['simpleText'], compat_str))
321         view_count_text = try_get(
322             renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
323         view_count = str_to_int(self._search_regex(
324             r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
325             'view count', default=None))
326         uploader = try_get(
327             renderer,
328             (lambda x: x['ownerText']['runs'][0]['text'],
329              lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
330         return {
331             '_type': 'url',
332             'ie_key': YoutubeIE.ie_key(),
333             'id': video_id,
334             'url': video_id,
335             'title': title,
336             'description': description,
337             'duration': duration,
338             'view_count': view_count,
339             'uploader': uploader,
340         }
341
342
343 class YoutubeIE(YoutubeBaseInfoExtractor):
344     IE_DESC = 'YouTube.com'
345     _INVIDIOUS_SITES = (
346         # invidious-redirect websites
347         r'(?:www\.)?redirect\.invidious\.io',
348         r'(?:(?:www|dev)\.)?invidio\.us',
349         # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
350         r'(?:(?:www|no)\.)?invidiou\.sh',
351         r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
352         r'(?:www\.)?invidious\.kabi\.tk',
353         r'(?:www\.)?invidious\.13ad\.de',
354         r'(?:www\.)?invidious\.mastodon\.host',
355         r'(?:www\.)?invidious\.zapashcanon\.fr',
356         r'(?:www\.)?invidious\.kavin\.rocks',
357         r'(?:www\.)?invidious\.tinfoil-hat\.net',
358         r'(?:www\.)?invidious\.himiko\.cloud',
359         r'(?:www\.)?invidious\.reallyancient\.tech',
360         r'(?:www\.)?invidious\.tube',
361         r'(?:www\.)?invidiou\.site',
362         r'(?:www\.)?invidious\.site',
363         r'(?:www\.)?invidious\.xyz',
364         r'(?:www\.)?invidious\.nixnet\.xyz',
365         r'(?:www\.)?invidious\.048596\.xyz',
366         r'(?:www\.)?invidious\.drycat\.fr',
367         r'(?:www\.)?inv\.skyn3t\.in',
368         r'(?:www\.)?tube\.poal\.co',
369         r'(?:www\.)?tube\.connect\.cafe',
370         r'(?:www\.)?vid\.wxzm\.sx',
371         r'(?:www\.)?vid\.mint\.lgbt',
372         r'(?:www\.)?vid\.puffyan\.us',
373         r'(?:www\.)?yewtu\.be',
374         r'(?:www\.)?yt\.elukerio\.org',
375         r'(?:www\.)?yt\.lelux\.fi',
376         r'(?:www\.)?invidious\.ggc-project\.de',
377         r'(?:www\.)?yt\.maisputain\.ovh',
378         r'(?:www\.)?ytprivate\.com',
379         r'(?:www\.)?invidious\.13ad\.de',
380         r'(?:www\.)?invidious\.toot\.koeln',
381         r'(?:www\.)?invidious\.fdn\.fr',
382         r'(?:www\.)?watch\.nettohikari\.com',
383         r'(?:www\.)?kgg2m7yk5aybusll\.onion',
384         r'(?:www\.)?qklhadlycap4cnod\.onion',
385         r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
386         r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
387         r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
388         r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
389         r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
390         r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
391     )
392     _VALID_URL = r"""(?x)^
393                      (
394                          (?:https?://|//)                                    # http(s):// or protocol-independent URL
395                          (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
396                             (?:www\.)?deturl\.com/www\.youtube\.com|
397                             (?:www\.)?pwnyoutube\.com|
398                             (?:www\.)?hooktube\.com|
399                             (?:www\.)?yourepeat\.com|
400                             tube\.majestyc\.net|
401                             %(invidious)s|
402                             youtube\.googleapis\.com)/                        # the various hostnames, with wildcard subdomains
403                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
404                          (?:                                                  # the various things that can precede the ID:
405                              (?:(?:v|embed|e)/(?!videoseries))                # v/ or embed/ or e/
406                              |(?:                                             # or the v= param in all its forms
407                                  (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)?  # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
408                                  (?:\?|\#!?)                                  # the params delimiter ? or # or #!
409                                  (?:.*?[&;])??                                # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
410                                  v=
411                              )
412                          ))
413                          |(?:
414                             youtu\.be|                                        # just youtu.be/xxxx
415                             vid\.plus|                                        # or vid.plus/xxxx
416                             zwearz\.com/watch|                                # or zwearz.com/watch/xxxx
417                             %(invidious)s
418                          )/
419                          |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
420                          )
421                      )?                                                       # all until now is optional -> you can pass the naked ID
422                      (?P<id>[0-9A-Za-z_-]{11})                                # here is it! the YouTube video ID
423                      (?(1).+)?                                                # if we found the ID, everything can follow
424                      $""" % {
425         'invidious': '|'.join(_INVIDIOUS_SITES),
426     }
427     _PLAYER_INFO_RE = (
428         r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
429         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$',
430         r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
431     )
432     _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
433
434     _GEO_BYPASS = False
435
436     IE_NAME = 'youtube'
437     _TESTS = [
438         {
439             'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
440             'info_dict': {
441                 'id': 'BaW_jenozKc',
442                 'ext': 'mp4',
443                 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
444                 'uploader': 'Philipp Hagemeister',
445                 'uploader_id': 'phihag',
446                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
447                 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
448                 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
449                 'upload_date': '20121002',
450                 '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 .',
451                 'categories': ['Science & Technology'],
452                 'tags': ['youtube-dl'],
453                 'duration': 10,
454                 'view_count': int,
455                 'like_count': int,
456                 'dislike_count': int,
457                 'start_time': 1,
458                 'end_time': 9,
459             }
460         },
461         {
462             'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
463             'note': 'Embed-only video (#1746)',
464             'info_dict': {
465                 'id': 'yZIXLfi8CZQ',
466                 'ext': 'mp4',
467                 'upload_date': '20120608',
468                 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
469                 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
470                 'uploader': 'SET India',
471                 'uploader_id': 'setindia',
472                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
473                 'age_limit': 18,
474             },
475             'skip': 'Private video',
476         },
477         {
478             'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
479             'note': 'Use the first video ID in the URL',
480             'info_dict': {
481                 'id': 'BaW_jenozKc',
482                 'ext': 'mp4',
483                 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
484                 'uploader': 'Philipp Hagemeister',
485                 'uploader_id': 'phihag',
486                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
487                 'upload_date': '20121002',
488                 '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 .',
489                 'categories': ['Science & Technology'],
490                 'tags': ['youtube-dl'],
491                 'duration': 10,
492                 'view_count': int,
493                 'like_count': int,
494                 'dislike_count': int,
495             },
496             'params': {
497                 'skip_download': True,
498             },
499         },
500         {
501             'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
502             'note': '256k DASH audio (format 141) via DASH manifest',
503             'info_dict': {
504                 'id': 'a9LDPn-MO4I',
505                 'ext': 'm4a',
506                 'upload_date': '20121002',
507                 'uploader_id': '8KVIDEO',
508                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
509                 'description': '',
510                 'uploader': '8KVIDEO',
511                 'title': 'UHDTV TEST 8K VIDEO.mp4'
512             },
513             'params': {
514                 'youtube_include_dash_manifest': True,
515                 'format': '141',
516             },
517             'skip': 'format 141 not served anymore',
518         },
519         # DASH manifest with encrypted signature
520         {
521             'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
522             'info_dict': {
523                 'id': 'IB3lcPjvWLA',
524                 'ext': 'm4a',
525                 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
526                 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
527                 'duration': 244,
528                 'uploader': 'AfrojackVEVO',
529                 'uploader_id': 'AfrojackVEVO',
530                 'upload_date': '20131011',
531                 'abr': 129.495,
532             },
533             'params': {
534                 'youtube_include_dash_manifest': True,
535                 'format': '141/bestaudio[ext=m4a]',
536             },
537         },
538         # Controversy video
539         {
540             'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
541             'info_dict': {
542                 'id': 'T4XJQO3qol8',
543                 'ext': 'mp4',
544                 'duration': 219,
545                 'upload_date': '20100909',
546                 'uploader': 'Amazing Atheist',
547                 'uploader_id': 'TheAmazingAtheist',
548                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
549                 'title': 'Burning Everyone\'s Koran',
550                 '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',
551             }
552         },
553         # Normal age-gate video (No vevo, embed allowed), available via embed page
554         {
555             'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
556             'info_dict': {
557                 'id': 'HtVdAasjOgU',
558                 'ext': 'mp4',
559                 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
560                 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
561                 'duration': 142,
562                 'uploader': 'The Witcher',
563                 'uploader_id': 'WitcherGame',
564                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
565                 'upload_date': '20140605',
566                 'age_limit': 18,
567             },
568         },
569         {
570             # Age-gated video only available with authentication (unavailable
571             # via embed page workaround)
572             'url': 'XgnwCQzjau8',
573             'only_matching': True,
574         },
575         # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
576         # YouTube Red ad is not captured for creator
577         {
578             'url': '__2ABJjxzNo',
579             'info_dict': {
580                 'id': '__2ABJjxzNo',
581                 'ext': 'mp4',
582                 'duration': 266,
583                 'upload_date': '20100430',
584                 'uploader_id': 'deadmau5',
585                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
586                 'creator': 'deadmau5',
587                 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
588                 'uploader': 'deadmau5',
589                 'title': 'Deadmau5 - Some Chords (HD)',
590                 'alt_title': 'Some Chords',
591             },
592             'expected_warnings': [
593                 'DASH manifest missing',
594             ]
595         },
596         # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
597         {
598             'url': 'lqQg6PlCWgI',
599             'info_dict': {
600                 'id': 'lqQg6PlCWgI',
601                 'ext': 'mp4',
602                 'duration': 6085,
603                 'upload_date': '20150827',
604                 'uploader_id': 'olympic',
605                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
606                 'description': 'HO09  - Women -  GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
607                 'uploader': 'Olympic',
608                 'title': 'Hockey - Women -  GER-AUS - London 2012 Olympic Games',
609             },
610             'params': {
611                 'skip_download': 'requires avconv',
612             }
613         },
614         # Non-square pixels
615         {
616             'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
617             'info_dict': {
618                 'id': '_b-2C3KPAM0',
619                 'ext': 'mp4',
620                 'stretched_ratio': 16 / 9.,
621                 'duration': 85,
622                 'upload_date': '20110310',
623                 'uploader_id': 'AllenMeow',
624                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
625                 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
626                 'uploader': '孫ᄋᄅ',
627                 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
628             },
629         },
630         # url_encoded_fmt_stream_map is empty string
631         {
632             'url': 'qEJwOuvDf7I',
633             'info_dict': {
634                 'id': 'qEJwOuvDf7I',
635                 'ext': 'webm',
636                 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
637                 'description': '',
638                 'upload_date': '20150404',
639                 'uploader_id': 'spbelect',
640                 'uploader': 'Наблюдатели Петербурга',
641             },
642             'params': {
643                 'skip_download': 'requires avconv',
644             },
645             'skip': 'This live event has ended.',
646         },
647         # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
648         {
649             'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
650             'info_dict': {
651                 'id': 'FIl7x6_3R5Y',
652                 'ext': 'webm',
653                 'title': 'md5:7b81415841e02ecd4313668cde88737a',
654                 'description': 'md5:116377fd2963b81ec4ce64b542173306',
655                 'duration': 220,
656                 'upload_date': '20150625',
657                 'uploader_id': 'dorappi2000',
658                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
659                 'uploader': 'dorappi2000',
660                 'formats': 'mincount:31',
661             },
662             'skip': 'not actual anymore',
663         },
664         # DASH manifest with segment_list
665         {
666             'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
667             'md5': '8ce563a1d667b599d21064e982ab9e31',
668             'info_dict': {
669                 'id': 'CsmdDsKjzN8',
670                 'ext': 'mp4',
671                 'upload_date': '20150501',  # According to '<meta itemprop="datePublished"', but in other places it's 20150510
672                 'uploader': 'Airtek',
673                 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
674                 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
675                 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
676             },
677             'params': {
678                 'youtube_include_dash_manifest': True,
679                 'format': '135',  # bestvideo
680             },
681             'skip': 'This live event has ended.',
682         },
683         {
684             # Multifeed videos (multiple cameras), URL is for Main Camera
685             'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
686             'info_dict': {
687                 'id': 'jvGDaLqkpTg',
688                 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
689                 'description': 'md5:e03b909557865076822aa169218d6a5d',
690             },
691             'playlist': [{
692                 'info_dict': {
693                     'id': 'jvGDaLqkpTg',
694                     'ext': 'mp4',
695                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
696                     'description': 'md5:e03b909557865076822aa169218d6a5d',
697                     'duration': 10643,
698                     'upload_date': '20161111',
699                     'uploader': 'Team PGP',
700                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
701                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
702                 },
703             }, {
704                 'info_dict': {
705                     'id': '3AKt1R1aDnw',
706                     'ext': 'mp4',
707                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
708                     'description': 'md5:e03b909557865076822aa169218d6a5d',
709                     'duration': 10991,
710                     'upload_date': '20161111',
711                     'uploader': 'Team PGP',
712                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
713                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
714                 },
715             }, {
716                 'info_dict': {
717                     'id': 'RtAMM00gpVc',
718                     'ext': 'mp4',
719                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
720                     'description': 'md5:e03b909557865076822aa169218d6a5d',
721                     'duration': 10995,
722                     'upload_date': '20161111',
723                     'uploader': 'Team PGP',
724                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
725                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
726                 },
727             }, {
728                 'info_dict': {
729                     'id': '6N2fdlP3C5U',
730                     'ext': 'mp4',
731                     'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
732                     'description': 'md5:e03b909557865076822aa169218d6a5d',
733                     'duration': 10990,
734                     'upload_date': '20161111',
735                     'uploader': 'Team PGP',
736                     'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
737                     'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
738                 },
739             }],
740             'params': {
741                 'skip_download': True,
742             },
743         },
744         {
745             # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
746             'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
747             'info_dict': {
748                 'id': 'gVfLd0zydlo',
749                 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
750             },
751             'playlist_count': 2,
752             'skip': 'Not multifeed anymore',
753         },
754         {
755             'url': 'https://vid.plus/FlRa-iH7PGw',
756             'only_matching': True,
757         },
758         {
759             'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
760             'only_matching': True,
761         },
762         {
763             # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
764             # Also tests cut-off URL expansion in video description (see
765             # https://github.com/ytdl-org/youtube-dl/issues/1892,
766             # https://github.com/ytdl-org/youtube-dl/issues/8164)
767             'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
768             'info_dict': {
769                 'id': 'lsguqyKfVQg',
770                 'ext': 'mp4',
771                 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
772                 'alt_title': 'Dark Walk - Position Music',
773                 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
774                 'duration': 133,
775                 'upload_date': '20151119',
776                 'uploader_id': 'IronSoulElf',
777                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
778                 'uploader': 'IronSoulElf',
779                 'creator': 'Todd Haberman,  Daniel Law Heath and Aaron Kaplan',
780                 'track': 'Dark Walk - Position Music',
781                 'artist': 'Todd Haberman,  Daniel Law Heath and Aaron Kaplan',
782                 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
783             },
784             'params': {
785                 'skip_download': True,
786             },
787         },
788         {
789             # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
790             'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
791             'only_matching': True,
792         },
793         {
794             # Video with yt:stretch=17:0
795             'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
796             'info_dict': {
797                 'id': 'Q39EVAstoRM',
798                 'ext': 'mp4',
799                 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
800                 'description': 'md5:ee18a25c350637c8faff806845bddee9',
801                 'upload_date': '20151107',
802                 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
803                 'uploader': 'CH GAMER DROID',
804             },
805             'params': {
806                 'skip_download': True,
807             },
808             'skip': 'This video does not exist.',
809         },
810         {
811             # Video with incomplete 'yt:stretch=16:'
812             'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
813             'only_matching': True,
814         },
815         {
816             # Video licensed under Creative Commons
817             'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
818             'info_dict': {
819                 'id': 'M4gD1WSo5mA',
820                 'ext': 'mp4',
821                 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
822                 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
823                 'duration': 721,
824                 'upload_date': '20150127',
825                 'uploader_id': 'BerkmanCenter',
826                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
827                 'uploader': 'The Berkman Klein Center for Internet & Society',
828                 'license': 'Creative Commons Attribution license (reuse allowed)',
829             },
830             'params': {
831                 'skip_download': True,
832             },
833         },
834         {
835             # Channel-like uploader_url
836             'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
837             'info_dict': {
838                 'id': 'eQcmzGIKrzg',
839                 'ext': 'mp4',
840                 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
841                 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
842                 'duration': 4060,
843                 'upload_date': '20151119',
844                 'uploader': 'Bernie Sanders',
845                 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
846                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
847                 'license': 'Creative Commons Attribution license (reuse allowed)',
848             },
849             'params': {
850                 'skip_download': True,
851             },
852         },
853         {
854             'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
855             'only_matching': True,
856         },
857         {
858             # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
859             'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
860             'only_matching': True,
861         },
862         {
863             # Rental video preview
864             'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
865             'info_dict': {
866                 'id': 'uGpuVWrhIzE',
867                 'ext': 'mp4',
868                 'title': 'Piku - Trailer',
869                 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
870                 'upload_date': '20150811',
871                 'uploader': 'FlixMatrix',
872                 'uploader_id': 'FlixMatrixKaravan',
873                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
874                 'license': 'Standard YouTube License',
875             },
876             'params': {
877                 'skip_download': True,
878             },
879             'skip': 'This video is not available.',
880         },
881         {
882             # YouTube Red video with episode data
883             'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
884             'info_dict': {
885                 'id': 'iqKdEhx-dD4',
886                 'ext': 'mp4',
887                 'title': 'Isolation - Mind Field (Ep 1)',
888                 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
889                 'duration': 2085,
890                 'upload_date': '20170118',
891                 'uploader': 'Vsauce',
892                 'uploader_id': 'Vsauce',
893                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
894                 'series': 'Mind Field',
895                 'season_number': 1,
896                 'episode_number': 1,
897             },
898             'params': {
899                 'skip_download': True,
900             },
901             'expected_warnings': [
902                 'Skipping DASH manifest',
903             ],
904         },
905         {
906             # The following content has been identified by the YouTube community
907             # as inappropriate or offensive to some audiences.
908             'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
909             'info_dict': {
910                 'id': '6SJNVb0GnPI',
911                 'ext': 'mp4',
912                 'title': 'Race Differences in Intelligence',
913                 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
914                 'duration': 965,
915                 'upload_date': '20140124',
916                 'uploader': 'New Century Foundation',
917                 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
918                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
919             },
920             'params': {
921                 'skip_download': True,
922             },
923             'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
924         },
925         {
926             # itag 212
927             'url': '1t24XAntNCY',
928             'only_matching': True,
929         },
930         {
931             # geo restricted to JP
932             'url': 'sJL6WA-aGkQ',
933             'only_matching': True,
934         },
935         {
936             'url': 'https://invidio.us/watch?v=BaW_jenozKc',
937             'only_matching': True,
938         },
939         {
940             'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
941             'only_matching': True,
942         },
943         {
944             # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
945             'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
946             'only_matching': True,
947         },
948         {
949             # DRM protected
950             'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
951             'only_matching': True,
952         },
953         {
954             # Video with unsupported adaptive stream type formats
955             'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
956             'info_dict': {
957                 'id': 'Z4Vy8R84T1U',
958                 'ext': 'mp4',
959                 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
960                 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
961                 'duration': 433,
962                 'upload_date': '20130923',
963                 'uploader': 'Amelia Putri Harwita',
964                 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
965                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
966                 'formats': 'maxcount:10',
967             },
968             'params': {
969                 'skip_download': True,
970                 'youtube_include_dash_manifest': False,
971             },
972             'skip': 'not actual anymore',
973         },
974         {
975             # Youtube Music Auto-generated description
976             'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
977             'info_dict': {
978                 'id': 'MgNrAu2pzNs',
979                 'ext': 'mp4',
980                 'title': 'Voyeur Girl',
981                 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
982                 'upload_date': '20190312',
983                 'uploader': 'Stephen - Topic',
984                 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
985                 'artist': 'Stephen',
986                 'track': 'Voyeur Girl',
987                 'album': 'it\'s too much love to know my dear',
988                 'release_date': '20190313',
989                 'release_year': 2019,
990             },
991             'params': {
992                 'skip_download': True,
993             },
994         },
995         {
996             'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
997             'only_matching': True,
998         },
999         {
1000             # invalid -> valid video id redirection
1001             'url': 'DJztXj2GPfl',
1002             'info_dict': {
1003                 'id': 'DJztXj2GPfk',
1004                 'ext': 'mp4',
1005                 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1006                 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1007                 'upload_date': '20090125',
1008                 'uploader': 'Prochorowka',
1009                 'uploader_id': 'Prochorowka',
1010                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1011                 'artist': 'Panjabi MC',
1012                 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1013                 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1014             },
1015             'params': {
1016                 'skip_download': True,
1017             },
1018             'skip': 'Video unavailable',
1019         },
1020         {
1021             # empty description results in an empty string
1022             'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1023             'info_dict': {
1024                 'id': 'x41yOUIvK2k',
1025                 'ext': 'mp4',
1026                 'title': 'IMG 3456',
1027                 'description': '',
1028                 'upload_date': '20170613',
1029                 'uploader_id': 'ElevageOrVert',
1030                 'uploader': 'ElevageOrVert',
1031             },
1032             'params': {
1033                 'skip_download': True,
1034             },
1035         },
1036         {
1037             # with '};' inside yt initial data (see [1])
1038             # see [2] for an example with '};' inside ytInitialPlayerResponse
1039             # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
1040             # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
1041             'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
1042             'info_dict': {
1043                 'id': 'CHqg6qOn4no',
1044                 'ext': 'mp4',
1045                 'title': 'Part 77   Sort a list of simple types in c#',
1046                 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
1047                 'upload_date': '20130831',
1048                 'uploader_id': 'kudvenkat',
1049                 'uploader': 'kudvenkat',
1050             },
1051             'params': {
1052                 'skip_download': True,
1053             },
1054         },
1055         {
1056             # another example of '};' in ytInitialData
1057             'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
1058             'only_matching': True,
1059         },
1060         {
1061             'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
1062             'only_matching': True,
1063         },
1064         {
1065             # https://github.com/ytdl-org/youtube-dl/pull/28094
1066             'url': 'OtqTfy26tG0',
1067             'info_dict': {
1068                 'id': 'OtqTfy26tG0',
1069                 'ext': 'mp4',
1070                 'title': 'Burn Out',
1071                 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
1072                 'upload_date': '20141120',
1073                 'uploader': 'The Cinematic Orchestra - Topic',
1074                 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
1075                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
1076                 'artist': 'The Cinematic Orchestra',
1077                 'track': 'Burn Out',
1078                 'album': 'Every Day',
1079                 'release_data': None,
1080                 'release_year': None,
1081             },
1082             'params': {
1083                 'skip_download': True,
1084             },
1085         },
1086         {
1087             # controversial video, only works with bpctr when authenticated with cookies
1088             'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
1089             'only_matching': True,
1090         },
1091         {
1092             # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
1093             'url': 'cBvYw8_A0vQ',
1094             'info_dict': {
1095                 'id': 'cBvYw8_A0vQ',
1096                 'ext': 'mp4',
1097                 'title': '4K Ueno Okachimachi  Street  Scenes  上野御徒町歩き',
1098                 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
1099                 'upload_date': '20201120',
1100                 'uploader': 'Walk around Japan',
1101                 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
1102                 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
1103             },
1104             'params': {
1105                 'skip_download': True,
1106             },
1107         },
1108     ]
1109     _formats = {
1110         '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1111         '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1112         '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
1113         '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
1114         '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
1115         '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1116         '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1117         '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1118         # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
1119         '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
1120         '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1121         '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1122         '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1123         '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1124         '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1125         '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
1126         '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1127         '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1128
1129
1130         # 3D videos
1131         '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1132         '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1133         '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1134         '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1135         '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
1136         '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1137         '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1138
1139         # Apple HTTP Live Streaming
1140         '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1141         '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1142         '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1143         '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1144         '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1145         '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1146         '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1147         '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
1148
1149         # DASH mp4 video
1150         '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
1151         '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
1152         '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1153         '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
1154         '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
1155         '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'},  # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
1156         '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
1157         '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1158         '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
1159         '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1160         '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1161         '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
1162
1163         # Dash mp4 audio
1164         '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
1165         '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
1166         '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
1167         '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1168         '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1169         '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
1170         '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
1171
1172         # Dash webm
1173         '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1174         '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1175         '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1176         '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1177         '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1178         '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1179         '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
1180         '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1181         '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1182         '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1183         '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1184         '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1185         '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1186         '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1187         '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1188         # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
1189         '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1190         '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1191         '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1192         '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1193         '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1194         '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1195
1196         # Dash webm audio
1197         '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
1198         '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
1199
1200         # Dash webm audio with opus inside
1201         '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
1202         '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
1203         '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
1204
1205         # RTMP (unnamed)
1206         '_rtmp': {'protocol': 'rtmp'},
1207
1208         # av01 video only formats sometimes served with "unknown" codecs
1209         '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1210         '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1211         '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1212         '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
1213     }
1214
1215     @classmethod
1216     def suitable(cls, url):
1217         # Hack for lazy extractors until more generic solution is implemented
1218         # (see #28780)
1219         from .youtube import parse_qs
1220         qs = parse_qs(url)
1221         if qs.get('list', [None])[0]:
1222             return False
1223         return super(YoutubeIE, cls).suitable(url)
1224
1225     def __init__(self, *args, **kwargs):
1226         super(YoutubeIE, self).__init__(*args, **kwargs)
1227         self._code_cache = {}
1228         self._player_cache = {}
1229
1230     def _signature_cache_id(self, example_sig):
1231         """ Return a string representation of a signature """
1232         return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
1233
1234     @classmethod
1235     def _extract_player_info(cls, player_url):
1236         for player_re in cls._PLAYER_INFO_RE:
1237             id_m = re.search(player_re, player_url)
1238             if id_m:
1239                 break
1240         else:
1241             raise ExtractorError('Cannot identify player %r' % player_url)
1242         return id_m.group('id')
1243
1244     def _extract_signature_function(self, video_id, player_url, example_sig):
1245         player_id = self._extract_player_info(player_url)
1246
1247         # Read from filesystem cache
1248         func_id = 'js_%s_%s' % (
1249             player_id, self._signature_cache_id(example_sig))
1250         assert os.path.basename(func_id) == func_id
1251
1252         cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
1253         if cache_spec is not None:
1254             return lambda s: ''.join(s[i] for i in cache_spec)
1255
1256         if player_id not in self._code_cache:
1257             self._code_cache[player_id] = self._download_webpage(
1258                 player_url, video_id,
1259                 note='Downloading player ' + player_id,
1260                 errnote='Download of %s failed' % player_url)
1261         code = self._code_cache[player_id]
1262         res = self._parse_sig_js(code)
1263
1264         test_string = ''.join(map(compat_chr, range(len(example_sig))))
1265         cache_res = res(test_string)
1266         cache_spec = [ord(c) for c in cache_res]
1267
1268         self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
1269         return res
1270
1271     def _print_sig_code(self, func, example_sig):
1272         def gen_sig_code(idxs):
1273             def _genslice(start, end, step):
1274                 starts = '' if start == 0 else str(start)
1275                 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
1276                 steps = '' if step == 1 else (':%d' % step)
1277                 return 's[%s%s%s]' % (starts, ends, steps)
1278
1279             step = None
1280             # Quelch pyflakes warnings - start will be set when step is set
1281             start = '(Never used)'
1282             for i, prev in zip(idxs[1:], idxs[:-1]):
1283                 if step is not None:
1284                     if i - prev == step:
1285                         continue
1286                     yield _genslice(start, prev, step)
1287                     step = None
1288                     continue
1289                 if i - prev in [-1, 1]:
1290                     step = i - prev
1291                     start = prev
1292                     continue
1293                 else:
1294                     yield 's[%d]' % prev
1295             if step is None:
1296                 yield 's[%d]' % i
1297             else:
1298                 yield _genslice(start, i, step)
1299
1300         test_string = ''.join(map(compat_chr, range(len(example_sig))))
1301         cache_res = func(test_string)
1302         cache_spec = [ord(c) for c in cache_res]
1303         expr_code = ' + '.join(gen_sig_code(cache_spec))
1304         signature_id_tuple = '(%s)' % (
1305             ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
1306         code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
1307                 '    return %s\n') % (signature_id_tuple, expr_code)
1308         self.to_screen('Extracted signature function:\n' + code)
1309
1310     def _parse_sig_js(self, jscode):
1311         funcname = self._search_regex(
1312             (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1313              r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1314              r'\bm=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(h\.s\)\)',
1315              r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2})\(decodeURIComponent\(c\)\)',
1316              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+\)',
1317              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*\)',
1318              r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
1319              # Obsolete patterns
1320              r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1321              r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
1322              r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1323              r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1324              r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1325              r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1326              r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1327              r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
1328             jscode, 'Initial JS player signature function name', group='sig')
1329
1330         jsi = JSInterpreter(jscode)
1331         initial_function = jsi.extract_function(funcname)
1332         return lambda s: initial_function([s])
1333
1334     def _decrypt_signature(self, s, video_id, player_url):
1335         """Turn the encrypted s field into a working signature"""
1336
1337         if player_url is None:
1338             raise ExtractorError('Cannot decrypt signature without player_url')
1339
1340         if player_url.startswith('//'):
1341             player_url = 'https:' + player_url
1342         elif not re.match(r'https?://', player_url):
1343             player_url = compat_urlparse.urljoin(
1344                 'https://www.youtube.com', player_url)
1345         try:
1346             player_id = (player_url, self._signature_cache_id(s))
1347             if player_id not in self._player_cache:
1348                 func = self._extract_signature_function(
1349                     video_id, player_url, s
1350                 )
1351                 self._player_cache[player_id] = func
1352             func = self._player_cache[player_id]
1353             if self._downloader.params.get('youtube_print_sig_code'):
1354                 self._print_sig_code(func, s)
1355             return func(s)
1356         except Exception as e:
1357             tb = traceback.format_exc()
1358             raise ExtractorError(
1359                 'Signature extraction failed: ' + tb, cause=e)
1360
1361     def _mark_watched(self, video_id, player_response):
1362         playback_url = url_or_none(try_get(
1363             player_response,
1364             lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
1365         if not playback_url:
1366             return
1367         parsed_playback_url = compat_urlparse.urlparse(playback_url)
1368         qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1369
1370         # cpn generation algorithm is reverse engineered from base.js.
1371         # In fact it works even with dummy cpn.
1372         CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
1373         cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1374
1375         qs.update({
1376             'ver': ['2'],
1377             'cpn': [cpn],
1378         })
1379         playback_url = compat_urlparse.urlunparse(
1380             parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
1381
1382         self._download_webpage(
1383             playback_url, video_id, 'Marking watched',
1384             'Unable to mark watched', fatal=False)
1385
1386     @staticmethod
1387     def _extract_urls(webpage):
1388         # Embedded YouTube player
1389         entries = [
1390             unescapeHTML(mobj.group('url'))
1391             for mobj in re.finditer(r'''(?x)
1392             (?:
1393                 <iframe[^>]+?src=|
1394                 data-video-url=|
1395                 <embed[^>]+?src=|
1396                 embedSWF\(?:\s*|
1397                 <object[^>]+data=|
1398                 new\s+SWFObject\(
1399             )
1400             (["\'])
1401                 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1402                 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1403             \1''', webpage)]
1404
1405         # lazyYT YouTube embed
1406         entries.extend(list(map(
1407             unescapeHTML,
1408             re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
1409
1410         # Wordpress "YouTube Video Importer" plugin
1411         matches = re.findall(r'''(?x)<div[^>]+
1412             class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
1413             data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
1414         entries.extend(m[-1] for m in matches)
1415
1416         return entries
1417
1418     @staticmethod
1419     def _extract_url(webpage):
1420         urls = YoutubeIE._extract_urls(webpage)
1421         return urls[0] if urls else None
1422
1423     @classmethod
1424     def extract_id(cls, url):
1425         mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
1426         if mobj is None:
1427             raise ExtractorError('Invalid URL: %s' % url)
1428         video_id = mobj.group(2)
1429         return video_id
1430
1431     def _extract_chapters_from_json(self, data, video_id, duration):
1432         chapters_list = try_get(
1433             data,
1434             lambda x: x['playerOverlays']
1435                        ['playerOverlayRenderer']
1436                        ['decoratedPlayerBarRenderer']
1437                        ['decoratedPlayerBarRenderer']
1438                        ['playerBar']
1439                        ['chapteredPlayerBarRenderer']
1440                        ['chapters'],
1441             list)
1442         if not chapters_list:
1443             return
1444
1445         def chapter_time(chapter):
1446             return float_or_none(
1447                 try_get(
1448                     chapter,
1449                     lambda x: x['chapterRenderer']['timeRangeStartMillis'],
1450                     int),
1451                 scale=1000)
1452         chapters = []
1453         for next_num, chapter in enumerate(chapters_list, start=1):
1454             start_time = chapter_time(chapter)
1455             if start_time is None:
1456                 continue
1457             end_time = (chapter_time(chapters_list[next_num])
1458                         if next_num < len(chapters_list) else duration)
1459             if end_time is None:
1460                 continue
1461             title = try_get(
1462                 chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
1463                 compat_str)
1464             chapters.append({
1465                 'start_time': start_time,
1466                 'end_time': end_time,
1467                 'title': title,
1468             })
1469         return chapters
1470
1471     def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
1472         return self._parse_json(self._search_regex(
1473             (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
1474              regex), webpage, name, default='{}'), video_id, fatal=False)
1475
1476     def _real_extract(self, url):
1477         url, smuggled_data = unsmuggle_url(url, {})
1478         video_id = self._match_id(url)
1479         base_url = self.http_scheme() + '//www.youtube.com/'
1480         webpage_url = base_url + 'watch?v=' + video_id
1481         webpage = self._download_webpage(
1482             webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
1483
1484         player_response = None
1485         if webpage:
1486             player_response = self._extract_yt_initial_variable(
1487                 webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
1488                 video_id, 'initial player response')
1489         if not player_response:
1490             player_response = self._call_api(
1491                 'player', {'videoId': video_id}, video_id)
1492
1493         playability_status = player_response.get('playabilityStatus') or {}
1494         if playability_status.get('reason') == 'Sign in to confirm your age':
1495             pr = self._parse_json(try_get(compat_parse_qs(
1496                 self._download_webpage(
1497                     base_url + 'get_video_info', video_id,
1498                     'Refetching age-gated info webpage',
1499                     'unable to download video info webpage', query={
1500                         'video_id': video_id,
1501                         'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1502                     }, fatal=False)),
1503                 lambda x: x['player_response'][0],
1504                 compat_str) or '{}', video_id)
1505             if pr:
1506                 player_response = pr
1507
1508         trailer_video_id = try_get(
1509             playability_status,
1510             lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
1511             compat_str)
1512         if trailer_video_id:
1513             return self.url_result(
1514                 trailer_video_id, self.ie_key(), trailer_video_id)
1515
1516         def get_text(x):
1517             if not x:
1518                 return
1519             text = x.get('simpleText')
1520             if text and isinstance(text, compat_str):
1521                 return text
1522             runs = x.get('runs')
1523             if not isinstance(runs, list):
1524                 return
1525             return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
1526
1527         search_meta = (
1528             lambda x: self._html_search_meta(x, webpage, default=None)) \
1529             if webpage else lambda x: None
1530
1531         video_details = player_response.get('videoDetails') or {}
1532         microformat = try_get(
1533             player_response,
1534             lambda x: x['microformat']['playerMicroformatRenderer'],
1535             dict) or {}
1536         video_title = video_details.get('title') \
1537             or get_text(microformat.get('title')) \
1538             or search_meta(['og:title', 'twitter:title', 'title'])
1539         video_description = video_details.get('shortDescription')
1540
1541         if not smuggled_data.get('force_singlefeed', False):
1542             if not self._downloader.params.get('noplaylist'):
1543                 multifeed_metadata_list = try_get(
1544                     player_response,
1545                     lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
1546                     compat_str)
1547                 if multifeed_metadata_list:
1548                     entries = []
1549                     feed_ids = []
1550                     for feed in multifeed_metadata_list.split(','):
1551                         # Unquote should take place before split on comma (,) since textual
1552                         # fields may contain comma as well (see
1553                         # https://github.com/ytdl-org/youtube-dl/issues/8536)
1554                         feed_data = compat_parse_qs(
1555                             compat_urllib_parse_unquote_plus(feed))
1556
1557                         def feed_entry(name):
1558                             return try_get(
1559                                 feed_data, lambda x: x[name][0], compat_str)
1560
1561                         feed_id = feed_entry('id')
1562                         if not feed_id:
1563                             continue
1564                         feed_title = feed_entry('title')
1565                         title = video_title
1566                         if feed_title:
1567                             title += ' (%s)' % feed_title
1568                         entries.append({
1569                             '_type': 'url_transparent',
1570                             'ie_key': 'Youtube',
1571                             'url': smuggle_url(
1572                                 base_url + 'watch?v=' + feed_data['id'][0],
1573                                 {'force_singlefeed': True}),
1574                             'title': title,
1575                         })
1576                         feed_ids.append(feed_id)
1577                     self.to_screen(
1578                         'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1579                         % (', '.join(feed_ids), video_id))
1580                     return self.playlist_result(
1581                         entries, video_id, video_title, video_description)
1582             else:
1583                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
1584
1585         formats = []
1586         itags = []
1587         itag_qualities = {}
1588         player_url = None
1589         q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
1590         streaming_data = player_response.get('streamingData') or {}
1591         streaming_formats = streaming_data.get('formats') or []
1592         streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
1593         for fmt in streaming_formats:
1594             if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
1595                 continue
1596
1597             itag = str_or_none(fmt.get('itag'))
1598             quality = fmt.get('quality')
1599             if itag and quality:
1600                 itag_qualities[itag] = quality
1601             # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
1602             # (adding `&sq=0` to the URL) and parsing emsg box to determine the
1603             # number of fragment that would subsequently requested with (`&sq=N`)
1604             if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
1605                 continue
1606
1607             fmt_url = fmt.get('url')
1608             if not fmt_url:
1609                 sc = compat_parse_qs(fmt.get('signatureCipher'))
1610                 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
1611                 encrypted_sig = try_get(sc, lambda x: x['s'][0])
1612                 if not (sc and fmt_url and encrypted_sig):
1613                     continue
1614                 if not player_url:
1615                     if not webpage:
1616                         continue
1617                     player_url = self._search_regex(
1618                         r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
1619                         webpage, 'player URL', fatal=False)
1620                 if not player_url:
1621                     continue
1622                 signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
1623                 sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
1624                 fmt_url += '&' + sp + '=' + signature
1625
1626             if itag:
1627                 itags.append(itag)
1628             tbr = float_or_none(
1629                 fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
1630             dct = {
1631                 'asr': int_or_none(fmt.get('audioSampleRate')),
1632                 'filesize': int_or_none(fmt.get('contentLength')),
1633                 'format_id': itag,
1634                 'format_note': fmt.get('qualityLabel') or quality,
1635                 'fps': int_or_none(fmt.get('fps')),
1636                 'height': int_or_none(fmt.get('height')),
1637                 'quality': q(quality),
1638                 'tbr': tbr,
1639                 'url': fmt_url,
1640                 'width': fmt.get('width'),
1641             }
1642             mimetype = fmt.get('mimeType')
1643             if mimetype:
1644                 mobj = re.match(
1645                     r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
1646                 if mobj:
1647                     dct['ext'] = mimetype2ext(mobj.group(1))
1648                     dct.update(parse_codecs(mobj.group(2)))
1649             no_audio = dct.get('acodec') == 'none'
1650             no_video = dct.get('vcodec') == 'none'
1651             if no_audio:
1652                 dct['vbr'] = tbr
1653             if no_video:
1654                 dct['abr'] = tbr
1655             if no_audio or no_video:
1656                 dct['downloader_options'] = {
1657                     # Youtube throttles chunks >~10M
1658                     'http_chunk_size': 10485760,
1659                 }
1660                 if dct.get('ext'):
1661                     dct['container'] = dct['ext'] + '_dash'
1662             formats.append(dct)
1663
1664         hls_manifest_url = streaming_data.get('hlsManifestUrl')
1665         if hls_manifest_url:
1666             for f in self._extract_m3u8_formats(
1667                     hls_manifest_url, video_id, 'mp4', fatal=False):
1668                 itag = self._search_regex(
1669                     r'/itag/(\d+)', f['url'], 'itag', default=None)
1670                 if itag:
1671                     f['format_id'] = itag
1672                 formats.append(f)
1673
1674         if self._downloader.params.get('youtube_include_dash_manifest', True):
1675             dash_manifest_url = streaming_data.get('dashManifestUrl')
1676             if dash_manifest_url:
1677                 for f in self._extract_mpd_formats(
1678                         dash_manifest_url, video_id, fatal=False):
1679                     itag = f['format_id']
1680                     if itag in itags:
1681                         continue
1682                     if itag in itag_qualities:
1683                         f['quality'] = q(itag_qualities[itag])
1684                     filesize = int_or_none(self._search_regex(
1685                         r'/clen/(\d+)', f.get('fragment_base_url')
1686                         or f['url'], 'file size', default=None))
1687                     if filesize:
1688                         f['filesize'] = filesize
1689                     formats.append(f)
1690
1691         if not formats:
1692             if streaming_data.get('licenseInfos'):
1693                 raise ExtractorError(
1694                     'This video is DRM protected.', expected=True)
1695             pemr = try_get(
1696                 playability_status,
1697                 lambda x: x['errorScreen']['playerErrorMessageRenderer'],
1698                 dict) or {}
1699             reason = get_text(pemr.get('reason')) or playability_status.get('reason')
1700             subreason = pemr.get('subreason')
1701             if subreason:
1702                 subreason = clean_html(get_text(subreason))
1703                 if subreason == 'The uploader has not made this video available in your country.':
1704                     countries = microformat.get('availableCountries')
1705                     if not countries:
1706                         regions_allowed = search_meta('regionsAllowed')
1707                         countries = regions_allowed.split(',') if regions_allowed else None
1708                     self.raise_geo_restricted(
1709                         subreason, countries)
1710                 reason += '\n' + subreason
1711             if reason:
1712                 raise ExtractorError(reason, expected=True)
1713
1714         self._sort_formats(formats)
1715
1716         keywords = video_details.get('keywords') or []
1717         if not keywords and webpage:
1718             keywords = [
1719                 unescapeHTML(m.group('content'))
1720                 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
1721         for keyword in keywords:
1722             if keyword.startswith('yt:stretch='):
1723                 mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
1724                 if mobj:
1725                     # NB: float is intentional for forcing float division
1726                     w, h = (float(v) for v in mobj.groups())
1727                     if w > 0 and h > 0:
1728                         ratio = w / h
1729                         for f in formats:
1730                             if f.get('vcodec') != 'none':
1731                                 f['stretched_ratio'] = ratio
1732                         break
1733
1734         thumbnails = []
1735         for container in (video_details, microformat):
1736             for thumbnail in (try_get(
1737                     container,
1738                     lambda x: x['thumbnail']['thumbnails'], list) or []):
1739                 thumbnail_url = thumbnail.get('url')
1740                 if not thumbnail_url:
1741                     continue
1742                 thumbnails.append({
1743                     'height': int_or_none(thumbnail.get('height')),
1744                     'url': thumbnail_url,
1745                     'width': int_or_none(thumbnail.get('width')),
1746                 })
1747             if thumbnails:
1748                 break
1749         else:
1750             thumbnail = search_meta(['og:image', 'twitter:image'])
1751             if thumbnail:
1752                 thumbnails = [{'url': thumbnail}]
1753
1754         category = microformat.get('category') or search_meta('genre')
1755         channel_id = video_details.get('channelId') \
1756             or microformat.get('externalChannelId') \
1757             or search_meta('channelId')
1758         duration = int_or_none(
1759             video_details.get('lengthSeconds')
1760             or microformat.get('lengthSeconds')) \
1761             or parse_duration(search_meta('duration'))
1762         is_live = video_details.get('isLive')
1763         owner_profile_url = microformat.get('ownerProfileUrl')
1764
1765         info = {
1766             'id': video_id,
1767             'title': self._live_title(video_title) if is_live else video_title,
1768             'formats': formats,
1769             'thumbnails': thumbnails,
1770             'description': video_description,
1771             'upload_date': unified_strdate(
1772                 microformat.get('uploadDate')
1773                 or search_meta('uploadDate')),
1774             'uploader': video_details['author'],
1775             'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
1776             'uploader_url': owner_profile_url,
1777             'channel_id': channel_id,
1778             'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
1779             'duration': duration,
1780             'view_count': int_or_none(
1781                 video_details.get('viewCount')
1782                 or microformat.get('viewCount')
1783                 or search_meta('interactionCount')),
1784             'average_rating': float_or_none(video_details.get('averageRating')),
1785             'age_limit': 18 if (
1786                 microformat.get('isFamilySafe') is False
1787                 or search_meta('isFamilyFriendly') == 'false'
1788                 or search_meta('og:restrictions:age') == '18+') else 0,
1789             'webpage_url': webpage_url,
1790             'categories': [category] if category else None,
1791             'tags': keywords,
1792             'is_live': is_live,
1793         }
1794
1795         pctr = try_get(
1796             player_response,
1797             lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
1798         if pctr:
1799             def process_language(container, base_url, lang_code, query):
1800                 lang_subs = []
1801                 for fmt in self._SUBTITLE_FORMATS:
1802                     query.update({
1803                         'fmt': fmt,
1804                     })
1805                     lang_subs.append({
1806                         'ext': fmt,
1807                         'url': update_url_query(base_url, query),
1808                     })
1809                 container[lang_code] = lang_subs
1810
1811             subtitles = {}
1812             for caption_track in (pctr.get('captionTracks') or []):
1813                 base_url = caption_track.get('baseUrl')
1814                 if not base_url:
1815                     continue
1816                 if caption_track.get('kind') != 'asr':
1817                     lang_code = caption_track.get('languageCode')
1818                     if not lang_code:
1819                         continue
1820                     process_language(
1821                         subtitles, base_url, lang_code, {})
1822                     continue
1823                 automatic_captions = {}
1824                 for translation_language in (pctr.get('translationLanguages') or []):
1825                     translation_language_code = translation_language.get('languageCode')
1826                     if not translation_language_code:
1827                         continue
1828                     process_language(
1829                         automatic_captions, base_url, translation_language_code,
1830                         {'tlang': translation_language_code})
1831                 info['automatic_captions'] = automatic_captions
1832             info['subtitles'] = subtitles
1833
1834         parsed_url = compat_urllib_parse_urlparse(url)
1835         for component in [parsed_url.fragment, parsed_url.query]:
1836             query = compat_parse_qs(component)
1837             for k, v in query.items():
1838                 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
1839                     d_k += '_time'
1840                     if d_k not in info and k in s_ks:
1841                         info[d_k] = parse_duration(query[k][0])
1842
1843         if video_description:
1844             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)
1845             if mobj:
1846                 release_year = mobj.group('release_year')
1847                 release_date = mobj.group('release_date')
1848                 if release_date:
1849                     release_date = release_date.replace('-', '')
1850                     if not release_year:
1851                         release_year = release_date[:4]
1852                 info.update({
1853                     'album': mobj.group('album'.strip()),
1854                     'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
1855                     'track': mobj.group('track').strip(),
1856                     'release_date': release_date,
1857                     'release_year': int_or_none(release_year),
1858                 })
1859
1860         initial_data = None
1861         if webpage:
1862             initial_data = self._extract_yt_initial_variable(
1863                 webpage, self._YT_INITIAL_DATA_RE, video_id,
1864                 'yt initial data')
1865         if not initial_data:
1866             initial_data = self._call_api(
1867                 'next', {'videoId': video_id}, video_id, fatal=False)
1868
1869         if initial_data:
1870             chapters = self._extract_chapters_from_json(
1871                 initial_data, video_id, duration)
1872             if not chapters:
1873                 for engagment_pannel in (initial_data.get('engagementPanels') or []):
1874                     contents = try_get(
1875                         engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
1876                         list)
1877                     if not contents:
1878                         continue
1879
1880                     def chapter_time(mmlir):
1881                         return parse_duration(
1882                             get_text(mmlir.get('timeDescription')))
1883
1884                     chapters = []
1885                     for next_num, content in enumerate(contents, start=1):
1886                         mmlir = content.get('macroMarkersListItemRenderer') or {}
1887                         start_time = chapter_time(mmlir)
1888                         end_time = chapter_time(try_get(
1889                             contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
1890                             if next_num < len(contents) else duration
1891                         if start_time is None or end_time is None:
1892                             continue
1893                         chapters.append({
1894                             'start_time': start_time,
1895                             'end_time': end_time,
1896                             'title': get_text(mmlir.get('title')),
1897                         })
1898                     if chapters:
1899                         break
1900             if chapters:
1901                 info['chapters'] = chapters
1902
1903             contents = try_get(
1904                 initial_data,
1905                 lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
1906                 list) or []
1907             for content in contents:
1908                 vpir = content.get('videoPrimaryInfoRenderer')
1909                 if vpir:
1910                     stl = vpir.get('superTitleLink')
1911                     if stl:
1912                         stl = get_text(stl)
1913                         if try_get(
1914                                 vpir,
1915                                 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
1916                             info['location'] = stl
1917                         else:
1918                             mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
1919                             if mobj:
1920                                 info.update({
1921                                     'series': mobj.group(1),
1922                                     'season_number': int(mobj.group(2)),
1923                                     'episode_number': int(mobj.group(3)),
1924                                 })
1925                     for tlb in (try_get(
1926                             vpir,
1927                             lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
1928                             list) or []):
1929                         tbr = tlb.get('toggleButtonRenderer') or {}
1930                         for getter, regex in [(
1931                                 lambda x: x['defaultText']['accessibility']['accessibilityData'],
1932                                 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
1933                                     lambda x: x['accessibility'],
1934                                     lambda x: x['accessibilityData']['accessibilityData'],
1935                                 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
1936                             label = (try_get(tbr, getter, dict) or {}).get('label')
1937                             if label:
1938                                 mobj = re.match(regex, label)
1939                                 if mobj:
1940                                     info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
1941                                     break
1942                     sbr_tooltip = try_get(
1943                         vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
1944                     if sbr_tooltip:
1945                         like_count, dislike_count = sbr_tooltip.split(' / ')
1946                         info.update({
1947                             'like_count': str_to_int(like_count),
1948                             'dislike_count': str_to_int(dislike_count),
1949                         })
1950                 vsir = content.get('videoSecondaryInfoRenderer')
1951                 if vsir:
1952                     info['channel'] = get_text(try_get(
1953                         vsir,
1954                         lambda x: x['owner']['videoOwnerRenderer']['title'],
1955                         dict))
1956                     rows = try_get(
1957                         vsir,
1958                         lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
1959                         list) or []
1960                     multiple_songs = False
1961                     for row in rows:
1962                         if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
1963                             multiple_songs = True
1964                             break
1965                     for row in rows:
1966                         mrr = row.get('metadataRowRenderer') or {}
1967                         mrr_title = mrr.get('title')
1968                         if not mrr_title:
1969                             continue
1970                         mrr_title = get_text(mrr['title'])
1971                         mrr_contents_text = get_text(mrr['contents'][0])
1972                         if mrr_title == 'License':
1973                             info['license'] = mrr_contents_text
1974                         elif not multiple_songs:
1975                             if mrr_title == 'Album':
1976                                 info['album'] = mrr_contents_text
1977                             elif mrr_title == 'Artist':
1978                                 info['artist'] = mrr_contents_text
1979                             elif mrr_title == 'Song':
1980                                 info['track'] = mrr_contents_text
1981
1982         for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
1983             v = info.get(s_k)
1984             if v:
1985                 info[d_k] = v
1986
1987         self.mark_watched(video_id, player_response)
1988
1989         return info
1990
1991
1992 class YoutubeTabIE(YoutubeBaseInfoExtractor):
1993     IE_DESC = 'YouTube.com tab'
1994     _VALID_URL = r'''(?x)
1995                     https?://
1996                         (?:\w+\.)?
1997                         (?:
1998                             youtube(?:kids)?\.com|
1999                             invidio\.us
2000                         )/
2001                         (?:
2002                             (?:channel|c|user|feed|hashtag)/|
2003                             (?:playlist|watch)\?.*?\blist=|
2004                             (?!(?:watch|embed|v|e)\b)
2005                         )
2006                         (?P<id>[^/?\#&]+)
2007                     '''
2008     IE_NAME = 'youtube:tab'
2009
2010     _TESTS = [{
2011         # playlists, multipage
2012         'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
2013         'playlist_mincount': 94,
2014         'info_dict': {
2015             'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2016             'title': 'Игорь Клейнер - Playlists',
2017             'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2018         },
2019     }, {
2020         # playlists, multipage, different order
2021         'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
2022         'playlist_mincount': 94,
2023         'info_dict': {
2024             'id': 'UCqj7Cz7revf5maW9g5pgNcg',
2025             'title': 'Игорь Клейнер - Playlists',
2026             'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
2027         },
2028     }, {
2029         # playlists, series
2030         'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
2031         'playlist_mincount': 5,
2032         'info_dict': {
2033             'id': 'UCYO_jab_esuFRV4b17AJtAw',
2034             'title': '3Blue1Brown - Playlists',
2035             'description': 'md5:e1384e8a133307dd10edee76e875d62f',
2036         },
2037     }, {
2038         # playlists, singlepage
2039         'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
2040         'playlist_mincount': 4,
2041         'info_dict': {
2042             'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
2043             'title': 'ThirstForScience - Playlists',
2044             'description': 'md5:609399d937ea957b0f53cbffb747a14c',
2045         }
2046     }, {
2047         'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
2048         'only_matching': True,
2049     }, {
2050         # basic, single video playlist
2051         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2052         'info_dict': {
2053             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2054             'uploader': 'Sergey M.',
2055             'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2056             'title': 'youtube-dl public playlist',
2057         },
2058         'playlist_count': 1,
2059     }, {
2060         # empty playlist
2061         'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2062         'info_dict': {
2063             'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
2064             'uploader': 'Sergey M.',
2065             'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
2066             'title': 'youtube-dl empty playlist',
2067         },
2068         'playlist_count': 0,
2069     }, {
2070         # Home tab
2071         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
2072         'info_dict': {
2073             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2074             'title': 'lex will - Home',
2075             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2076         },
2077         'playlist_mincount': 2,
2078     }, {
2079         # Videos tab
2080         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
2081         'info_dict': {
2082             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2083             'title': 'lex will - Videos',
2084             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2085         },
2086         'playlist_mincount': 975,
2087     }, {
2088         # Videos tab, sorted by popular
2089         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
2090         'info_dict': {
2091             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2092             'title': 'lex will - Videos',
2093             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2094         },
2095         'playlist_mincount': 199,
2096     }, {
2097         # Playlists tab
2098         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
2099         'info_dict': {
2100             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2101             'title': 'lex will - Playlists',
2102             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2103         },
2104         'playlist_mincount': 17,
2105     }, {
2106         # Community tab
2107         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
2108         'info_dict': {
2109             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2110             'title': 'lex will - Community',
2111             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2112         },
2113         'playlist_mincount': 18,
2114     }, {
2115         # Channels tab
2116         'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
2117         'info_dict': {
2118             'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
2119             'title': 'lex will - Channels',
2120             'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
2121         },
2122         'playlist_mincount': 138,
2123     }, {
2124         'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2125         'only_matching': True,
2126     }, {
2127         'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2128         'only_matching': True,
2129     }, {
2130         'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
2131         'only_matching': True,
2132     }, {
2133         'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
2134         'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2135         'info_dict': {
2136             'title': '29C3: Not my department',
2137             'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
2138             'uploader': 'Christiaan008',
2139             'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
2140         },
2141         'playlist_count': 96,
2142     }, {
2143         'note': 'Large playlist',
2144         'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
2145         'info_dict': {
2146             'title': 'Uploads from Cauchemar',
2147             'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
2148             'uploader': 'Cauchemar',
2149             'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
2150         },
2151         'playlist_mincount': 1123,
2152     }, {
2153         # even larger playlist, 8832 videos
2154         'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
2155         'only_matching': True,
2156     }, {
2157         'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
2158         'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
2159         'info_dict': {
2160             'title': 'Uploads from Interstellar Movie',
2161             'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
2162             'uploader': 'Interstellar Movie',
2163             'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
2164         },
2165         'playlist_mincount': 21,
2166     }, {
2167         # https://github.com/ytdl-org/youtube-dl/issues/21844
2168         'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2169         'info_dict': {
2170             'title': 'Data Analysis with Dr Mike Pound',
2171             'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
2172             'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
2173             'uploader': 'Computerphile',
2174         },
2175         'playlist_mincount': 11,
2176     }, {
2177         'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
2178         'only_matching': True,
2179     }, {
2180         # Playlist URL that does not actually serve a playlist
2181         'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
2182         'info_dict': {
2183             'id': 'FqZTN594JQw',
2184             'ext': 'webm',
2185             'title': "Smiley's People 01 detective, Adventure Series, Action",
2186             'uploader': 'STREEM',
2187             'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
2188             'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
2189             'upload_date': '20150526',
2190             'license': 'Standard YouTube License',
2191             'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2192             'categories': ['People & Blogs'],
2193             'tags': list,
2194             'view_count': int,
2195             'like_count': int,
2196             'dislike_count': int,
2197         },
2198         'params': {
2199             'skip_download': True,
2200         },
2201         'skip': 'This video is not available.',
2202         'add_ie': [YoutubeIE.ie_key()],
2203     }, {
2204         'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
2205         'only_matching': True,
2206     }, {
2207         'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
2208         'only_matching': True,
2209     }, {
2210         'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
2211         'info_dict': {
2212             'id': '9Auq9mYxFEE',
2213             'ext': 'mp4',
2214             'title': 'Watch Sky News live',
2215             'uploader': 'Sky News',
2216             'uploader_id': 'skynews',
2217             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
2218             'upload_date': '20191102',
2219             'description': 'md5:78de4e1c2359d0ea3ed829678e38b662',
2220             'categories': ['News & Politics'],
2221             'tags': list,
2222             'like_count': int,
2223             'dislike_count': int,
2224         },
2225         'params': {
2226             'skip_download': True,
2227         },
2228     }, {
2229         'url': 'https://www.youtube.com/user/TheYoungTurks/live',
2230         'info_dict': {
2231             'id': 'a48o2S1cPoo',
2232             'ext': 'mp4',
2233             'title': 'The Young Turks - Live Main Show',
2234             'uploader': 'The Young Turks',
2235             'uploader_id': 'TheYoungTurks',
2236             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
2237             'upload_date': '20150715',
2238             'license': 'Standard YouTube License',
2239             'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2240             'categories': ['News & Politics'],
2241             'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2242             'like_count': int,
2243             'dislike_count': int,
2244         },
2245         'params': {
2246             'skip_download': True,
2247         },
2248         'only_matching': True,
2249     }, {
2250         'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
2251         'only_matching': True,
2252     }, {
2253         'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2254         'only_matching': True,
2255     }, {
2256         'url': 'https://www.youtube.com/feed/trending',
2257         'only_matching': True,
2258     }, {
2259         # needs auth
2260         'url': 'https://www.youtube.com/feed/library',
2261         'only_matching': True,
2262     }, {
2263         # needs auth
2264         'url': 'https://www.youtube.com/feed/history',
2265         'only_matching': True,
2266     }, {
2267         # needs auth
2268         'url': 'https://www.youtube.com/feed/subscriptions',
2269         'only_matching': True,
2270     }, {
2271         # needs auth
2272         'url': 'https://www.youtube.com/feed/watch_later',
2273         'only_matching': True,
2274     }, {
2275         # no longer available?
2276         'url': 'https://www.youtube.com/feed/recommended',
2277         'only_matching': True,
2278     }, {
2279         # inline playlist with not always working continuations
2280         'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
2281         'only_matching': True,
2282     }, {
2283         'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
2284         'only_matching': True,
2285     }, {
2286         'url': 'https://www.youtube.com/course',
2287         'only_matching': True,
2288     }, {
2289         'url': 'https://www.youtube.com/zsecurity',
2290         'only_matching': True,
2291     }, {
2292         'url': 'http://www.youtube.com/NASAgovVideo/videos',
2293         'only_matching': True,
2294     }, {
2295         'url': 'https://www.youtube.com/TheYoungTurks/live',
2296         'only_matching': True,
2297     }, {
2298         'url': 'https://www.youtube.com/hashtag/cctv9',
2299         'info_dict': {
2300             'id': 'cctv9',
2301             'title': '#cctv9',
2302         },
2303         'playlist_mincount': 350,
2304     }, {
2305         'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
2306         'only_matching': True,
2307     }]
2308
2309     @classmethod
2310     def suitable(cls, url):
2311         return False if YoutubeIE.suitable(url) else super(
2312             YoutubeTabIE, cls).suitable(url)
2313
2314     def _extract_channel_id(self, webpage):
2315         channel_id = self._html_search_meta(
2316             'channelId', webpage, 'channel id', default=None)
2317         if channel_id:
2318             return channel_id
2319         channel_url = self._html_search_meta(
2320             ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
2321              'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
2322              'twitter:app:url:googleplay'), webpage, 'channel url')
2323         return self._search_regex(
2324             r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
2325             channel_url, 'channel id')
2326
2327     @staticmethod
2328     def _extract_grid_item_renderer(item):
2329         assert isinstance(item, dict)
2330         for key, renderer in item.items():
2331             if not key.startswith('grid') or not key.endswith('Renderer'):
2332                 continue
2333             if not isinstance(renderer, dict):
2334                 continue
2335             return renderer
2336
2337     def _grid_entries(self, grid_renderer):
2338         for item in grid_renderer['items']:
2339             if not isinstance(item, dict):
2340                 continue
2341             renderer = self._extract_grid_item_renderer(item)
2342             if not isinstance(renderer, dict):
2343                 continue
2344             title = try_get(
2345                 renderer, (lambda x: x['title']['runs'][0]['text'],
2346                            lambda x: x['title']['simpleText']), compat_str)
2347             # playlist
2348             playlist_id = renderer.get('playlistId')
2349             if playlist_id:
2350                 yield self.url_result(
2351                     'https://www.youtube.com/playlist?list=%s' % playlist_id,
2352                     ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2353                     video_title=title)
2354                 continue
2355             # video
2356             video_id = renderer.get('videoId')
2357             if video_id:
2358                 yield self._extract_video(renderer)
2359                 continue
2360             # channel
2361             channel_id = renderer.get('channelId')
2362             if channel_id:
2363                 title = try_get(
2364                     renderer, lambda x: x['title']['simpleText'], compat_str)
2365                 yield self.url_result(
2366                     'https://www.youtube.com/channel/%s' % channel_id,
2367                     ie=YoutubeTabIE.ie_key(), video_title=title)
2368                 continue
2369             # generic endpoint URL support
2370             ep_url = urljoin('https://www.youtube.com/', try_get(
2371                 renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
2372                 compat_str))
2373             if ep_url:
2374                 for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
2375                     if ie.suitable(ep_url):
2376                         yield self.url_result(
2377                             ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
2378                         break
2379
2380     def _shelf_entries_from_content(self, shelf_renderer):
2381         content = shelf_renderer.get('content')
2382         if not isinstance(content, dict):
2383             return
2384         renderer = content.get('gridRenderer')
2385         if renderer:
2386             # TODO: add support for nested playlists so each shelf is processed
2387             # as separate playlist
2388             # TODO: this includes only first N items
2389             for entry in self._grid_entries(renderer):
2390                 yield entry
2391         renderer = content.get('horizontalListRenderer')
2392         if renderer:
2393             # TODO
2394             pass
2395
2396     def _shelf_entries(self, shelf_renderer, skip_channels=False):
2397         ep = try_get(
2398             shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2399             compat_str)
2400         shelf_url = urljoin('https://www.youtube.com', ep)
2401         if shelf_url:
2402             # Skipping links to another channels, note that checking for
2403             # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
2404             # will not work
2405             if skip_channels and '/channels?' in shelf_url:
2406                 return
2407             title = try_get(
2408                 shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
2409             yield self.url_result(shelf_url, video_title=title)
2410         # Shelf may not contain shelf URL, fallback to extraction from content
2411         for entry in self._shelf_entries_from_content(shelf_renderer):
2412             yield entry
2413
2414     def _playlist_entries(self, video_list_renderer):
2415         for content in video_list_renderer['contents']:
2416             if not isinstance(content, dict):
2417                 continue
2418             renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
2419             if not isinstance(renderer, dict):
2420                 continue
2421             video_id = renderer.get('videoId')
2422             if not video_id:
2423                 continue
2424             yield self._extract_video(renderer)
2425
2426     def _video_entry(self, video_renderer):
2427         video_id = video_renderer.get('videoId')
2428         if video_id:
2429             return self._extract_video(video_renderer)
2430
2431     def _post_thread_entries(self, post_thread_renderer):
2432         post_renderer = try_get(
2433             post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
2434         if not post_renderer:
2435             return
2436         # video attachment
2437         video_renderer = try_get(
2438             post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
2439         video_id = None
2440         if video_renderer:
2441             entry = self._video_entry(video_renderer)
2442             if entry:
2443                 yield entry
2444         # inline video links
2445         runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
2446         for run in runs:
2447             if not isinstance(run, dict):
2448                 continue
2449             ep_url = try_get(
2450                 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
2451             if not ep_url:
2452                 continue
2453             if not YoutubeIE.suitable(ep_url):
2454                 continue
2455             ep_video_id = YoutubeIE._match_id(ep_url)
2456             if video_id == ep_video_id:
2457                 continue
2458             yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
2459
2460     def _post_thread_continuation_entries(self, post_thread_continuation):
2461         contents = post_thread_continuation.get('contents')
2462         if not isinstance(contents, list):
2463             return
2464         for content in contents:
2465             renderer = content.get('backstagePostThreadRenderer')
2466             if not isinstance(renderer, dict):
2467                 continue
2468             for entry in self._post_thread_entries(renderer):
2469                 yield entry
2470
2471     def _rich_grid_entries(self, contents):
2472         for content in contents:
2473             video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
2474             if video_renderer:
2475                 entry = self._video_entry(video_renderer)
2476                 if entry:
2477                     yield entry
2478
2479     @staticmethod
2480     def _build_continuation_query(continuation, ctp=None):
2481         query = {
2482             'ctoken': continuation,
2483             'continuation': continuation,
2484         }
2485         if ctp:
2486             query['itct'] = ctp
2487         return query
2488
2489     @staticmethod
2490     def _extract_next_continuation_data(renderer):
2491         next_continuation = try_get(
2492             renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
2493         if not next_continuation:
2494             return
2495         continuation = next_continuation.get('continuation')
2496         if not continuation:
2497             return
2498         ctp = next_continuation.get('clickTrackingParams')
2499         return YoutubeTabIE._build_continuation_query(continuation, ctp)
2500
2501     @classmethod
2502     def _extract_continuation(cls, renderer):
2503         next_continuation = cls._extract_next_continuation_data(renderer)
2504         if next_continuation:
2505             return next_continuation
2506         contents = []
2507         for key in ('contents', 'items'):
2508             contents.extend(try_get(renderer, lambda x: x[key], list) or [])
2509         for content in contents:
2510             if not isinstance(content, dict):
2511                 continue
2512             continuation_ep = try_get(
2513                 content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
2514                 dict)
2515             if not continuation_ep:
2516                 continue
2517             continuation = try_get(
2518                 continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
2519             if not continuation:
2520                 continue
2521             ctp = continuation_ep.get('clickTrackingParams')
2522             return YoutubeTabIE._build_continuation_query(continuation, ctp)
2523
2524     def _entries(self, tab, item_id, webpage):
2525         tab_content = try_get(tab, lambda x: x['content'], dict)
2526         if not tab_content:
2527             return
2528         slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
2529         if slr_renderer:
2530             is_channels_tab = tab.get('title') == 'Channels'
2531             continuation = None
2532             slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
2533             for slr_content in slr_contents:
2534                 if not isinstance(slr_content, dict):
2535                     continue
2536                 is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
2537                 if not is_renderer:
2538                     continue
2539                 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
2540                 for isr_content in isr_contents:
2541                     if not isinstance(isr_content, dict):
2542                         continue
2543                     renderer = isr_content.get('playlistVideoListRenderer')
2544                     if renderer:
2545                         for entry in self._playlist_entries(renderer):
2546                             yield entry
2547                         continuation = self._extract_continuation(renderer)
2548                         continue
2549                     renderer = isr_content.get('gridRenderer')
2550                     if renderer:
2551                         for entry in self._grid_entries(renderer):
2552                             yield entry
2553                         continuation = self._extract_continuation(renderer)
2554                         continue
2555                     renderer = isr_content.get('shelfRenderer')
2556                     if renderer:
2557                         for entry in self._shelf_entries(renderer, not is_channels_tab):
2558                             yield entry
2559                         continue
2560                     renderer = isr_content.get('backstagePostThreadRenderer')
2561                     if renderer:
2562                         for entry in self._post_thread_entries(renderer):
2563                             yield entry
2564                         continuation = self._extract_continuation(renderer)
2565                         continue
2566                     renderer = isr_content.get('videoRenderer')
2567                     if renderer:
2568                         entry = self._video_entry(renderer)
2569                         if entry:
2570                             yield entry
2571
2572                 if not continuation:
2573                     continuation = self._extract_continuation(is_renderer)
2574             if not continuation:
2575                 continuation = self._extract_continuation(slr_renderer)
2576         else:
2577             rich_grid_renderer = tab_content.get('richGridRenderer')
2578             if not rich_grid_renderer:
2579                 return
2580             for entry in self._rich_grid_entries(rich_grid_renderer.get('contents') or []):
2581                 yield entry
2582             continuation = self._extract_continuation(rich_grid_renderer)
2583
2584         ytcfg = self._extract_ytcfg(item_id, webpage)
2585         client_version = try_get(
2586             ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
2587
2588         headers = {
2589             'x-youtube-client-name': '1',
2590             'x-youtube-client-version': client_version,
2591             'content-type': 'application/json',
2592         }
2593
2594         context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
2595             'client': {
2596                 'clientName': 'WEB',
2597                 'clientVersion': client_version,
2598             }
2599         }
2600         visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
2601
2602         identity_token = self._extract_identity_token(ytcfg, webpage)
2603         if identity_token:
2604             headers['x-youtube-identity-token'] = identity_token
2605
2606         data = {
2607             'context': context,
2608         }
2609
2610         for page_num in itertools.count(1):
2611             if not continuation:
2612                 break
2613             if visitor_data:
2614                 headers['x-goog-visitor-id'] = visitor_data
2615             data['continuation'] = continuation['continuation']
2616             data['clickTracking'] = {
2617                 'clickTrackingParams': continuation['itct']
2618             }
2619             count = 0
2620             retries = 3
2621             while count <= retries:
2622                 try:
2623                     # Downloading page may result in intermittent 5xx HTTP error
2624                     # that is usually worked around with a retry
2625                     response = self._download_json(
2626                         'https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
2627                         None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
2628                         headers=headers, data=json.dumps(data).encode('utf8'))
2629                     break
2630                 except ExtractorError as e:
2631                     if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
2632                         count += 1
2633                         if count <= retries:
2634                             continue
2635                     raise
2636             if not response:
2637                 break
2638
2639             visitor_data = try_get(
2640                 response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
2641
2642             continuation_contents = try_get(
2643                 response, lambda x: x['continuationContents'], dict)
2644             if continuation_contents:
2645                 continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
2646                 if continuation_renderer:
2647                     for entry in self._playlist_entries(continuation_renderer):
2648                         yield entry
2649                     continuation = self._extract_continuation(continuation_renderer)
2650                     continue
2651                 continuation_renderer = continuation_contents.get('gridContinuation')
2652                 if continuation_renderer:
2653                     for entry in self._grid_entries(continuation_renderer):
2654                         yield entry
2655                     continuation = self._extract_continuation(continuation_renderer)
2656                     continue
2657                 continuation_renderer = continuation_contents.get('itemSectionContinuation')
2658                 if continuation_renderer:
2659                     for entry in self._post_thread_continuation_entries(continuation_renderer):
2660                         yield entry
2661                     continuation = self._extract_continuation(continuation_renderer)
2662                     continue
2663
2664             on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
2665             continuation_items = try_get(
2666                 on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
2667             if continuation_items:
2668                 continuation_item = continuation_items[0]
2669                 if not isinstance(continuation_item, dict):
2670                     continue
2671                 renderer = self._extract_grid_item_renderer(continuation_item)
2672                 if renderer:
2673                     grid_renderer = {'items': continuation_items}
2674                     for entry in self._grid_entries(grid_renderer):
2675                         yield entry
2676                     continuation = self._extract_continuation(grid_renderer)
2677                     continue
2678                 renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
2679                 if renderer:
2680                     video_list_renderer = {'contents': continuation_items}
2681                     for entry in self._playlist_entries(video_list_renderer):
2682                         yield entry
2683                     continuation = self._extract_continuation(video_list_renderer)
2684                     continue
2685                 renderer = continuation_item.get('backstagePostThreadRenderer')
2686                 if renderer:
2687                     continuation_renderer = {'contents': continuation_items}
2688                     for entry in self._post_thread_continuation_entries(continuation_renderer):
2689                         yield entry
2690                     continuation = self._extract_continuation(continuation_renderer)
2691                     continue
2692                 renderer = continuation_item.get('richItemRenderer')
2693                 if renderer:
2694                     for entry in self._rich_grid_entries(continuation_items):
2695                         yield entry
2696                     continuation = self._extract_continuation({'contents': continuation_items})
2697                     continue
2698
2699             break
2700
2701     @staticmethod
2702     def _extract_selected_tab(tabs):
2703         for tab in tabs:
2704             if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
2705                 return tab['tabRenderer']
2706         else:
2707             raise ExtractorError('Unable to find selected tab')
2708
2709     @staticmethod
2710     def _extract_uploader(data):
2711         uploader = {}
2712         sidebar_renderer = try_get(
2713             data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
2714         if sidebar_renderer:
2715             for item in sidebar_renderer:
2716                 if not isinstance(item, dict):
2717                     continue
2718                 renderer = item.get('playlistSidebarSecondaryInfoRenderer')
2719                 if not isinstance(renderer, dict):
2720                     continue
2721                 owner = try_get(
2722                     renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
2723                 if owner:
2724                     uploader['uploader'] = owner.get('text')
2725                     uploader['uploader_id'] = try_get(
2726                         owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
2727                     uploader['uploader_url'] = urljoin(
2728                         'https://www.youtube.com/',
2729                         try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
2730         return uploader
2731
2732     @staticmethod
2733     def _extract_alert(data):
2734         alerts = []
2735         for alert in try_get(data, lambda x: x['alerts'], list) or []:
2736             if not isinstance(alert, dict):
2737                 continue
2738             alert_text = try_get(
2739                 alert, lambda x: x['alertRenderer']['text'], dict)
2740             if not alert_text:
2741                 continue
2742             text = try_get(
2743                 alert_text,
2744                 (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
2745                 compat_str)
2746             if text:
2747                 alerts.append(text)
2748         return '\n'.join(alerts)
2749
2750     def _extract_from_tabs(self, item_id, webpage, data, tabs):
2751         selected_tab = self._extract_selected_tab(tabs)
2752         renderer = try_get(
2753             data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
2754         playlist_id = item_id
2755         title = description = None
2756         if renderer:
2757             channel_title = renderer.get('title') or item_id
2758             tab_title = selected_tab.get('title')
2759             title = channel_title or item_id
2760             if tab_title:
2761                 title += ' - %s' % tab_title
2762             description = renderer.get('description')
2763             playlist_id = renderer.get('externalId')
2764         else:
2765             renderer = try_get(
2766                 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
2767             if renderer:
2768                 title = renderer.get('title')
2769             else:
2770                 renderer = try_get(
2771                     data, lambda x: x['header']['hashtagHeaderRenderer'], dict)
2772                 if renderer:
2773                     title = try_get(renderer, lambda x: x['hashtag']['simpleText'])
2774         playlist = self.playlist_result(
2775             self._entries(selected_tab, item_id, webpage),
2776             playlist_id=playlist_id, playlist_title=title,
2777             playlist_description=description)
2778         playlist.update(self._extract_uploader(data))
2779         return playlist
2780
2781     def _extract_from_playlist(self, item_id, url, data, playlist):
2782         title = playlist.get('title') or try_get(
2783             data, lambda x: x['titleText']['simpleText'], compat_str)
2784         playlist_id = playlist.get('playlistId') or item_id
2785         # Inline playlist rendition continuation does not always work
2786         # at Youtube side, so delegating regular tab-based playlist URL
2787         # processing whenever possible.
2788         playlist_url = urljoin(url, try_get(
2789             playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
2790             compat_str))
2791         if playlist_url and playlist_url != url:
2792             return self.url_result(
2793                 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
2794                 video_title=title)
2795         return self.playlist_result(
2796             self._playlist_entries(playlist), playlist_id=playlist_id,
2797             playlist_title=title)
2798
2799     def _extract_identity_token(self, ytcfg, webpage):
2800         if ytcfg:
2801             token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
2802             if token:
2803                 return token
2804         return self._search_regex(
2805             r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
2806             'identity token', default=None)
2807
2808     def _real_extract(self, url):
2809         item_id = self._match_id(url)
2810         url = compat_urlparse.urlunparse(
2811             compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
2812         # Handle both video/playlist URLs
2813         qs = parse_qs(url)
2814         video_id = qs.get('v', [None])[0]
2815         playlist_id = qs.get('list', [None])[0]
2816         if video_id and playlist_id:
2817             if self._downloader.params.get('noplaylist'):
2818                 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
2819                 return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2820             self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
2821         webpage = self._download_webpage(url, item_id)
2822         data = self._extract_yt_initial_data(item_id, webpage)
2823         tabs = try_get(
2824             data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
2825         if tabs:
2826             return self._extract_from_tabs(item_id, webpage, data, tabs)
2827         playlist = try_get(
2828             data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
2829         if playlist:
2830             return self._extract_from_playlist(item_id, url, data, playlist)
2831         # Fallback to video extraction if no playlist alike page is recognized.
2832         # First check for the current video then try the v attribute of URL query.
2833         video_id = try_get(
2834             data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
2835             compat_str) or video_id
2836         if video_id:
2837             return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
2838         # Capture and output alerts
2839         alert = self._extract_alert(data)
2840         if alert:
2841             raise ExtractorError(alert, expected=True)
2842         # Failed to recognize
2843         raise ExtractorError('Unable to recognize tab page')
2844
2845
2846 class YoutubePlaylistIE(InfoExtractor):
2847     IE_DESC = 'YouTube.com playlists'
2848     _VALID_URL = r'''(?x)(?:
2849                         (?:https?://)?
2850                         (?:\w+\.)?
2851                         (?:
2852                             (?:
2853                                 youtube(?:kids)?\.com|
2854                                 invidio\.us
2855                             )
2856                             /.*?\?.*?\blist=
2857                         )?
2858                         (?P<id>%(playlist_id)s)
2859                      )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
2860     IE_NAME = 'youtube:playlist'
2861     _TESTS = [{
2862         'note': 'issue #673',
2863         'url': 'PLBB231211A4F62143',
2864         'info_dict': {
2865             'title': '[OLD]Team Fortress 2 (Class-based LP)',
2866             'id': 'PLBB231211A4F62143',
2867             'uploader': 'Wickydoo',
2868             'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
2869         },
2870         'playlist_mincount': 29,
2871     }, {
2872         'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2873         'info_dict': {
2874             'title': 'YDL_safe_search',
2875             'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
2876         },
2877         'playlist_count': 2,
2878         'skip': 'This playlist is private',
2879     }, {
2880         'note': 'embedded',
2881         'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2882         'playlist_count': 4,
2883         'info_dict': {
2884             'title': 'JODA15',
2885             'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
2886             'uploader': 'milan',
2887             'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
2888         }
2889     }, {
2890         'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2891         'playlist_mincount': 982,
2892         'info_dict': {
2893             'title': '2018 Chinese New Singles (11/6 updated)',
2894             'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
2895             'uploader': 'LBK',
2896             'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
2897         }
2898     }, {
2899         'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
2900         'only_matching': True,
2901     }, {
2902         # music album playlist
2903         'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
2904         'only_matching': True,
2905     }]
2906
2907     @classmethod
2908     def suitable(cls, url):
2909         if YoutubeTabIE.suitable(url):
2910             return False
2911         # Hack for lazy extractors until more generic solution is implemented
2912         # (see #28780)
2913         from .youtube import parse_qs
2914         qs = parse_qs(url)
2915         if qs.get('v', [None])[0]:
2916             return False
2917         return super(YoutubePlaylistIE, cls).suitable(url)
2918
2919     def _real_extract(self, url):
2920         playlist_id = self._match_id(url)
2921         qs = parse_qs(url)
2922         if not qs:
2923             qs = {'list': playlist_id}
2924         return self.url_result(
2925             update_url_query('https://www.youtube.com/playlist', qs),
2926             ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2927
2928
2929 class YoutubeYtBeIE(InfoExtractor):
2930     _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}
2931     _TESTS = [{
2932         'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
2933         'info_dict': {
2934             'id': 'yeWKywCrFtk',
2935             'ext': 'mp4',
2936             'title': 'Small Scale Baler and Braiding Rugs',
2937             'uploader': 'Backus-Page House Museum',
2938             'uploader_id': 'backuspagemuseum',
2939             'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
2940             'upload_date': '20161008',
2941             'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
2942             'categories': ['Nonprofits & Activism'],
2943             'tags': list,
2944             'like_count': int,
2945             'dislike_count': int,
2946         },
2947         'params': {
2948             'noplaylist': True,
2949             'skip_download': True,
2950         },
2951     }, {
2952         'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
2953         'only_matching': True,
2954     }]
2955
2956     def _real_extract(self, url):
2957         mobj = re.match(self._VALID_URL, url)
2958         video_id = mobj.group('id')
2959         playlist_id = mobj.group('playlist_id')
2960         return self.url_result(
2961             update_url_query('https://www.youtube.com/watch', {
2962                 'v': video_id,
2963                 'list': playlist_id,
2964                 'feature': 'youtu.be',
2965             }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
2966
2967
2968 class YoutubeYtUserIE(InfoExtractor):
2969     _VALID_URL = r'ytuser:(?P<id>.+)'
2970     _TESTS = [{
2971         'url': 'ytuser:phihag',
2972         'only_matching': True,
2973     }]
2974
2975     def _real_extract(self, url):
2976         user_id = self._match_id(url)
2977         return self.url_result(
2978             'https://www.youtube.com/user/%s' % user_id,
2979             ie=YoutubeTabIE.ie_key(), video_id=user_id)
2980
2981
2982 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
2983     IE_NAME = 'youtube:favorites'
2984     IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
2985     _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
2986     _LOGIN_REQUIRED = True
2987     _TESTS = [{
2988         'url': ':ytfav',
2989         'only_matching': True,
2990     }, {
2991         'url': ':ytfavorites',
2992         'only_matching': True,
2993     }]
2994
2995     def _real_extract(self, url):
2996         return self.url_result(
2997             'https://www.youtube.com/playlist?list=LL',
2998             ie=YoutubeTabIE.ie_key())
2999
3000
3001 class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
3002     IE_DESC = 'YouTube.com searches'
3003     # there doesn't appear to be a real limit, for example if you search for
3004     # 'python' you get more than 8.000.000 results
3005     _MAX_RESULTS = float('inf')
3006     IE_NAME = 'youtube:search'
3007     _SEARCH_KEY = 'ytsearch'
3008     _SEARCH_PARAMS = None
3009     _TESTS = []
3010
3011     def _entries(self, query, n):
3012         data = {
3013             'context': {
3014                 'client': {
3015                     'clientName': 'WEB',
3016                     'clientVersion': '2.20201021.03.00',
3017                 }
3018             },
3019             'query': query,
3020         }
3021         if self._SEARCH_PARAMS:
3022             data['params'] = self._SEARCH_PARAMS
3023         total = 0
3024         for page_num in itertools.count(1):
3025             search = self._download_json(
3026                 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
3027                 video_id='query "%s"' % query,
3028                 note='Downloading page %s' % page_num,
3029                 errnote='Unable to download API page', fatal=False,
3030                 data=json.dumps(data).encode('utf8'),
3031                 headers={'content-type': 'application/json'})
3032             if not search:
3033                 break
3034             slr_contents = try_get(
3035                 search,
3036                 (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
3037                  lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
3038                 list)
3039             if not slr_contents:
3040                 break
3041             for slr_content in slr_contents:
3042                 isr_contents = try_get(
3043                     slr_content,
3044                     lambda x: x['itemSectionRenderer']['contents'],
3045                     list)
3046                 if not isr_contents:
3047                     continue
3048                 for content in isr_contents:
3049                     if not isinstance(content, dict):
3050                         continue
3051                     video = content.get('videoRenderer')
3052                     if not isinstance(video, dict):
3053                         continue
3054                     video_id = video.get('videoId')
3055                     if not video_id:
3056                         continue
3057                     yield self._extract_video(video)
3058                     total += 1
3059                     if total == n:
3060                         return
3061             token = try_get(
3062                 slr_contents,
3063                 lambda x: x[-1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
3064                 compat_str)
3065             if not token:
3066                 break
3067             data['continuation'] = token
3068
3069     def _get_n_results(self, query, n):
3070         """Get a specified number of results for a query"""
3071         return self.playlist_result(self._entries(query, n), query)
3072
3073
3074 class YoutubeSearchDateIE(YoutubeSearchIE):
3075     IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
3076     _SEARCH_KEY = 'ytsearchdate'
3077     IE_DESC = 'YouTube.com searches, newest videos first'
3078     _SEARCH_PARAMS = 'CAI%3D'
3079
3080
3081 r"""
3082 class YoutubeSearchURLIE(YoutubeSearchIE):
3083     IE_DESC = 'YouTube.com search URLs'
3084     IE_NAME = 'youtube:search_url'
3085     _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
3086     _TESTS = [{
3087         'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
3088         'playlist_mincount': 5,
3089         'info_dict': {
3090             'title': 'youtube-dl test video',
3091         }
3092     }, {
3093         'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
3094         'only_matching': True,
3095     }]
3096
3097     def _real_extract(self, url):
3098         mobj = re.match(self._VALID_URL, url)
3099         query = compat_urllib_parse_unquote_plus(mobj.group('query'))
3100         webpage = self._download_webpage(url, query)
3101         return self.playlist_result(self._process_page(webpage), playlist_title=query)
3102 """
3103
3104
3105 class YoutubeFeedsInfoExtractor(YoutubeTabIE):
3106     """
3107     Base class for feed extractors
3108     Subclasses must define the _FEED_NAME property.
3109     """
3110     _LOGIN_REQUIRED = True
3111
3112     @property
3113     def IE_NAME(self):
3114         return 'youtube:%s' % self._FEED_NAME
3115
3116     def _real_initialize(self):
3117         self._login()
3118
3119     def _real_extract(self, url):
3120         return self.url_result(
3121             'https://www.youtube.com/feed/%s' % self._FEED_NAME,
3122             ie=YoutubeTabIE.ie_key())
3123
3124
3125 class YoutubeWatchLaterIE(InfoExtractor):
3126     IE_NAME = 'youtube:watchlater'
3127     IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
3128     _VALID_URL = r':ytwatchlater'
3129     _TESTS = [{
3130         'url': ':ytwatchlater',
3131         'only_matching': True,
3132     }]
3133
3134     def _real_extract(self, url):
3135         return self.url_result(
3136             'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3137
3138
3139 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
3140     IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
3141     _VALID_URL = r':ytrec(?:ommended)?'
3142     _FEED_NAME = 'recommended'
3143     _TESTS = [{
3144         'url': ':ytrec',
3145         'only_matching': True,
3146     }, {
3147         'url': ':ytrecommended',
3148         'only_matching': True,
3149     }]
3150
3151
3152 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
3153     IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
3154     _VALID_URL = r':ytsubs(?:criptions)?'
3155     _FEED_NAME = 'subscriptions'
3156     _TESTS = [{
3157         'url': ':ytsubs',
3158         'only_matching': True,
3159     }, {
3160         'url': ':ytsubscriptions',
3161         'only_matching': True,
3162     }]
3163
3164
3165 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
3166     IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
3167     _VALID_URL = r':ythistory'
3168     _FEED_NAME = 'history'
3169     _TESTS = [{
3170         'url': ':ythistory',
3171         'only_matching': True,
3172     }]
3173
3174
3175 class YoutubeTruncatedURLIE(InfoExtractor):
3176     IE_NAME = 'youtube:truncated_url'
3177     IE_DESC = False  # Do not list
3178     _VALID_URL = r'''(?x)
3179         (?:https?://)?
3180         (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
3181         (?:watch\?(?:
3182             feature=[a-z_]+|
3183             annotation_id=annotation_[^&]+|
3184             x-yt-cl=[0-9]+|
3185             hl=[^&]*|
3186             t=[0-9]+
3187         )?
3188         |
3189             attribution_link\?a=[^&]+
3190         )
3191         $
3192     '''
3193
3194     _TESTS = [{
3195         'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
3196         'only_matching': True,
3197     }, {
3198         'url': 'https://www.youtube.com/watch?',
3199         'only_matching': True,
3200     }, {
3201         'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
3202         'only_matching': True,
3203     }, {
3204         'url': 'https://www.youtube.com/watch?feature=foo',
3205         'only_matching': True,
3206     }, {
3207         'url': 'https://www.youtube.com/watch?hl=en-GB',
3208         'only_matching': True,
3209     }, {
3210         'url': 'https://www.youtube.com/watch?t=2372',
3211         'only_matching': True,
3212     }]
3213
3214     def _real_extract(self, url):
3215         raise ExtractorError(
3216             'Did you forget to quote the URL? Remember that & is a meta '
3217             'character in most shells, so you want to put the URL in quotes, '
3218             'like  youtube-dl '
3219             '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3220             ' or simply  youtube-dl BaW_jenozKc  .',
3221             expected=True)
3222
3223
3224 class YoutubeTruncatedIDIE(InfoExtractor):
3225     IE_NAME = 'youtube:truncated_id'
3226     IE_DESC = False  # Do not list
3227     _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
3228
3229     _TESTS = [{
3230         'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
3231         'only_matching': True,
3232     }]
3233
3234     def _real_extract(self, url):
3235         video_id = self._match_id(url)
3236         raise ExtractorError(
3237             'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
3238             expected=True)