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