]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/youtube.py
[extractor/lbry] Authenticate with cookies (#5435)
[yt-dlp.git] / yt_dlp / extractor / youtube.py
CommitLineData
6e634cbe 1import base64
d92f5d5a 2import calendar
109dd3b2 3import copy
fe93e2c4 4import datetime
c26f9b99 5import enum
a5c56234 6import hashlib
0ca96d48 7import itertools
c5e8d7af 8import json
720c3099 9import math
c4417ddb 10import os.path
d77ab8e2 11import random
c5e8d7af 12import re
46383212 13import sys
f8271158 14import threading
8a784c74 15import time
e0df6211 16import traceback
14f25df2 17import urllib.error
ac668111 18import urllib.parse
c5e8d7af 19
b05654f0 20from .common import InfoExtractor, SearchInfoExtractor
25836db6 21from .openload import PhantomJSwrapper
14f25df2 22from ..compat import functools
545cc85d 23from ..jsinterp import JSInterpreter
4bb4a188 24from ..utils import (
f8271158 25 NO_DEFAULT,
26 ExtractorError,
4d37720a 27 LazyList,
693f0600 28 UserNotLive,
720c3099 29 bug_reports_message,
82d02080 30 classproperty,
c5e8d7af 31 clean_html,
d92f5d5a 32 datetime_from_str,
11f9be09 33 dict_get,
7a32c70d 34 filter_dict,
2d30521a 35 float_or_none,
11f9be09 36 format_field,
ff91cf74 37 get_first,
dd27fd17 38 int_or_none,
641ad5d8 39 is_html,
34921b43 40 join_nonempty,
48416bc4 41 js_to_json,
94278f72 42 mimetype2ext,
9c0d7f49 43 network_exceptions,
11f9be09 44 orderedSet,
6310acf5 45 parse_codecs,
49bd8c66 46 parse_count,
7c80519c 47 parse_duration,
7ea65411 48 parse_iso8601,
4dfbf869 49 parse_qs,
dca3ff4a 50 qualities,
3995d37d 51 remove_start,
cf7e015f 52 smuggle_url,
dbdaaa23 53 str_or_none,
c93d53f5 54 str_to_int,
f3aa3c3f 55 strftime_or_none,
7c365c21 56 traverse_obj,
556dbe7f 57 try_get,
c5e8d7af
PH
58 unescapeHTML,
59 unified_strdate,
f0d785d3 60 unified_timestamp,
cf7e015f 61 unsmuggle_url,
8bdd16b4 62 update_url_query,
21c340b8 63 url_or_none,
fe93e2c4 64 urljoin,
7c365c21 65 variadic,
c5e8d7af
PH
66)
67
962ffcf8 68# any clients starting with _ cannot be explicitly requested by the user
000c15a4 69INNERTUBE_CLIENTS = {
70 'web': {
71 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
72 'INNERTUBE_CONTEXT': {
73 'client': {
74 'clientName': 'WEB',
a0c830f4 75 'clientVersion': '2.20220801.00.00',
000c15a4 76 }
77 },
78 'INNERTUBE_CONTEXT_CLIENT_NAME': 1
79 },
80 'web_embedded': {
81 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
82 'INNERTUBE_CONTEXT': {
83 'client': {
84 'clientName': 'WEB_EMBEDDED_PLAYER',
a0c830f4 85 'clientVersion': '1.20220731.00.00',
000c15a4 86 },
87 },
88 'INNERTUBE_CONTEXT_CLIENT_NAME': 56
89 },
90 'web_music': {
91 'INNERTUBE_API_KEY': 'AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30',
92 'INNERTUBE_HOST': 'music.youtube.com',
93 'INNERTUBE_CONTEXT': {
94 'client': {
95 'clientName': 'WEB_REMIX',
a0c830f4 96 'clientVersion': '1.20220727.01.00',
000c15a4 97 }
98 },
99 'INNERTUBE_CONTEXT_CLIENT_NAME': 67,
100 },
e7e94f2a 101 'web_creator': {
18c7683d 102 'INNERTUBE_API_KEY': 'AIzaSyBUPetSUmoZL-OhlxA7wSac5XinrygCqMo',
e7e94f2a
D
103 'INNERTUBE_CONTEXT': {
104 'client': {
105 'clientName': 'WEB_CREATOR',
a0c830f4 106 'clientVersion': '1.20220726.00.00',
e7e94f2a
D
107 }
108 },
109 'INNERTUBE_CONTEXT_CLIENT_NAME': 62,
110 },
000c15a4 111 'android': {
18c7683d 112 'INNERTUBE_API_KEY': 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w',
000c15a4 113 'INNERTUBE_CONTEXT': {
114 'client': {
115 'clientName': 'ANDROID',
50ac0e54 116 'clientVersion': '17.31.35',
117 'androidSdkVersion': 30,
118 'userAgent': 'com.google.android.youtube/17.31.35 (Linux; U; Android 11) gzip'
000c15a4 119 }
120 },
121 'INNERTUBE_CONTEXT_CLIENT_NAME': 3,
b6de707d 122 'REQUIRE_JS_PLAYER': False
000c15a4 123 },
124 'android_embedded': {
18c7683d 125 'INNERTUBE_API_KEY': 'AIzaSyCjc_pVEDi4qsv5MtC2dMXzpIaDoRFLsxw',
000c15a4 126 'INNERTUBE_CONTEXT': {
127 'client': {
128 'clientName': 'ANDROID_EMBEDDED_PLAYER',
50ac0e54 129 'clientVersion': '17.31.35',
130 'androidSdkVersion': 30,
131 'userAgent': 'com.google.android.youtube/17.31.35 (Linux; U; Android 11) gzip'
000c15a4 132 },
133 },
b6de707d 134 'INNERTUBE_CONTEXT_CLIENT_NAME': 55,
135 'REQUIRE_JS_PLAYER': False
000c15a4 136 },
137 'android_music': {
18c7683d 138 'INNERTUBE_API_KEY': 'AIzaSyAOghZGza2MQSZkY_zfZ370N-PUdXEo8AI',
000c15a4 139 'INNERTUBE_CONTEXT': {
140 'client': {
141 'clientName': 'ANDROID_MUSIC',
a0c830f4 142 'clientVersion': '5.16.51',
50ac0e54 143 'androidSdkVersion': 30,
144 'userAgent': 'com.google.android.apps.youtube.music/5.16.51 (Linux; U; Android 11) gzip'
000c15a4 145 }
146 },
147 'INNERTUBE_CONTEXT_CLIENT_NAME': 21,
b6de707d 148 'REQUIRE_JS_PLAYER': False
000c15a4 149 },
e7e94f2a 150 'android_creator': {
18c7683d 151 'INNERTUBE_API_KEY': 'AIzaSyD_qjV8zaaUMehtLkrKFgVeSX_Iqbtyws8',
e7e94f2a
D
152 'INNERTUBE_CONTEXT': {
153 'client': {
154 'clientName': 'ANDROID_CREATOR',
50ac0e54 155 'clientVersion': '22.30.100',
156 'androidSdkVersion': 30,
157 'userAgent': 'com.google.android.apps.youtube.creator/22.30.100 (Linux; U; Android 11) gzip'
e7e94f2a
D
158 },
159 },
b6de707d 160 'INNERTUBE_CONTEXT_CLIENT_NAME': 14,
161 'REQUIRE_JS_PLAYER': False
e7e94f2a 162 },
18c7683d 163 # iOS clients have HLS live streams. Setting device model to get 60fps formats.
164 # See: https://github.com/TeamNewPipe/NewPipeExtractor/issues/680#issuecomment-1002724558
000c15a4 165 'ios': {
18c7683d 166 'INNERTUBE_API_KEY': 'AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc',
000c15a4 167 'INNERTUBE_CONTEXT': {
168 'client': {
169 'clientName': 'IOS',
224b5a35 170 'clientVersion': '17.33.2',
18c7683d 171 'deviceModel': 'iPhone14,3',
224b5a35 172 'userAgent': 'com.google.ios.youtube/17.33.2 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)'
000c15a4 173 }
174 },
b6de707d 175 'INNERTUBE_CONTEXT_CLIENT_NAME': 5,
176 'REQUIRE_JS_PLAYER': False
000c15a4 177 },
178 'ios_embedded': {
000c15a4 179 'INNERTUBE_CONTEXT': {
180 'client': {
181 'clientName': 'IOS_MESSAGES_EXTENSION',
224b5a35 182 'clientVersion': '17.33.2',
18c7683d 183 'deviceModel': 'iPhone14,3',
224b5a35 184 'userAgent': 'com.google.ios.youtube/17.33.2 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)'
000c15a4 185 },
186 },
b6de707d 187 'INNERTUBE_CONTEXT_CLIENT_NAME': 66,
188 'REQUIRE_JS_PLAYER': False
000c15a4 189 },
190 'ios_music': {
18c7683d 191 'INNERTUBE_API_KEY': 'AIzaSyBAETezhkwP0ZWA02RsqT1zu78Fpt0bC_s',
000c15a4 192 'INNERTUBE_CONTEXT': {
193 'client': {
194 'clientName': 'IOS_MUSIC',
224b5a35
SF
195 'clientVersion': '5.21',
196 'deviceModel': 'iPhone14,3',
197 'userAgent': 'com.google.ios.youtubemusic/5.21 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)'
000c15a4 198 },
199 },
b6de707d 200 'INNERTUBE_CONTEXT_CLIENT_NAME': 26,
201 'REQUIRE_JS_PLAYER': False
000c15a4 202 },
e7e94f2a
D
203 'ios_creator': {
204 'INNERTUBE_CONTEXT': {
205 'client': {
206 'clientName': 'IOS_CREATOR',
224b5a35
SF
207 'clientVersion': '22.33.101',
208 'deviceModel': 'iPhone14,3',
209 'userAgent': 'com.google.ios.ytcreator/22.33.101 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)'
e7e94f2a
D
210 },
211 },
b6de707d 212 'INNERTUBE_CONTEXT_CLIENT_NAME': 15,
213 'REQUIRE_JS_PLAYER': False
e7e94f2a 214 },
3619f78d 215 # mweb has 'ultralow' formats
216 # See: https://github.com/yt-dlp/yt-dlp/pull/557
000c15a4 217 'mweb': {
18c7683d 218 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
000c15a4 219 'INNERTUBE_CONTEXT': {
220 'client': {
221 'clientName': 'MWEB',
a0c830f4 222 'clientVersion': '2.20220801.00.00',
000c15a4 223 }
224 },
225 'INNERTUBE_CONTEXT_CLIENT_NAME': 2
e7870111
D
226 },
227 # This client can access age restricted videos (unless the uploader has disabled the 'allow embedding' option)
228 # See: https://github.com/zerodytrash/YouTube-Internal-Clients
229 'tv_embedded': {
230 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
231 'INNERTUBE_CONTEXT': {
232 'client': {
233 'clientName': 'TVHTML5_SIMPLY_EMBEDDED_PLAYER',
234 'clientVersion': '2.0',
235 },
236 },
237 'INNERTUBE_CONTEXT_CLIENT_NAME': 85
238 },
000c15a4 239}
240
241
e7870111
D
242def _split_innertube_client(client_name):
243 variant, *base = client_name.rsplit('.', 1)
244 if base:
245 return variant, base[0], variant
246 base, *variant = client_name.split('_', 1)
247 return client_name, base, variant[0] if variant else None
248
249
000c15a4 250def build_innertube_clients():
2e4cacd0 251 THIRD_PARTY = {
e7870111 252 'embedUrl': 'https://www.youtube.com/', # Can be any valid URL
65c2fde2 253 }
e7870111 254 BASE_CLIENTS = ('android', 'web', 'tv', 'ios', 'mweb')
2e4cacd0 255 priority = qualities(BASE_CLIENTS[::-1])
000c15a4 256
257 for client, ytcfg in tuple(INNERTUBE_CLIENTS.items()):
eca330cb 258 ytcfg.setdefault('INNERTUBE_API_KEY', 'AIzaSyDCU8hByM-4DrUqRUYnGn-3llEO78bcxq8')
000c15a4 259 ytcfg.setdefault('INNERTUBE_HOST', 'www.youtube.com')
b6de707d 260 ytcfg.setdefault('REQUIRE_JS_PLAYER', True)
000c15a4 261 ytcfg['INNERTUBE_CONTEXT']['client'].setdefault('hl', 'en')
000c15a4 262
e7870111 263 _, base_client, variant = _split_innertube_client(client)
2e4cacd0 264 ytcfg['priority'] = 10 * priority(base_client)
265
e48b3875 266 if not variant:
e7870111
D
267 INNERTUBE_CLIENTS[f'{client}_embedscreen'] = embedscreen = copy.deepcopy(ytcfg)
268 embedscreen['INNERTUBE_CONTEXT']['client']['clientScreen'] = 'EMBED'
269 embedscreen['INNERTUBE_CONTEXT']['thirdParty'] = THIRD_PARTY
270 embedscreen['priority'] -= 3
271 elif variant == 'embedded':
e48b3875 272 ytcfg['INNERTUBE_CONTEXT']['thirdParty'] = THIRD_PARTY
000c15a4 273 ytcfg['priority'] -= 2
e48b3875 274 else:
000c15a4 275 ytcfg['priority'] -= 3
276
277
278build_innertube_clients()
279
280
c26f9b99 281class BadgeType(enum.Enum):
282 AVAILABILITY_UNLISTED = enum.auto()
283 AVAILABILITY_PRIVATE = enum.auto()
284 AVAILABILITY_PUBLIC = enum.auto()
285 AVAILABILITY_PREMIUM = enum.auto()
286 AVAILABILITY_SUBSCRIPTION = enum.auto()
287 LIVE_NOW = enum.auto()
288
289
de7f3446 290class YoutubeBaseInfoExtractor(InfoExtractor):
b2e8bc1b 291 """Provide base functions for Youtube extractors"""
e00eb564 292
3462ffa8 293 _RESERVED_NAMES = (
3cd786db 294 r'channel|c|user|playlist|watch|w|v|embed|e|watch_popup|clip|'
182bda88 295 r'shorts|movies|results|search|shared|hashtag|trending|explore|feed|feeds|'
1dd18a88 296 r'browse|oembed|get_video_info|iframe_api|s/player|source|'
0a5095fe 297 r'storefront|oops|index|account|t/terms|about|upload|signin|logout')
3462ffa8 298
3619f78d 299 _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
300
52efa4b3 301 # _NETRC_MACHINE = 'youtube'
3619f78d 302
b2e8bc1b
JMF
303 # If True it will raise an error if no login info is provided
304 _LOGIN_REQUIRED = False
305
d9190e44
RH
306 _INVIDIOUS_SITES = (
307 # invidious-redirect websites
308 r'(?:www\.)?redirect\.invidious\.io',
309 r'(?:(?:www|dev)\.)?invidio\.us',
0a41f331 310 # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/docs/instances.md
d9190e44
RH
311 r'(?:www\.)?invidious\.pussthecat\.org',
312 r'(?:www\.)?invidious\.zee\.li',
313 r'(?:www\.)?invidious\.ethibox\.fr',
314 r'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
4c968755
U
315 r'(?:www\.)?osbivz6guyeahrwp2lnwyjk2xos342h4ocsxyqrlaopqjuhwn2djiiyd\.onion',
316 r'(?:www\.)?u2cvlit75owumwpy4dj2hsmvkq7nvrclkpht7xgyye2pyoxhpmclkrad\.onion',
d9190e44
RH
317 # youtube-dl invidious instances list
318 r'(?:(?:www|no)\.)?invidiou\.sh',
319 r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
320 r'(?:www\.)?invidious\.kabi\.tk',
321 r'(?:www\.)?invidious\.mastodon\.host',
322 r'(?:www\.)?invidious\.zapashcanon\.fr',
323 r'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
324 r'(?:www\.)?invidious\.tinfoil-hat\.net',
325 r'(?:www\.)?invidious\.himiko\.cloud',
326 r'(?:www\.)?invidious\.reallyancient\.tech',
327 r'(?:www\.)?invidious\.tube',
328 r'(?:www\.)?invidiou\.site',
329 r'(?:www\.)?invidious\.site',
330 r'(?:www\.)?invidious\.xyz',
331 r'(?:www\.)?invidious\.nixnet\.xyz',
332 r'(?:www\.)?invidious\.048596\.xyz',
333 r'(?:www\.)?invidious\.drycat\.fr',
334 r'(?:www\.)?inv\.skyn3t\.in',
335 r'(?:www\.)?tube\.poal\.co',
336 r'(?:www\.)?tube\.connect\.cafe',
337 r'(?:www\.)?vid\.wxzm\.sx',
338 r'(?:www\.)?vid\.mint\.lgbt',
339 r'(?:www\.)?vid\.puffyan\.us',
340 r'(?:www\.)?yewtu\.be',
341 r'(?:www\.)?yt\.elukerio\.org',
342 r'(?:www\.)?yt\.lelux\.fi',
343 r'(?:www\.)?invidious\.ggc-project\.de',
344 r'(?:www\.)?yt\.maisputain\.ovh',
345 r'(?:www\.)?ytprivate\.com',
346 r'(?:www\.)?invidious\.13ad\.de',
347 r'(?:www\.)?invidious\.toot\.koeln',
348 r'(?:www\.)?invidious\.fdn\.fr',
349 r'(?:www\.)?watch\.nettohikari\.com',
350 r'(?:www\.)?invidious\.namazso\.eu',
351 r'(?:www\.)?invidious\.silkky\.cloud',
352 r'(?:www\.)?invidious\.exonip\.de',
353 r'(?:www\.)?invidious\.riverside\.rocks',
354 r'(?:www\.)?invidious\.blamefran\.net',
355 r'(?:www\.)?invidious\.moomoo\.de',
356 r'(?:www\.)?ytb\.trom\.tf',
357 r'(?:www\.)?yt\.cyberhost\.uk',
358 r'(?:www\.)?kgg2m7yk5aybusll\.onion',
359 r'(?:www\.)?qklhadlycap4cnod\.onion',
360 r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
361 r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
362 r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
363 r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
364 r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
365 r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
366 r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
367 r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
368 r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
369 r'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
d1c4f6d4
JW
370 # piped instances from https://github.com/TeamPiped/Piped/wiki/Instances
371 r'(?:www\.)?piped\.kavin\.rocks',
372 r'(?:www\.)?piped\.silkky\.cloud',
373 r'(?:www\.)?piped\.tokhmi\.xyz',
374 r'(?:www\.)?piped\.moomoo\.me',
375 r'(?:www\.)?il\.ax',
376 r'(?:www\.)?piped\.syncpundit\.com',
377 r'(?:www\.)?piped\.mha\.fi',
378 r'(?:www\.)?piped\.mint\.lgbt',
379 r'(?:www\.)?piped\.privacy\.com\.de',
d9190e44
RH
380 )
381
c26f9b99 382 # extracted from account/account_menu ep
383 # XXX: These are the supported YouTube UI and API languages,
384 # which is slightly different from languages supported for translation in YouTube studio
385 _SUPPORTED_LANG_CODES = [
386 'af', 'az', 'id', 'ms', 'bs', 'ca', 'cs', 'da', 'de', 'et', 'en-IN', 'en-GB', 'en', 'es',
387 'es-419', 'es-US', 'eu', 'fil', 'fr', 'fr-CA', 'gl', 'hr', 'zu', 'is', 'it', 'sw', 'lv',
388 'lt', 'hu', 'nl', 'no', 'uz', 'pl', 'pt-PT', 'pt', 'ro', 'sq', 'sk', 'sl', 'sr-Latn', 'fi',
389 'sv', 'vi', 'tr', 'be', 'bg', 'ky', 'kk', 'mk', 'mn', 'ru', 'sr', 'uk', 'el', 'hy', 'iw',
390 'ur', 'ar', 'fa', 'ne', 'mr', 'hi', 'as', 'bn', 'pa', 'gu', 'or', 'ta', 'te', 'kn', 'ml',
391 'si', 'th', 'lo', 'my', 'ka', 'am', 'km', 'zh-CN', 'zh-TW', 'zh-HK', 'ja', 'ko'
392 ]
393
a057779d 394 _IGNORED_WARNINGS = {'Unavailable videos will be hidden during playback'}
395
c26f9b99 396 @functools.cached_property
397 def _preferred_lang(self):
398 """
399 Returns a language code supported by YouTube for the user preferred language.
400 Returns None if no preferred language set.
401 """
402 preferred_lang = self._configuration_arg('lang', ie_key='Youtube', casesense=True, default=[''])[0]
403 if not preferred_lang:
404 return
405 if preferred_lang not in self._SUPPORTED_LANG_CODES:
406 raise ExtractorError(
407 f'Unsupported language code: {preferred_lang}. Supported language codes (case-sensitive): {join_nonempty(*self._SUPPORTED_LANG_CODES, delim=", ")}.',
408 expected=True)
409 elif preferred_lang != 'en':
410 self.report_warning(
411 f'Preferring "{preferred_lang}" translated fields. Note that some metadata extraction may fail or be incorrect.')
412 return preferred_lang
413
cce889b9 414 def _initialize_consent(self):
415 cookies = self._get_cookies('https://www.youtube.com/')
416 if cookies.get('__Secure-3PSID'):
417 return
418 consent_id = None
419 consent = cookies.get('CONSENT')
420 if consent:
421 if 'YES' in consent.value:
422 return
423 consent_id = self._search_regex(
424 r'PENDING\+(\d+)', consent.value, 'consent', default=None)
425 if not consent_id:
426 consent_id = random.randint(100, 999)
427 self._set_cookie('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id)
8d81f3e3 428
f3aa3c3f 429 def _initialize_pref(self):
430 cookies = self._get_cookies('https://www.youtube.com/')
431 pref_cookie = cookies.get('PREF')
432 pref = {}
433 if pref_cookie:
434 try:
14f25df2 435 pref = dict(urllib.parse.parse_qsl(pref_cookie.value))
f3aa3c3f 436 except ValueError:
437 self.report_warning('Failed to parse user PREF cookie' + bug_reports_message())
c26f9b99 438 pref.update({'hl': self._preferred_lang or 'en', 'tz': 'UTC'})
14f25df2 439 self._set_cookie('.youtube.com', name='PREF', value=urllib.parse.urlencode(pref))
f3aa3c3f 440
b2e8bc1b 441 def _real_initialize(self):
f3aa3c3f 442 self._initialize_pref()
cce889b9 443 self._initialize_consent()
a25bca9f 444 self._check_login_required()
445
446 def _check_login_required(self):
24146491 447 if self._LOGIN_REQUIRED and not self._cookies_passed:
52efa4b3 448 self.raise_login_required('Login details are needed to download this content', method='cookies')
c5e8d7af 449
b7c47b74 450 _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*='
451 _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*='
a0566bbf 452
000c15a4 453 def _get_default_ytcfg(self, client='web'):
454 return copy.deepcopy(INNERTUBE_CLIENTS[client])
109dd3b2 455
000c15a4 456 def _get_innertube_host(self, client='web'):
457 return INNERTUBE_CLIENTS[client]['INNERTUBE_HOST']
109dd3b2 458
000c15a4 459 def _ytcfg_get_safe(self, ytcfg, getter, expected_type=None, default_client='web'):
109dd3b2 460 # try_get but with fallback to default ytcfg client values when present
461 _func = lambda y: try_get(y, getter, expected_type)
462 return _func(ytcfg) or _func(self._get_default_ytcfg(default_client))
463
000c15a4 464 def _extract_client_name(self, ytcfg, default_client='web'):
3619f78d 465 return self._ytcfg_get_safe(
466 ytcfg, (lambda x: x['INNERTUBE_CLIENT_NAME'],
14f25df2 467 lambda x: x['INNERTUBE_CONTEXT']['client']['clientName']), str, default_client)
109dd3b2 468
000c15a4 469 def _extract_client_version(self, ytcfg, default_client='web'):
3619f78d 470 return self._ytcfg_get_safe(
471 ytcfg, (lambda x: x['INNERTUBE_CLIENT_VERSION'],
14f25df2 472 lambda x: x['INNERTUBE_CONTEXT']['client']['clientVersion']), str, default_client)
109dd3b2 473
2ae778b8 474 def _select_api_hostname(self, req_api_hostname, default_client=None):
475 return (self._configuration_arg('innertube_host', [''], ie_key=YoutubeIE.ie_key())[0]
476 or req_api_hostname or self._get_innertube_host(default_client or 'web'))
477
000c15a4 478 def _extract_api_key(self, ytcfg=None, default_client='web'):
14f25df2 479 return self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_API_KEY'], str, default_client)
109dd3b2 480
000c15a4 481 def _extract_context(self, ytcfg=None, default_client='web'):
f3aa3c3f 482 context = get_first(
483 (ytcfg, self._get_default_ytcfg(default_client)), 'INNERTUBE_CONTEXT', expected_type=dict)
396a76f7 484 # Enforce language and tz for extraction
485 client_context = traverse_obj(context, 'client', expected_type=dict, default={})
c26f9b99 486 client_context.update({'hl': self._preferred_lang or 'en', 'timeZone': 'UTC', 'utcOffsetMinutes': 0})
109dd3b2 487 return context
488
cf87314d 489 _SAPISID = None
490
109dd3b2 491 def _generate_sapisidhash_header(self, origin='https://www.youtube.com'):
a5c56234 492 time_now = round(time.time())
cf87314d 493 if self._SAPISID is None:
494 yt_cookies = self._get_cookies('https://www.youtube.com')
495 # Sometimes SAPISID cookie isn't present but __Secure-3PAPISID is.
496 # See: https://github.com/yt-dlp/yt-dlp/issues/393
497 sapisid_cookie = dict_get(
498 yt_cookies, ('__Secure-3PAPISID', 'SAPISID'))
499 if sapisid_cookie and sapisid_cookie.value:
500 self._SAPISID = sapisid_cookie.value
501 self.write_debug('Extracted SAPISID cookie')
502 # SAPISID cookie is required if not already present
503 if not yt_cookies.get('SAPISID'):
504 self.write_debug('Copying __Secure-3PAPISID cookie to SAPISID cookie')
505 self._set_cookie(
506 '.youtube.com', 'SAPISID', self._SAPISID, secure=True, expire_time=time_now + 3600)
507 else:
508 self._SAPISID = False
509 if not self._SAPISID:
510 return None
1974e99f 511 # SAPISIDHASH algorithm from https://stackoverflow.com/a/32065323
512 sapisidhash = hashlib.sha1(
86e5f3ed 513 f'{time_now} {self._SAPISID} {origin}'.encode()).hexdigest()
1974e99f 514 return f'SAPISIDHASH {time_now}_{sapisidhash}'
a5c56234
M
515
516 def _call_api(self, ep, query, video_id, fatal=True, headers=None,
f4f751af 517 note='Downloading API JSON', errnote='Unable to download API page',
000c15a4 518 context=None, api_key=None, api_hostname=None, default_client='web'):
f4f751af 519
109dd3b2 520 data = {'context': context} if context else {'context': self._extract_context(default_client=default_client)}
8bdd16b4 521 data.update(query)
11f9be09 522 real_headers = self.generate_api_headers(default_client=default_client)
f4f751af 523 real_headers.update({'content-type': 'application/json'})
524 if headers:
525 real_headers.update(headers)
2ae778b8 526 api_key = (self._configuration_arg('innertube_key', [''], ie_key=YoutubeIE.ie_key(), casesense=True)[0]
527 or api_key or self._extract_api_key(default_client=default_client))
545cc85d 528 return self._download_json(
2ae778b8 529 f'https://{self._select_api_hostname(api_hostname, default_client)}/youtubei/v1/{ep}',
a5c56234 530 video_id=video_id, fatal=fatal, note=note, errnote=errnote,
f4f751af 531 data=json.dumps(data).encode('utf8'), headers=real_headers,
2ae778b8 532 query={'key': api_key, 'prettyPrint': 'false'})
f4f751af 533
65141660 534 def extract_yt_initial_data(self, item_id, webpage, fatal=True):
535 return self._search_json(self._YT_INITIAL_DATA_RE, webpage, 'yt initial data', item_id, fatal=fatal)
1890fc63 536
99e9e001 537 @staticmethod
538 def _extract_session_index(*data):
539 """
540 Index of current account in account list.
541 See: https://github.com/yt-dlp/yt-dlp/pull/519
542 """
543 for ytcfg in data:
544 session_index = int_or_none(try_get(ytcfg, lambda x: x['SESSION_INDEX']))
545 if session_index is not None:
546 return session_index
547
548 # Deprecated?
549 def _extract_identity_token(self, ytcfg=None, webpage=None):
a1c5d2ca 550 if ytcfg:
14f25df2 551 token = try_get(ytcfg, lambda x: x['ID_TOKEN'], str)
a1c5d2ca
M
552 if token:
553 return token
99e9e001 554 if webpage:
555 return self._search_regex(
556 r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
557 'identity token', default=None, fatal=False)
a1c5d2ca
M
558
559 @staticmethod
fe93e2c4 560 def _extract_account_syncid(*args):
8ea3f7b9 561 """
562 Extract syncId required to download private playlists of secondary channels
fe93e2c4 563 @params response and/or ytcfg
8ea3f7b9 564 """
fe93e2c4 565 for data in args:
566 # ytcfg includes channel_syncid if on secondary channel
14f25df2 567 delegated_sid = try_get(data, lambda x: x['DELEGATED_SESSION_ID'], str)
fe93e2c4 568 if delegated_sid:
569 return delegated_sid
570 sync_ids = (try_get(
571 data, (lambda x: x['responseContext']['mainAppWebResponseContext']['datasyncId'],
14f25df2 572 lambda x: x['DATASYNC_ID']), str) or '').split('||')
fe93e2c4 573 if len(sync_ids) >= 2 and sync_ids[1]:
574 # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
575 # and just "user_syncid||" for primary channel. We only want the channel_syncid
576 return sync_ids[0]
a1c5d2ca 577
ac56cf38 578 @staticmethod
579 def _extract_visitor_data(*args):
580 """
581 Extracts visitorData from an API response or ytcfg
582 Appears to be used to track session state
583 """
9222c381 584 return get_first(
6c73052c 585 args, [('VISITOR_DATA', ('INNERTUBE_CONTEXT', 'client', 'visitorData'), ('responseContext', 'visitorData'))],
9222c381 586 expected_type=str)
ac56cf38 587
2762dbb1 588 @functools.cached_property
99e9e001 589 def is_authenticated(self):
590 return bool(self._generate_sapisidhash_header())
591
11f9be09 592 def extract_ytcfg(self, video_id, webpage):
8c54a305 593 if not webpage:
594 return {}
29f7c58a 595 return self._parse_json(
596 self._search_regex(
597 r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
f4f751af 598 default='{}'), video_id, fatal=False) or {}
599
11f9be09 600 def generate_api_headers(
99e9e001 601 self, *, ytcfg=None, account_syncid=None, session_index=None,
602 visitor_data=None, identity_token=None, api_hostname=None, default_client='web'):
603
2ae778b8 604 origin = 'https://' + (self._select_api_hostname(api_hostname, default_client))
f4f751af 605 headers = {
14f25df2 606 'X-YouTube-Client-Name': str(
11f9be09 607 self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT_CLIENT_NAME'], default_client=default_client)),
608 'X-YouTube-Client-Version': self._extract_client_version(ytcfg, default_client),
99e9e001 609 'Origin': origin,
610 'X-Youtube-Identity-Token': identity_token or self._extract_identity_token(ytcfg),
611 'X-Goog-PageId': account_syncid or self._extract_account_syncid(ytcfg),
50ac0e54 612 'X-Goog-Visitor-Id': visitor_data or self._extract_visitor_data(ytcfg),
613 'User-Agent': self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT']['client']['userAgent'], default_client=default_client)
99e9e001 614 }
615 if session_index is None:
314ee305 616 session_index = self._extract_session_index(ytcfg)
617 if account_syncid or session_index is not None:
618 headers['X-Goog-AuthUser'] = session_index if session_index is not None else 0
99e9e001 619
109dd3b2 620 auth = self._generate_sapisidhash_header(origin)
f4f751af 621 if auth is not None:
622 headers['Authorization'] = auth
109dd3b2 623 headers['X-Origin'] = origin
7a32c70d 624 return filter_dict(headers)
29f7c58a 625
a25bca9f 626 def _download_ytcfg(self, client, video_id):
627 url = {
628 'web': 'https://www.youtube.com',
629 'web_music': 'https://music.youtube.com',
630 'web_embedded': f'https://www.youtube.com/embed/{video_id}?html5=1'
631 }.get(client)
632 if not url:
633 return {}
634 webpage = self._download_webpage(
635 url, video_id, fatal=False, note=f'Downloading {client.replace("_", " ").strip()} client config')
636 return self.extract_ytcfg(video_id, webpage) or {}
637
2d6659b9 638 @staticmethod
639 def _build_api_continuation_query(continuation, ctp=None):
640 query = {
641 'continuation': continuation
642 }
643 # TODO: Inconsistency with clickTrackingParams.
644 # Currently we have a fixed ctp contained within context (from ytcfg)
645 # and a ctp in root query for continuation.
646 if ctp:
647 query['clickTracking'] = {'clickTrackingParams': ctp}
648 return query
649
2d6659b9 650 @classmethod
651 def _extract_next_continuation_data(cls, renderer):
652 next_continuation = try_get(
653 renderer, (lambda x: x['continuations'][0]['nextContinuationData'],
654 lambda x: x['continuation']['reloadContinuationData']), dict)
655 if not next_continuation:
656 return
657 continuation = next_continuation.get('continuation')
658 if not continuation:
659 return
660 ctp = next_continuation.get('clickTrackingParams')
fe93e2c4 661 return cls._build_api_continuation_query(continuation, ctp)
2d6659b9 662
663 @classmethod
664 def _extract_continuation_ep_data(cls, continuation_ep: dict):
665 if isinstance(continuation_ep, dict):
666 continuation = try_get(
14f25df2 667 continuation_ep, lambda x: x['continuationCommand']['token'], str)
2d6659b9 668 if not continuation:
669 return
670 ctp = continuation_ep.get('clickTrackingParams')
fe93e2c4 671 return cls._build_api_continuation_query(continuation, ctp)
2d6659b9 672
673 @classmethod
674 def _extract_continuation(cls, renderer):
675 next_continuation = cls._extract_next_continuation_data(renderer)
676 if next_continuation:
677 return next_continuation
fe93e2c4 678
7a32c70d 679 return traverse_obj(renderer, (
680 ('contents', 'items', 'rows'), ..., 'continuationItemRenderer',
681 ('continuationEndpoint', ('button', 'buttonRenderer', 'command'))
682 ), get_all=False, expected_type=cls._extract_continuation_ep_data)
2d6659b9 683
fe93e2c4 684 @classmethod
685 def _extract_alerts(cls, data):
109dd3b2 686 for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
687 if not isinstance(alert_dict, dict):
688 continue
689 for alert in alert_dict.values():
690 alert_type = alert.get('type')
691 if not alert_type:
692 continue
052e1350 693 message = cls._get_text(alert, 'text')
109dd3b2 694 if message:
695 yield alert_type, message
696
c0ac49bc 697 def _report_alerts(self, alerts, expected=True, fatal=True, only_once=False):
a057779d 698 errors, warnings = [], []
109dd3b2 699 for alert_type, alert_message in alerts:
641ad5d8 700 if alert_type.lower() == 'error' and fatal:
109dd3b2 701 errors.append([alert_type, alert_message])
a057779d 702 elif alert_message not in self._IGNORED_WARNINGS:
109dd3b2 703 warnings.append([alert_type, alert_message])
704
705 for alert_type, alert_message in (warnings + errors[:-1]):
86e5f3ed 706 self.report_warning(f'YouTube said: {alert_type} - {alert_message}', only_once=only_once)
109dd3b2 707 if errors:
708 raise ExtractorError('YouTube said: %s' % errors[-1][1], expected=expected)
709
710 def _extract_and_report_alerts(self, data, *args, **kwargs):
711 return self._report_alerts(self._extract_alerts(data), *args, **kwargs)
712
47193e02 713 def _extract_badges(self, renderer: dict):
c26f9b99 714 privacy_icon_map = {
715 'PRIVACY_UNLISTED': BadgeType.AVAILABILITY_UNLISTED,
716 'PRIVACY_PRIVATE': BadgeType.AVAILABILITY_PRIVATE,
717 'PRIVACY_PUBLIC': BadgeType.AVAILABILITY_PUBLIC
718 }
719
720 badge_style_map = {
721 'BADGE_STYLE_TYPE_MEMBERS_ONLY': BadgeType.AVAILABILITY_SUBSCRIPTION,
722 'BADGE_STYLE_TYPE_PREMIUM': BadgeType.AVAILABILITY_PREMIUM,
723 'BADGE_STYLE_TYPE_LIVE_NOW': BadgeType.LIVE_NOW
724 }
725
726 label_map = {
727 'unlisted': BadgeType.AVAILABILITY_UNLISTED,
728 'private': BadgeType.AVAILABILITY_PRIVATE,
729 'members only': BadgeType.AVAILABILITY_SUBSCRIPTION,
730 'live': BadgeType.LIVE_NOW,
731 'premium': BadgeType.AVAILABILITY_PREMIUM
732 }
733
734 badges = []
735 for badge in traverse_obj(renderer, ('badges', ..., 'metadataBadgeRenderer'), default=[]):
736 badge_type = (
737 privacy_icon_map.get(traverse_obj(badge, ('icon', 'iconType'), expected_type=str))
738 or badge_style_map.get(traverse_obj(badge, 'style'))
739 )
740 if badge_type:
741 badges.append({'type': badge_type})
742 continue
743
744 # fallback, won't work in some languages
745 label = traverse_obj(badge, 'label', expected_type=str, default='')
746 for match, label_badge_type in label_map.items():
747 if match in label.lower():
748 badges.append({'type': badge_type})
749 continue
750
47193e02 751 return badges
752
c26f9b99 753 @staticmethod
754 def _has_badge(badges, badge_type):
755 return bool(traverse_obj(badges, lambda _, v: v['type'] == badge_type))
756
47193e02 757 @staticmethod
052e1350 758 def _get_text(data, *path_list, max_runs=None):
759 for path in path_list or [None]:
760 if path is None:
761 obj = [data]
762 else:
763 obj = traverse_obj(data, path, default=[])
764 if not any(key is ... or isinstance(key, (list, tuple)) for key in variadic(path)):
765 obj = [obj]
766 for item in obj:
14f25df2 767 text = try_get(item, lambda x: x['simpleText'], str)
052e1350 768 if text:
769 return text
770 runs = try_get(item, lambda x: x['runs'], list) or []
771 if not runs and isinstance(item, list):
772 runs = item
773
774 runs = runs[:min(len(runs), max_runs or len(runs))]
775 text = ''.join(traverse_obj(runs, (..., 'text'), expected_type=str, default=[]))
776 if text:
777 return text
47193e02 778
f0d785d3 779 def _get_count(self, data, *path_list):
780 count_text = self._get_text(data, *path_list) or ''
781 count = parse_count(count_text)
782 if count is None:
783 count = str_to_int(
784 self._search_regex(r'^([\d,]+)', re.sub(r'\s', '', count_text), 'count', default=None))
785 return count
786
a709d873 787 @staticmethod
788 def _extract_thumbnails(data, *path_list):
789 """
790 Extract thumbnails from thumbnails dict
791 @param path_list: path list to level that contains 'thumbnails' key
792 """
793 thumbnails = []
794 for path in path_list or [()]:
795 for thumbnail in traverse_obj(data, (*variadic(path), 'thumbnails', ...), default=[]):
796 thumbnail_url = url_or_none(thumbnail.get('url'))
797 if not thumbnail_url:
798 continue
799 # Sometimes youtube gives a wrong thumbnail URL. See:
800 # https://github.com/yt-dlp/yt-dlp/issues/233
801 # https://github.com/ytdl-org/youtube-dl/issues/28023
802 if 'maxresdefault' in thumbnail_url:
803 thumbnail_url = thumbnail_url.split('?')[0]
804 thumbnails.append({
805 'url': thumbnail_url,
806 'height': int_or_none(thumbnail.get('height')),
807 'width': int_or_none(thumbnail.get('width')),
808 })
809 return thumbnails
810
f3aa3c3f 811 @staticmethod
812 def extract_relative_time(relative_time_text):
813 """
814 Extracts a relative time from string and converts to dt object
f0d785d3 815 e.g. 'streamed 6 days ago', '5 seconds ago (edited)', 'updated today'
f3aa3c3f 816 """
f0d785d3 817 mobj = re.search(r'(?P<start>today|yesterday|now)|(?P<time>\d+)\s*(?P<unit>microsecond|second|minute|hour|day|week|month|year)s?\s*ago', relative_time_text)
f3aa3c3f 818 if mobj:
f0d785d3 819 start = mobj.group('start')
820 if start:
821 return datetime_from_str(start)
f3aa3c3f 822 try:
f0d785d3 823 return datetime_from_str('now-%s%s' % (mobj.group('time'), mobj.group('unit')))
f3aa3c3f 824 except ValueError:
825 return None
826
c26f9b99 827 def _parse_time_text(self, text):
828 if not text:
829 return
f3aa3c3f 830 dt = self.extract_relative_time(text)
831 timestamp = None
832 if isinstance(dt, datetime.datetime):
833 timestamp = calendar.timegm(dt.timetuple())
f0d785d3 834
835 if timestamp is None:
836 timestamp = (
837 unified_timestamp(text) or unified_timestamp(
838 self._search_regex(
17322130 839 (r'([a-z]+\s*\d{1,2},?\s*20\d{2})', r'(?:.+|^)(?:live|premieres|ed|ing)(?:\s*(?:on|for))?\s*(.+\d)'),
396a76f7 840 text.lower(), 'time text', default=None)))
f0d785d3 841
c26f9b99 842 if text and timestamp is None and self._preferred_lang in (None, 'en'):
843 self.report_warning(
844 f'Cannot parse localized time text "{text}"', only_once=True)
845 return timestamp
f3aa3c3f 846
109dd3b2 847 def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
848 ytcfg=None, check_get_keys=None, ep='browse', fatal=True, api_hostname=None,
000c15a4 849 default_client='web'):
be5c1ae8 850 for retry in self.RetryManager():
109dd3b2 851 try:
852 response = self._call_api(
853 ep=ep, fatal=True, headers=headers,
be5c1ae8 854 video_id=item_id, query=query, note=note,
109dd3b2 855 context=self._extract_context(ytcfg, default_client),
856 api_key=self._extract_api_key(ytcfg, default_client),
be5c1ae8 857 api_hostname=api_hostname, default_client=default_client)
109dd3b2 858 except ExtractorError as e:
be5c1ae8 859 if not isinstance(e.cause, network_exceptions):
860 return self._error_or_warning(e, fatal=fatal)
861 elif not isinstance(e.cause, urllib.error.HTTPError):
862 retry.error = e
863 continue
109dd3b2 864
be5c1ae8 865 first_bytes = e.cause.read(512)
866 if not is_html(first_bytes):
867 yt_error = try_get(
868 self._parse_json(
869 self._webpage_read_content(e.cause, None, item_id, prefix=first_bytes) or '{}', item_id, fatal=False),
870 lambda x: x['error']['message'], str)
871 if yt_error:
872 self._report_alerts([('ERROR', yt_error)], fatal=False)
873 # Downloading page may result in intermittent 5xx HTTP error
874 # Sometimes a 404 is also recieved. See: https://github.com/ytdl-org/youtube-dl/issues/28289
875 # We also want to catch all other network exceptions since errors in later pages can be troublesome
876 # See https://github.com/yt-dlp/yt-dlp/issues/507#issuecomment-880188210
877 if e.cause.code not in (403, 429):
878 retry.error = e
879 continue
880 return self._error_or_warning(e, fatal=fatal)
881
882 try:
883 self._extract_and_report_alerts(response, only_once=True)
884 except ExtractorError as e:
885 # YouTube servers may return errors we want to retry on in a 200 OK response
886 # See: https://github.com/yt-dlp/yt-dlp/issues/839
887 if 'unknown error' in e.msg.lower():
888 retry.error = e
889 continue
890 return self._error_or_warning(e, fatal=fatal)
891 # Youtube sometimes sends incomplete data
892 # See: https://github.com/ytdl-org/youtube-dl/issues/28194
893 if not traverse_obj(response, *variadic(check_get_keys)):
3ce29336 894 retry.error = ExtractorError('Incomplete data received', expected=True)
be5c1ae8 895 continue
896
897 return response
109dd3b2 898
9297939e 899 @staticmethod
900 def is_music_url(url):
901 return re.match(r'https?://music\.youtube\.com/', url) is not None
902
30a074c2 903 def _extract_video(self, renderer):
904 video_id = renderer.get('videoId')
052e1350 905 title = self._get_text(renderer, 'title')
906 description = self._get_text(renderer, 'descriptionSnippet')
a353beba 907 duration = parse_duration(self._get_text(
908 renderer, 'lengthText', ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'text')))
1c1b2f96 909 if duration is None:
910 duration = parse_duration(self._search_regex(
911 r'(?i)(ago)(?!.*\1)\s+(?P<duration>[a-z0-9 ,]+?)(?:\s+[\d,]+\s+views)?(?:\s+-\s+play\s+short)?$',
912 traverse_obj(renderer, ('title', 'accessibility', 'accessibilityData', 'label'), default='', expected_type=str),
913 video_id, default=None, group='duration'))
914
867c66ff 915 view_count = self._get_count(renderer, 'viewCountText', 'shortViewCountText')
052e1350 916 uploader = self._get_text(renderer, 'ownerText', 'shortBylineText')
f3aa3c3f 917 channel_id = traverse_obj(
a44ca5a4 918 renderer, ('shortBylineText', 'runs', ..., 'navigationEndpoint', 'browseEndpoint', 'browseId'),
919 expected_type=str, get_all=False)
c26f9b99 920 time_text = self._get_text(renderer, 'publishedTimeText') or ''
f3aa3c3f 921 scheduled_timestamp = str_to_int(traverse_obj(renderer, ('upcomingEventData', 'startTime'), get_all=False))
922 overlay_style = traverse_obj(
a44ca5a4 923 renderer, ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'style'),
924 get_all=False, expected_type=str)
f3aa3c3f 925 badges = self._extract_badges(renderer)
a709d873 926 thumbnails = self._extract_thumbnails(renderer, 'thumbnail')
fd2ad7cb 927 navigation_url = urljoin('https://www.youtube.com/', traverse_obj(
a44ca5a4 928 renderer, ('navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url'),
929 expected_type=str)) or ''
fd2ad7cb 930 url = f'https://www.youtube.com/watch?v={video_id}'
a44ca5a4 931 if overlay_style == 'SHORTS' or '/shorts/' in navigation_url:
fd2ad7cb 932 url = f'https://www.youtube.com/shorts/{video_id}'
a709d873 933
867c66ff
M
934 live_status = (
935 'is_upcoming' if scheduled_timestamp is not None
936 else 'was_live' if 'streamed' in time_text.lower()
937 else 'is_live' if overlay_style == 'LIVE' or self._has_badge(badges, BadgeType.LIVE_NOW)
938 else None)
939
30a074c2 940 return {
39ed931e 941 '_type': 'url',
30a074c2 942 'ie_key': YoutubeIE.ie_key(),
943 'id': video_id,
fd2ad7cb 944 'url': url,
30a074c2 945 'title': title,
946 'description': description,
947 'duration': duration,
30a074c2 948 'uploader': uploader,
f3aa3c3f 949 'channel_id': channel_id,
a709d873 950 'thumbnails': thumbnails,
5225df50 951 'timestamp': (self._parse_time_text(time_text)
952 if self._configuration_arg('approximate_date', ie_key=YoutubeTabIE)
953 else None),
f3aa3c3f 954 'release_timestamp': scheduled_timestamp,
c26f9b99 955 'availability':
956 'public' if self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
957 else self._availability(
958 is_private=self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE) or None,
959 needs_premium=self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or None,
960 needs_subscription=self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION) or None,
867c66ff
M
961 is_unlisted=self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED) or None),
962 'concurrent_view_count' if live_status in ('is_live', 'is_upcoming') else 'view_count': view_count,
e63faa10 963 'live_status': live_status
30a074c2 964 }
965
0c148415 966
360e1ca5 967class YoutubeIE(YoutubeBaseInfoExtractor):
96565c7e 968 IE_DESC = 'YouTube'
cb7dfeea 969 _VALID_URL = r"""(?x)^
c5e8d7af 970 (
edb53e2d 971 (?:https?://|//) # http(s):// or protocol-independent URL
bc2ca1bb 972 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
973 (?:www\.)?deturl\.com/www\.youtube\.com|
974 (?:www\.)?pwnyoutube\.com|
975 (?:www\.)?hooktube\.com|
976 (?:www\.)?yourepeat\.com|
977 tube\.majestyc\.net|
978 %(invidious)s|
979 youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
c5e8d7af
PH
980 (?:.*?\#/)? # handle anchor (#/) redirect urls
981 (?: # the various things that can precede the ID:
b6ce9bb0 982 (?:(?:v|embed|e|shorts)/(?!videoseries|live_stream)) # v/ or embed/ or e/ or shorts/
c5e8d7af 983 |(?: # or the v= param in all its forms
f7000f3a 984 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
c5e8d7af 985 (?:\?|\#!?) # the params delimiter ? or # or #!
040ac686 986 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
c5e8d7af
PH
987 v=
988 )
f4b05232 989 ))
cbaed4bb
S
990 |(?:
991 youtu\.be| # just youtu.be/xxxx
6d4fc66b
S
992 vid\.plus| # or vid.plus/xxxx
993 zwearz\.com/watch| # or zwearz.com/watch/xxxx
bc2ca1bb 994 %(invidious)s
cbaed4bb 995 )/
edb53e2d 996 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
f4b05232 997 )
c5e8d7af 998 )? # all until now is optional -> you can pass the naked ID
201c1459 999 (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
c5e8d7af 1000 (?(1).+)? # if we found the ID, everything can follow
9297939e 1001 (?:\#|$)""" % {
d9190e44 1002 'invidious': '|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
bc2ca1bb 1003 }
7c6eb424 1004 _EMBED_REGEX = [
1005 r'''(?x)
1006 (?:
0ca0f881 1007 <(?:[0-9A-Za-z-]+?)?iframe[^>]+?src=|
7c6eb424 1008 data-video-url=|
1009 <embed[^>]+?src=|
1010 embedSWF\(?:\s*|
1011 <object[^>]+data=|
1012 new\s+SWFObject\(
1013 )
1014 (["\'])
1015 (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
1016 (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
1017 \1''',
1018 # https://wordpress.org/plugins/lazy-load-for-videos/
1019 r'''(?xs)
1020 <a\s[^>]*\bhref="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"
1021 \s[^>]*\bclass="[^"]*\blazy-load-youtube''',
1022 ]
1023
e40c758c 1024 _PLAYER_INFO_RE = (
cc2db878 1025 r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
1026 r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
545cc85d 1027 r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
e40c758c 1028 )
2c62dc26 1029 _formats = {
c2d3cb4c 1030 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1031 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
1032 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
1033 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
1034 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
1035 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1036 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1037 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
3834d3e3 1038 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
c2d3cb4c 1039 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
1040 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1041 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
1042 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1043 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
1044 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
e1a0bfdf 1045 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
c2d3cb4c 1046 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
1047 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
e1a0bfdf 1048
1049
1050 # 3D videos
c2d3cb4c 1051 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1052 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
1053 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
1054 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
e1a0bfdf 1055 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
1056 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
1057 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
836a086c 1058
96fb5605 1059 # Apple HTTP Live Streaming
11f12195 1060 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
c2d3cb4c 1061 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1062 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1063 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
1064 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
1065 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
e1a0bfdf 1066 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
1067 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
2c62dc26
PH
1068
1069 # DASH mp4 video
d23028a8
S
1070 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
1071 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
1072 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1073 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
1074 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
067aa17e 1075 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
d23028a8
S
1076 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
1077 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
1078 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
1079 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1080 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
1081 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
836a086c 1082
f6f1fc92 1083 # Dash mp4 audio
d23028a8
S
1084 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
1085 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
1086 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
1087 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1088 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
1089 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
1090 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
836a086c
AZ
1091
1092 # Dash webm
d23028a8
S
1093 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1094 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1095 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1096 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1097 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1098 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
1099 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
1100 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1101 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1102 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1103 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1104 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1105 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1106 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1107 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
4c6b4764 1108 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
d23028a8
S
1109 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1110 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1111 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1112 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
1113 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
1114 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
2c62dc26
PH
1115
1116 # Dash webm audio
d23028a8
S
1117 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
1118 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
ce6b9a2d 1119
0857baad 1120 # Dash webm audio with opus inside
d23028a8
S
1121 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
1122 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
1123 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
0857baad 1124
ce6b9a2d
PH
1125 # RTMP (unnamed)
1126 '_rtmp': {'protocol': 'rtmp'},
b85eae0f
S
1127
1128 # av01 video only formats sometimes served with "unknown" codecs
9b5fa9ee
TOH
1129 '394': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
1130 '395': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
1131 '396': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'av01.0.01M.08'},
1132 '397': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'av01.0.04M.08'},
1133 '398': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'av01.0.05M.08'},
1134 '399': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'av01.0.08M.08'},
1135 '400': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
1136 '401': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
c5e8d7af 1137 }
29f7c58a 1138 _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
836a086c 1139
fd5c4aab
S
1140 _GEO_BYPASS = False
1141
78caa52a 1142 IE_NAME = 'youtube'
2eb88d95
PH
1143 _TESTS = [
1144 {
2d3d2997 1145 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
4bc3a23e
PH
1146 'info_dict': {
1147 'id': 'BaW_jenozKc',
1148 'ext': 'mp4',
3867038a 1149 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
4bc3a23e
PH
1150 'uploader': 'Philipp Hagemeister',
1151 'uploader_id': 'phihag',
ec85ded8 1152 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
ff9f925b 1153 'channel': 'Philipp Hagemeister',
dd4c4492
S
1154 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
1155 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
4bc3a23e 1156 'upload_date': '20121002',
ff9f925b 1157 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
4bc3a23e 1158 'categories': ['Science & Technology'],
3867038a 1159 'tags': ['youtube-dl'],
556dbe7f 1160 'duration': 10,
dbdaaa23 1161 'view_count': int,
3e7c1224 1162 'like_count': int,
ff9f925b 1163 'availability': 'public',
1164 'playable_in_embed': True,
1165 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
1166 'live_status': 'not_live',
1167 'age_limit': 0,
7c80519c 1168 'start_time': 1,
297a564b 1169 'end_time': 9,
12a1b225 1170 'comment_count': int,
6c73052c 1171 'channel_follower_count': int
2eb88d95 1172 }
0e853ca4 1173 },
fccd3771 1174 {
4bc3a23e
PH
1175 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
1176 'note': 'Embed-only video (#1746)',
1177 'info_dict': {
1178 'id': 'yZIXLfi8CZQ',
1179 'ext': 'mp4',
1180 'upload_date': '20120608',
1181 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
1182 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
1183 'uploader': 'SET India',
94bfcd23 1184 'uploader_id': 'setindia',
ec85ded8 1185 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
94bfcd23 1186 'age_limit': 18,
545cc85d 1187 },
1188 'skip': 'Private video',
fccd3771 1189 },
11b56058 1190 {
8bdd16b4 1191 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
11b56058
PM
1192 'note': 'Use the first video ID in the URL',
1193 'info_dict': {
1194 'id': 'BaW_jenozKc',
1195 'ext': 'mp4',
3867038a 1196 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
11b56058
PM
1197 'uploader': 'Philipp Hagemeister',
1198 'uploader_id': 'phihag',
ec85ded8 1199 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
976ae3ea 1200 'channel': 'Philipp Hagemeister',
1201 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
1202 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
11b56058 1203 'upload_date': '20121002',
976ae3ea 1204 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
11b56058 1205 'categories': ['Science & Technology'],
3867038a 1206 'tags': ['youtube-dl'],
556dbe7f 1207 'duration': 10,
dbdaaa23 1208 'view_count': int,
11b56058 1209 'like_count': int,
976ae3ea 1210 'availability': 'public',
1211 'playable_in_embed': True,
1212 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
1213 'live_status': 'not_live',
1214 'age_limit': 0,
12a1b225 1215 'comment_count': int,
6c73052c 1216 'channel_follower_count': int
34a7de29
S
1217 },
1218 'params': {
1219 'skip_download': True,
1220 },
11b56058 1221 },
dd27fd17 1222 {
2d3d2997 1223 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
4bc3a23e
PH
1224 'note': '256k DASH audio (format 141) via DASH manifest',
1225 'info_dict': {
1226 'id': 'a9LDPn-MO4I',
1227 'ext': 'm4a',
1228 'upload_date': '20121002',
1229 'uploader_id': '8KVIDEO',
ec85ded8 1230 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
4bc3a23e
PH
1231 'description': '',
1232 'uploader': '8KVIDEO',
1233 'title': 'UHDTV TEST 8K VIDEO.mp4'
4919603f 1234 },
4bc3a23e
PH
1235 'params': {
1236 'youtube_include_dash_manifest': True,
1237 'format': '141',
4919603f 1238 },
de3c7fe0 1239 'skip': 'format 141 not served anymore',
dd27fd17 1240 },
8bdd16b4 1241 # DASH manifest with encrypted signature
1242 {
1243 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
1244 'info_dict': {
1245 'id': 'IB3lcPjvWLA',
1246 'ext': 'm4a',
1247 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
1248 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
1249 'duration': 244,
1250 'uploader': 'AfrojackVEVO',
1251 'uploader_id': 'AfrojackVEVO',
1252 'upload_date': '20131011',
cc2db878 1253 'abr': 129.495,
976ae3ea 1254 'like_count': int,
1255 'channel_id': 'UChuZAo1RKL85gev3Eal9_zg',
1256 'playable_in_embed': True,
1257 'channel_url': 'https://www.youtube.com/channel/UChuZAo1RKL85gev3Eal9_zg',
1258 'view_count': int,
1259 'track': 'The Spark',
1260 'live_status': 'not_live',
1261 'thumbnail': 'https://i.ytimg.com/vi_webp/IB3lcPjvWLA/maxresdefault.webp',
1262 'channel': 'Afrojack',
1263 'uploader_url': 'http://www.youtube.com/user/AfrojackVEVO',
1264 'tags': 'count:19',
1265 'availability': 'public',
1266 'categories': ['Music'],
1267 'age_limit': 0,
1268 'alt_title': 'The Spark',
6c73052c 1269 'channel_follower_count': int
8bdd16b4 1270 },
1271 'params': {
1272 'youtube_include_dash_manifest': True,
1273 'format': '141/bestaudio[ext=m4a]',
1274 },
1275 },
65c2fde2 1276 # Age-gate videos. See https://github.com/yt-dlp/yt-dlp/pull/575#issuecomment-888837000
c522adb1 1277 {
65c2fde2 1278 'note': 'Embed allowed age-gate video',
2d3d2997 1279 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
c522adb1
JMF
1280 'info_dict': {
1281 'id': 'HtVdAasjOgU',
1282 'ext': 'mp4',
1283 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
ec85ded8 1284 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
556dbe7f 1285 'duration': 142,
c522adb1
JMF
1286 'uploader': 'The Witcher',
1287 'uploader_id': 'WitcherGame',
ec85ded8 1288 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
c522adb1 1289 'upload_date': '20140605',
34952f09 1290 'age_limit': 18,
976ae3ea 1291 'categories': ['Gaming'],
1292 'thumbnail': 'https://i.ytimg.com/vi_webp/HtVdAasjOgU/maxresdefault.webp',
1293 'availability': 'needs_auth',
1294 'channel_url': 'https://www.youtube.com/channel/UCzybXLxv08IApdjdN0mJhEg',
1295 'like_count': int,
1296 'channel': 'The Witcher',
1297 'live_status': 'not_live',
1298 'tags': 'count:17',
1299 'channel_id': 'UCzybXLxv08IApdjdN0mJhEg',
1300 'playable_in_embed': True,
1301 'view_count': int,
6c73052c 1302 'channel_follower_count': int
c522adb1
JMF
1303 },
1304 },
65c2fde2 1305 {
1306 'note': 'Age-gate video with embed allowed in public site',
1307 'url': 'https://youtube.com/watch?v=HsUATh_Nc2U',
1308 'info_dict': {
1309 'id': 'HsUATh_Nc2U',
1310 'ext': 'mp4',
1311 'title': 'Godzilla 2 (Official Video)',
1312 'description': 'md5:bf77e03fcae5529475e500129b05668a',
1313 'upload_date': '20200408',
1314 'uploader_id': 'FlyingKitty900',
1315 'uploader': 'FlyingKitty',
1316 'age_limit': 18,
976ae3ea 1317 'availability': 'needs_auth',
1318 'channel_id': 'UCYQT13AtrJC0gsM1far_zJg',
1319 'uploader_url': 'http://www.youtube.com/user/FlyingKitty900',
1320 'channel': 'FlyingKitty',
1321 'channel_url': 'https://www.youtube.com/channel/UCYQT13AtrJC0gsM1far_zJg',
1322 'view_count': int,
1323 'categories': ['Entertainment'],
1324 'live_status': 'not_live',
1325 'tags': ['Flyingkitty', 'godzilla 2'],
1326 'thumbnail': 'https://i.ytimg.com/vi/HsUATh_Nc2U/maxresdefault.jpg',
1327 'like_count': int,
1328 'duration': 177,
1329 'playable_in_embed': True,
6c73052c 1330 'channel_follower_count': int
65c2fde2 1331 },
1332 },
1333 {
1334 'note': 'Age-gate video embedable only with clientScreen=EMBED',
1335 'url': 'https://youtube.com/watch?v=Tq92D6wQ1mg',
1336 'info_dict': {
1337 'id': 'Tq92D6wQ1mg',
1338 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
3619f78d 1339 'ext': 'mp4',
17322130 1340 'upload_date': '20191228',
65c2fde2 1341 'uploader_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
1342 'uploader': 'Projekt Melody',
1343 'description': 'md5:17eccca93a786d51bc67646756894066',
1344 'age_limit': 18,
976ae3ea 1345 'like_count': int,
1346 'availability': 'needs_auth',
1347 'uploader_url': 'http://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
1348 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
1349 'view_count': int,
1350 'thumbnail': 'https://i.ytimg.com/vi_webp/Tq92D6wQ1mg/sddefault.webp',
1351 'channel': 'Projekt Melody',
1352 'live_status': 'not_live',
1353 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
1354 'playable_in_embed': True,
1355 'categories': ['Entertainment'],
1356 'duration': 106,
1357 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
12a1b225 1358 'comment_count': int,
6c73052c 1359 'channel_follower_count': int
65c2fde2 1360 },
1361 },
1362 {
1363 'note': 'Non-Agegated non-embeddable video',
1364 'url': 'https://youtube.com/watch?v=MeJVWBSsPAY',
1365 'info_dict': {
1366 'id': 'MeJVWBSsPAY',
1367 'ext': 'mp4',
1368 'title': 'OOMPH! - Such Mich Find Mich (Lyrics)',
1369 'uploader': 'Herr Lurik',
1370 'uploader_id': 'st3in234',
1371 'description': 'Fan Video. Music & Lyrics by OOMPH!.',
1372 'upload_date': '20130730',
976ae3ea 1373 'track': 'Such mich find mich',
1374 'age_limit': 0,
1375 'tags': ['oomph', 'such mich find mich', 'lyrics', 'german industrial', 'musica industrial'],
1376 'like_count': int,
1377 'playable_in_embed': False,
1378 'creator': 'OOMPH!',
1379 'thumbnail': 'https://i.ytimg.com/vi/MeJVWBSsPAY/sddefault.jpg',
1380 'view_count': int,
1381 'alt_title': 'Such mich find mich',
1382 'duration': 210,
1383 'channel': 'Herr Lurik',
1384 'channel_id': 'UCdR3RSDPqub28LjZx0v9-aA',
1385 'categories': ['Music'],
1386 'availability': 'public',
1387 'uploader_url': 'http://www.youtube.com/user/st3in234',
1388 'channel_url': 'https://www.youtube.com/channel/UCdR3RSDPqub28LjZx0v9-aA',
1389 'live_status': 'not_live',
1390 'artist': 'OOMPH!',
6c73052c 1391 'channel_follower_count': int
65c2fde2 1392 },
1393 },
1394 {
1395 'note': 'Non-bypassable age-gated video',
1396 'url': 'https://youtube.com/watch?v=Cr381pDsSsA',
1397 'only_matching': True,
1398 },
8bdd16b4 1399 # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
1400 # YouTube Red ad is not captured for creator
1401 {
1402 'url': '__2ABJjxzNo',
1403 'info_dict': {
1404 'id': '__2ABJjxzNo',
1405 'ext': 'mp4',
1406 'duration': 266,
1407 'upload_date': '20100430',
1408 'uploader_id': 'deadmau5',
1409 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
545cc85d 1410 'creator': 'deadmau5',
1411 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
8bdd16b4 1412 'uploader': 'deadmau5',
1413 'title': 'Deadmau5 - Some Chords (HD)',
545cc85d 1414 'alt_title': 'Some Chords',
976ae3ea 1415 'availability': 'public',
1416 'tags': 'count:14',
1417 'channel_id': 'UCYEK6xds6eo-3tr4xRdflmQ',
1418 'view_count': int,
1419 'live_status': 'not_live',
1420 'channel': 'deadmau5',
1421 'thumbnail': 'https://i.ytimg.com/vi_webp/__2ABJjxzNo/maxresdefault.webp',
1422 'like_count': int,
1423 'track': 'Some Chords',
1424 'artist': 'deadmau5',
1425 'playable_in_embed': True,
1426 'age_limit': 0,
1427 'channel_url': 'https://www.youtube.com/channel/UCYEK6xds6eo-3tr4xRdflmQ',
1428 'categories': ['Music'],
1429 'album': 'Some Chords',
6c73052c 1430 'channel_follower_count': int
8bdd16b4 1431 },
1432 'expected_warnings': [
1433 'DASH manifest missing',
1434 ]
1435 },
067aa17e 1436 # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
e52a40ab
PH
1437 {
1438 'url': 'lqQg6PlCWgI',
1439 'info_dict': {
1440 'id': 'lqQg6PlCWgI',
1441 'ext': 'mp4',
556dbe7f 1442 'duration': 6085,
90227264 1443 'upload_date': '20150827',
cbe2bd91 1444 'uploader_id': 'olympic',
ec85ded8 1445 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
12a1b225 1446 'description': 'md5:04bbbf3ccceb6795947572ca36f45904',
11f9be09 1447 'uploader': 'Olympics',
cbe2bd91 1448 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
976ae3ea 1449 'like_count': int,
1450 'release_timestamp': 1343767800,
1451 'playable_in_embed': True,
1452 'categories': ['Sports'],
1453 'release_date': '20120731',
1454 'channel': 'Olympics',
1455 'tags': ['Hockey', '2012-07-31', '31 July 2012', 'Riverbank Arena', 'Session', 'Olympics', 'Olympic Games', 'London 2012', '2012 Summer Olympics', 'Summer Games'],
1456 'channel_id': 'UCTl3QQTvqHFjurroKxexy2Q',
1457 'thumbnail': 'https://i.ytimg.com/vi/lqQg6PlCWgI/maxresdefault.jpg',
1458 'age_limit': 0,
1459 'availability': 'public',
1460 'live_status': 'was_live',
1461 'view_count': int,
1462 'channel_url': 'https://www.youtube.com/channel/UCTl3QQTvqHFjurroKxexy2Q',
6c73052c 1463 'channel_follower_count': int
cbe2bd91
PH
1464 },
1465 'params': {
1466 'skip_download': 'requires avconv',
e52a40ab 1467 }
cbe2bd91 1468 },
6271f1ca
PH
1469 # Non-square pixels
1470 {
1471 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
1472 'info_dict': {
1473 'id': '_b-2C3KPAM0',
1474 'ext': 'mp4',
1475 'stretched_ratio': 16 / 9.,
556dbe7f 1476 'duration': 85,
6271f1ca
PH
1477 'upload_date': '20110310',
1478 'uploader_id': 'AllenMeow',
ec85ded8 1479 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
6271f1ca 1480 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
eb6793ba 1481 'uploader': '孫ᄋᄅ',
6271f1ca 1482 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
976ae3ea 1483 'playable_in_embed': True,
1484 'channel': '孫ᄋᄅ',
1485 'age_limit': 0,
1486 'tags': 'count:11',
1487 'channel_url': 'https://www.youtube.com/channel/UCS-xxCmRaA6BFdmgDPA_BIw',
1488 'channel_id': 'UCS-xxCmRaA6BFdmgDPA_BIw',
1489 'thumbnail': 'https://i.ytimg.com/vi/_b-2C3KPAM0/maxresdefault.jpg',
1490 'view_count': int,
1491 'categories': ['People & Blogs'],
1492 'like_count': int,
1493 'live_status': 'not_live',
1494 'availability': 'unlisted',
12a1b225 1495 'comment_count': int,
6c73052c 1496 'channel_follower_count': int
6271f1ca 1497 },
06b491eb
S
1498 },
1499 # url_encoded_fmt_stream_map is empty string
1500 {
1501 'url': 'qEJwOuvDf7I',
1502 'info_dict': {
1503 'id': 'qEJwOuvDf7I',
f57b7835 1504 'ext': 'webm',
06b491eb
S
1505 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
1506 'description': '',
1507 'upload_date': '20150404',
1508 'uploader_id': 'spbelect',
1509 'uploader': 'Наблюдатели Петербурга',
1510 },
1511 'params': {
1512 'skip_download': 'requires avconv',
e323cf3f
S
1513 },
1514 'skip': 'This live event has ended.',
06b491eb 1515 },
067aa17e 1516 # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
da77d856
S
1517 {
1518 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
1519 'info_dict': {
1520 'id': 'FIl7x6_3R5Y',
eb6793ba 1521 'ext': 'webm',
da77d856
S
1522 'title': 'md5:7b81415841e02ecd4313668cde88737a',
1523 'description': 'md5:116377fd2963b81ec4ce64b542173306',
556dbe7f 1524 'duration': 220,
da77d856
S
1525 'upload_date': '20150625',
1526 'uploader_id': 'dorappi2000',
ec85ded8 1527 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
da77d856 1528 'uploader': 'dorappi2000',
eb6793ba 1529 'formats': 'mincount:31',
da77d856 1530 },
eb6793ba 1531 'skip': 'not actual anymore',
2ee8f5d8 1532 },
8a1a26ce
YCH
1533 # DASH manifest with segment_list
1534 {
1535 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
1536 'md5': '8ce563a1d667b599d21064e982ab9e31',
1537 'info_dict': {
1538 'id': 'CsmdDsKjzN8',
1539 'ext': 'mp4',
17ee98e1 1540 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
8a1a26ce
YCH
1541 'uploader': 'Airtek',
1542 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
1543 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
1544 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
1545 },
1546 'params': {
1547 'youtube_include_dash_manifest': True,
1548 'format': '135', # bestvideo
be49068d
S
1549 },
1550 'skip': 'This live event has ended.',
2ee8f5d8 1551 },
cf7e015f
S
1552 {
1553 # Multifeed videos (multiple cameras), URL is for Main Camera
545cc85d 1554 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
cf7e015f 1555 'info_dict': {
545cc85d 1556 'id': 'jvGDaLqkpTg',
1557 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
1558 'description': 'md5:e03b909557865076822aa169218d6a5d',
cf7e015f
S
1559 },
1560 'playlist': [{
1561 'info_dict': {
545cc85d 1562 'id': 'jvGDaLqkpTg',
cf7e015f 1563 'ext': 'mp4',
545cc85d 1564 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
1565 'description': 'md5:e03b909557865076822aa169218d6a5d',
1566 'duration': 10643,
1567 'upload_date': '20161111',
1568 'uploader': 'Team PGP',
1569 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
1570 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
cf7e015f
S
1571 },
1572 }, {
1573 'info_dict': {
545cc85d 1574 'id': '3AKt1R1aDnw',
cf7e015f 1575 'ext': 'mp4',
545cc85d 1576 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
1577 'description': 'md5:e03b909557865076822aa169218d6a5d',
1578 'duration': 10991,
1579 'upload_date': '20161111',
1580 'uploader': 'Team PGP',
1581 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
1582 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
cf7e015f
S
1583 },
1584 }, {
1585 'info_dict': {
545cc85d 1586 'id': 'RtAMM00gpVc',
cf7e015f 1587 'ext': 'mp4',
545cc85d 1588 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
1589 'description': 'md5:e03b909557865076822aa169218d6a5d',
1590 'duration': 10995,
1591 'upload_date': '20161111',
1592 'uploader': 'Team PGP',
1593 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
1594 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
cf7e015f
S
1595 },
1596 }, {
1597 'info_dict': {
545cc85d 1598 'id': '6N2fdlP3C5U',
cf7e015f 1599 'ext': 'mp4',
545cc85d 1600 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
1601 'description': 'md5:e03b909557865076822aa169218d6a5d',
1602 'duration': 10990,
1603 'upload_date': '20161111',
1604 'uploader': 'Team PGP',
1605 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
1606 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
cf7e015f
S
1607 },
1608 }],
1609 'params': {
1610 'skip_download': True,
1611 },
65c2fde2 1612 'skip': 'Not multifeed anymore',
cbaed4bb 1613 },
f9f49d87 1614 {
067aa17e 1615 # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
f9f49d87
S
1616 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
1617 'info_dict': {
1618 'id': 'gVfLd0zydlo',
1619 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
1620 },
1621 'playlist_count': 2,
be49068d 1622 'skip': 'Not multifeed anymore',
f9f49d87 1623 },
cbaed4bb 1624 {
2d3d2997 1625 'url': 'https://vid.plus/FlRa-iH7PGw',
cbaed4bb 1626 'only_matching': True,
0e49d9a6 1627 },
6d4fc66b 1628 {
2d3d2997 1629 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
6d4fc66b
S
1630 'only_matching': True,
1631 },
0e49d9a6 1632 {
067aa17e 1633 # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
a8776b10 1634 # Also tests cut-off URL expansion in video description (see
067aa17e
S
1635 # https://github.com/ytdl-org/youtube-dl/issues/1892,
1636 # https://github.com/ytdl-org/youtube-dl/issues/8164)
0e49d9a6
LL
1637 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
1638 'info_dict': {
1639 'id': 'lsguqyKfVQg',
1640 'ext': 'mp4',
1641 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
11f9be09 1642 'alt_title': 'Dark Walk',
0e49d9a6 1643 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
556dbe7f 1644 'duration': 133,
0e49d9a6
LL
1645 'upload_date': '20151119',
1646 'uploader_id': 'IronSoulElf',
ec85ded8 1647 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
0e49d9a6 1648 'uploader': 'IronSoulElf',
11f9be09 1649 'creator': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
1650 'track': 'Dark Walk',
1651 'artist': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
92bc97d3 1652 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
976ae3ea 1653 'thumbnail': 'https://i.ytimg.com/vi_webp/lsguqyKfVQg/maxresdefault.webp',
1654 'categories': ['Film & Animation'],
1655 'view_count': int,
1656 'live_status': 'not_live',
1657 'channel_url': 'https://www.youtube.com/channel/UCTSRgz5jylBvFt_S7wnsqLQ',
1658 'channel_id': 'UCTSRgz5jylBvFt_S7wnsqLQ',
1659 'tags': 'count:13',
1660 'availability': 'public',
1661 'channel': 'IronSoulElf',
1662 'playable_in_embed': True,
1663 'like_count': int,
1664 'age_limit': 0,
6c73052c 1665 'channel_follower_count': int
0e49d9a6
LL
1666 },
1667 'params': {
1668 'skip_download': True,
1669 },
1670 },
61f92af1 1671 {
067aa17e 1672 # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
61f92af1
S
1673 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
1674 'only_matching': True,
1675 },
313dfc45
LL
1676 {
1677 # Video with yt:stretch=17:0
1678 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
1679 'info_dict': {
1680 'id': 'Q39EVAstoRM',
1681 'ext': 'mp4',
1682 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
1683 'description': 'md5:ee18a25c350637c8faff806845bddee9',
1684 'upload_date': '20151107',
1685 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
1686 'uploader': 'CH GAMER DROID',
1687 },
1688 'params': {
1689 'skip_download': True,
1690 },
be49068d 1691 'skip': 'This video does not exist.',
313dfc45 1692 },
201c1459 1693 {
1694 # Video with incomplete 'yt:stretch=16:'
1695 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
1696 'only_matching': True,
1697 },
7caf9830
S
1698 {
1699 # Video licensed under Creative Commons
1700 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
1701 'info_dict': {
1702 'id': 'M4gD1WSo5mA',
1703 'ext': 'mp4',
1704 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
1705 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
556dbe7f 1706 'duration': 721,
17322130 1707 'upload_date': '20150128',
7caf9830 1708 'uploader_id': 'BerkmanCenter',
ec85ded8 1709 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
556dbe7f 1710 'uploader': 'The Berkman Klein Center for Internet & Society',
7caf9830 1711 'license': 'Creative Commons Attribution license (reuse allowed)',
976ae3ea 1712 'channel_id': 'UCuLGmD72gJDBwmLw06X58SA',
1713 'channel_url': 'https://www.youtube.com/channel/UCuLGmD72gJDBwmLw06X58SA',
1714 'like_count': int,
1715 'age_limit': 0,
1716 'tags': ['Copyright (Legal Subject)', 'Law (Industry)', 'William W. Fisher (Author)'],
1717 'channel': 'The Berkman Klein Center for Internet & Society',
1718 'availability': 'public',
1719 'view_count': int,
1720 'categories': ['Education'],
1721 'thumbnail': 'https://i.ytimg.com/vi_webp/M4gD1WSo5mA/maxresdefault.webp',
1722 'live_status': 'not_live',
1723 'playable_in_embed': True,
12a1b225 1724 'comment_count': int,
d5d1df8a 1725 'channel_follower_count': int,
1726 'chapters': list,
7caf9830
S
1727 },
1728 'params': {
1729 'skip_download': True,
1730 },
1731 },
fd050249
S
1732 {
1733 # Channel-like uploader_url
1734 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
1735 'info_dict': {
1736 'id': 'eQcmzGIKrzg',
1737 'ext': 'mp4',
1738 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
545cc85d 1739 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
556dbe7f 1740 'duration': 4060,
17322130 1741 'upload_date': '20151120',
eb6793ba 1742 'uploader': 'Bernie Sanders',
fd050249 1743 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
ec85ded8 1744 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
fd050249 1745 'license': 'Creative Commons Attribution license (reuse allowed)',
976ae3ea 1746 'playable_in_embed': True,
1747 'tags': 'count:12',
1748 'like_count': int,
1749 'channel_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
1750 'age_limit': 0,
1751 'availability': 'public',
1752 'categories': ['News & Politics'],
1753 'channel': 'Bernie Sanders',
1754 'thumbnail': 'https://i.ytimg.com/vi_webp/eQcmzGIKrzg/maxresdefault.webp',
1755 'view_count': int,
1756 'live_status': 'not_live',
1757 'channel_url': 'https://www.youtube.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
12a1b225 1758 'comment_count': int,
d5d1df8a 1759 'channel_follower_count': int,
1760 'chapters': list,
fd050249
S
1761 },
1762 'params': {
1763 'skip_download': True,
1764 },
1765 },
040ac686
S
1766 {
1767 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
1768 'only_matching': True,
7f29cf54
S
1769 },
1770 {
067aa17e 1771 # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
7f29cf54
S
1772 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
1773 'only_matching': True,
6496ccb4
S
1774 },
1775 {
1776 # Rental video preview
1777 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
1778 'info_dict': {
1779 'id': 'uGpuVWrhIzE',
1780 'ext': 'mp4',
1781 'title': 'Piku - Trailer',
1782 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
1783 'upload_date': '20150811',
1784 'uploader': 'FlixMatrix',
1785 'uploader_id': 'FlixMatrixKaravan',
ec85ded8 1786 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
6496ccb4
S
1787 'license': 'Standard YouTube License',
1788 },
1789 'params': {
1790 'skip_download': True,
1791 },
eb6793ba 1792 'skip': 'This video is not available.',
022a5d66 1793 },
12afdc2a
S
1794 {
1795 # YouTube Red video with episode data
1796 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
1797 'info_dict': {
1798 'id': 'iqKdEhx-dD4',
1799 'ext': 'mp4',
1800 'title': 'Isolation - Mind Field (Ep 1)',
545cc85d 1801 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
556dbe7f 1802 'duration': 2085,
12afdc2a
S
1803 'upload_date': '20170118',
1804 'uploader': 'Vsauce',
1805 'uploader_id': 'Vsauce',
1806 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
12afdc2a
S
1807 'series': 'Mind Field',
1808 'season_number': 1,
1809 'episode_number': 1,
976ae3ea 1810 'thumbnail': 'https://i.ytimg.com/vi_webp/iqKdEhx-dD4/maxresdefault.webp',
1811 'tags': 'count:12',
1812 'view_count': int,
1813 'availability': 'public',
1814 'age_limit': 0,
1815 'channel': 'Vsauce',
1816 'episode': 'Episode 1',
1817 'categories': ['Entertainment'],
1818 'season': 'Season 1',
1819 'channel_id': 'UC6nSFpj9HTCZ5t-N3Rm3-HA',
1820 'channel_url': 'https://www.youtube.com/channel/UC6nSFpj9HTCZ5t-N3Rm3-HA',
1821 'like_count': int,
1822 'playable_in_embed': True,
1823 'live_status': 'not_live',
6c73052c 1824 'channel_follower_count': int
12afdc2a
S
1825 },
1826 'params': {
1827 'skip_download': True,
1828 },
1829 'expected_warnings': [
1830 'Skipping DASH manifest',
1831 ],
1832 },
c7121fa7
S
1833 {
1834 # The following content has been identified by the YouTube community
1835 # as inappropriate or offensive to some audiences.
1836 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
1837 'info_dict': {
1838 'id': '6SJNVb0GnPI',
1839 'ext': 'mp4',
1840 'title': 'Race Differences in Intelligence',
1841 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
1842 'duration': 965,
1843 'upload_date': '20140124',
1844 'uploader': 'New Century Foundation',
1845 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
1846 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
c7121fa7
S
1847 },
1848 'params': {
1849 'skip_download': True,
1850 },
545cc85d 1851 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
c7121fa7 1852 },
022a5d66
S
1853 {
1854 # itag 212
1855 'url': '1t24XAntNCY',
1856 'only_matching': True,
fd5c4aab
S
1857 },
1858 {
1859 # geo restricted to JP
1860 'url': 'sJL6WA-aGkQ',
1861 'only_matching': True,
1862 },
cd5a74a2
S
1863 {
1864 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
1865 'only_matching': True,
1866 },
bc2ca1bb 1867 {
1868 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
1869 'only_matching': True,
1870 },
1871 {
1872 # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
1873 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
1874 'only_matching': True,
1875 },
825cd268
RA
1876 {
1877 # DRM protected
1878 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
1879 'only_matching': True,
4fe54c12
S
1880 },
1881 {
1882 # Video with unsupported adaptive stream type formats
1883 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
1884 'info_dict': {
1885 'id': 'Z4Vy8R84T1U',
1886 'ext': 'mp4',
1887 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
1888 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
1889 'duration': 433,
1890 'upload_date': '20130923',
1891 'uploader': 'Amelia Putri Harwita',
1892 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
1893 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
1894 'formats': 'maxcount:10',
1895 },
1896 'params': {
1897 'skip_download': True,
1898 'youtube_include_dash_manifest': False,
1899 },
5429d6a9 1900 'skip': 'not actual anymore',
5caabd3c 1901 },
1902 {
822b9d9c 1903 # Youtube Music Auto-generated description
5caabd3c 1904 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
1905 'info_dict': {
1906 'id': 'MgNrAu2pzNs',
1907 'ext': 'mp4',
1908 'title': 'Voyeur Girl',
1909 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
1910 'upload_date': '20190312',
5429d6a9
S
1911 'uploader': 'Stephen - Topic',
1912 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
5caabd3c 1913 'artist': 'Stephen',
1914 'track': 'Voyeur Girl',
1915 'album': 'it\'s too much love to know my dear',
1916 'release_date': '20190313',
1917 'release_year': 2019,
976ae3ea 1918 'alt_title': 'Voyeur Girl',
1919 'view_count': int,
1920 'uploader_url': 'http://www.youtube.com/channel/UC-pWHpBjdGG69N9mM2auIAA',
1921 'playable_in_embed': True,
1922 'like_count': int,
1923 'categories': ['Music'],
1924 'channel_url': 'https://www.youtube.com/channel/UC-pWHpBjdGG69N9mM2auIAA',
1925 'channel': 'Stephen',
1926 'availability': 'public',
1927 'creator': 'Stephen',
1928 'duration': 169,
1929 'thumbnail': 'https://i.ytimg.com/vi_webp/MgNrAu2pzNs/maxresdefault.webp',
1930 'age_limit': 0,
1931 'channel_id': 'UC-pWHpBjdGG69N9mM2auIAA',
1932 'tags': 'count:11',
1933 'live_status': 'not_live',
6c73052c 1934 'channel_follower_count': int
5caabd3c 1935 },
1936 'params': {
1937 'skip_download': True,
1938 },
1939 },
66b48727
RA
1940 {
1941 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
1942 'only_matching': True,
1943 },
011e75e6
S
1944 {
1945 # invalid -> valid video id redirection
1946 'url': 'DJztXj2GPfl',
1947 'info_dict': {
1948 'id': 'DJztXj2GPfk',
1949 'ext': 'mp4',
1950 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
1951 'description': 'md5:bf577a41da97918e94fa9798d9228825',
1952 'upload_date': '20090125',
1953 'uploader': 'Prochorowka',
1954 'uploader_id': 'Prochorowka',
1955 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
1956 'artist': 'Panjabi MC',
1957 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
1958 'album': 'Beware of the Boys (Mundian To Bach Ke)',
1959 },
1960 'params': {
1961 'skip_download': True,
1962 },
545cc85d 1963 'skip': 'Video unavailable',
ea74e00b
DP
1964 },
1965 {
1966 # empty description results in an empty string
1967 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
1968 'info_dict': {
1969 'id': 'x41yOUIvK2k',
1970 'ext': 'mp4',
1971 'title': 'IMG 3456',
1972 'description': '',
1973 'upload_date': '20170613',
1974 'uploader_id': 'ElevageOrVert',
1975 'uploader': 'ElevageOrVert',
976ae3ea 1976 'view_count': int,
1977 'thumbnail': 'https://i.ytimg.com/vi_webp/x41yOUIvK2k/maxresdefault.webp',
1978 'uploader_url': 'http://www.youtube.com/user/ElevageOrVert',
1979 'like_count': int,
1980 'channel_id': 'UCo03ZQPBW5U4UC3regpt1nw',
1981 'tags': [],
1982 'channel_url': 'https://www.youtube.com/channel/UCo03ZQPBW5U4UC3regpt1nw',
1983 'availability': 'public',
1984 'age_limit': 0,
1985 'categories': ['Pets & Animals'],
1986 'duration': 7,
1987 'playable_in_embed': True,
1988 'live_status': 'not_live',
1989 'channel': 'ElevageOrVert',
6c73052c 1990 'channel_follower_count': int
ea74e00b
DP
1991 },
1992 'params': {
1993 'skip_download': True,
1994 },
1995 },
a0566bbf 1996 {
29f7c58a 1997 # with '};' inside yt initial data (see [1])
1998 # see [2] for an example with '};' inside ytInitialPlayerResponse
1999 # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
2000 # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
a0566bbf 2001 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
2002 'info_dict': {
2003 'id': 'CHqg6qOn4no',
2004 'ext': 'mp4',
2005 'title': 'Part 77 Sort a list of simple types in c#',
2006 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
2007 'upload_date': '20130831',
2008 'uploader_id': 'kudvenkat',
2009 'uploader': 'kudvenkat',
976ae3ea 2010 'channel_id': 'UCCTVrRB5KpIiK6V2GGVsR1Q',
2011 'like_count': int,
2012 'uploader_url': 'http://www.youtube.com/user/kudvenkat',
2013 'channel_url': 'https://www.youtube.com/channel/UCCTVrRB5KpIiK6V2GGVsR1Q',
2014 'live_status': 'not_live',
2015 'categories': ['Education'],
2016 'availability': 'public',
2017 'thumbnail': 'https://i.ytimg.com/vi/CHqg6qOn4no/sddefault.jpg',
2018 'tags': 'count:12',
2019 'playable_in_embed': True,
2020 'age_limit': 0,
2021 'view_count': int,
2022 'duration': 522,
2023 'channel': 'kudvenkat',
12a1b225 2024 'comment_count': int,
d5d1df8a 2025 'channel_follower_count': int,
2026 'chapters': list,
a0566bbf 2027 },
2028 'params': {
2029 'skip_download': True,
2030 },
2031 },
29f7c58a 2032 {
2033 # another example of '};' in ytInitialData
2034 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
2035 'only_matching': True,
2036 },
2037 {
2038 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
2039 'only_matching': True,
2040 },
545cc85d 2041 {
cc2db878 2042 # https://github.com/ytdl-org/youtube-dl/pull/28094
2043 'url': 'OtqTfy26tG0',
2044 'info_dict': {
2045 'id': 'OtqTfy26tG0',
2046 'ext': 'mp4',
2047 'title': 'Burn Out',
2048 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
2049 'upload_date': '20141120',
2050 'uploader': 'The Cinematic Orchestra - Topic',
2051 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
2052 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
2053 'artist': 'The Cinematic Orchestra',
2054 'track': 'Burn Out',
2055 'album': 'Every Day',
976ae3ea 2056 'like_count': int,
2057 'live_status': 'not_live',
2058 'alt_title': 'Burn Out',
2059 'duration': 614,
2060 'age_limit': 0,
2061 'view_count': int,
2062 'channel_url': 'https://www.youtube.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
2063 'creator': 'The Cinematic Orchestra',
2064 'channel': 'The Cinematic Orchestra',
2065 'tags': ['The Cinematic Orchestra', 'Every Day', 'Burn Out'],
2066 'channel_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
2067 'availability': 'public',
2068 'thumbnail': 'https://i.ytimg.com/vi/OtqTfy26tG0/maxresdefault.jpg',
2069 'categories': ['Music'],
2070 'playable_in_embed': True,
6c73052c 2071 'channel_follower_count': int
cc2db878 2072 },
2073 'params': {
2074 'skip_download': True,
2075 },
545cc85d 2076 },
bc2ca1bb 2077 {
2078 # controversial video, only works with bpctr when authenticated with cookies
2079 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
2080 'only_matching': True,
2081 },
a1a7907b 2082 {
2083 # controversial video, requires bpctr/contentCheckOk
2084 'url': 'https://www.youtube.com/watch?v=SZJvDhaSDnc',
2085 'info_dict': {
2086 'id': 'SZJvDhaSDnc',
2087 'ext': 'mp4',
2088 'title': 'San Diego teen commits suicide after bullying over embarrassing video',
2089 'channel_id': 'UC-SJ6nODDmufqBzPBwCvYvQ',
976ae3ea 2090 'uploader': 'CBS Mornings',
11f9be09 2091 'uploader_id': 'CBSThisMorning',
a1a7907b 2092 'upload_date': '20140716',
976ae3ea 2093 'description': 'md5:acde3a73d3f133fc97e837a9f76b53b7',
2094 'duration': 170,
2095 'categories': ['News & Politics'],
2096 'uploader_url': 'http://www.youtube.com/user/CBSThisMorning',
2097 'view_count': int,
2098 'channel': 'CBS Mornings',
2099 'tags': ['suicide', 'bullying', 'video', 'cbs', 'news'],
2100 'thumbnail': 'https://i.ytimg.com/vi/SZJvDhaSDnc/hqdefault.jpg',
2101 'age_limit': 18,
2102 'availability': 'needs_auth',
2103 'channel_url': 'https://www.youtube.com/channel/UC-SJ6nODDmufqBzPBwCvYvQ',
2104 'like_count': int,
2105 'live_status': 'not_live',
2106 'playable_in_embed': True,
6c73052c 2107 'channel_follower_count': int
a1a7907b 2108 }
2109 },
f7ad7160 2110 {
2111 # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
2112 'url': 'cBvYw8_A0vQ',
2113 'info_dict': {
2114 'id': 'cBvYw8_A0vQ',
2115 'ext': 'mp4',
2116 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
2117 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
2118 'upload_date': '20201120',
2119 'uploader': 'Walk around Japan',
2120 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
2121 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
976ae3ea 2122 'duration': 1456,
2123 'categories': ['Travel & Events'],
2124 'channel_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
2125 'view_count': int,
2126 'channel': 'Walk around Japan',
2127 'tags': ['Ueno Tokyo', 'Okachimachi Tokyo', 'Ameyoko Street', 'Tokyo attraction', 'Travel in Tokyo'],
2128 'thumbnail': 'https://i.ytimg.com/vi_webp/cBvYw8_A0vQ/hqdefault.webp',
2129 'age_limit': 0,
2130 'availability': 'public',
2131 'channel_url': 'https://www.youtube.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
2132 'live_status': 'not_live',
2133 'playable_in_embed': True,
6c73052c 2134 'channel_follower_count': int
f7ad7160 2135 },
2136 'params': {
2137 'skip_download': True,
2138 },
0fb983f6 2139 }, {
2140 # Has multiple audio streams
2141 'url': 'WaOKSUlf4TM',
2142 'only_matching': True
9297939e 2143 }, {
2144 # Requires Premium: has format 141 when requested using YTM url
2145 'url': 'https://music.youtube.com/watch?v=XclachpHxis',
2146 'only_matching': True
2147 }, {
120916da 2148 # multiple subtitles with same lang_code
2149 'url': 'https://www.youtube.com/watch?v=wsQiKKfKxug',
2150 'only_matching': True,
109dd3b2 2151 }, {
2152 # Force use android client fallback
2153 'url': 'https://www.youtube.com/watch?v=YOelRv7fMxY',
2154 'info_dict': {
2155 'id': 'YOelRv7fMxY',
11f9be09 2156 'title': 'DIGGING A SECRET TUNNEL Part 1',
109dd3b2 2157 'ext': '3gp',
2158 'upload_date': '20210624',
2159 'channel_id': 'UCp68_FLety0O-n9QU6phsgw',
2160 'uploader': 'colinfurze',
11f9be09 2161 'uploader_id': 'colinfurze',
109dd3b2 2162 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCp68_FLety0O-n9QU6phsgw',
976ae3ea 2163 'description': 'md5:5d5991195d599b56cd0c4148907eec50',
2164 'duration': 596,
2165 'categories': ['Entertainment'],
2166 'uploader_url': 'http://www.youtube.com/user/colinfurze',
2167 'view_count': int,
2168 'channel': 'colinfurze',
2169 'tags': ['Colin', 'furze', 'Terry', 'tunnel', 'underground', 'bunker'],
2170 'thumbnail': 'https://i.ytimg.com/vi/YOelRv7fMxY/maxresdefault.jpg',
2171 'age_limit': 0,
2172 'availability': 'public',
2173 'like_count': int,
2174 'live_status': 'not_live',
2175 'playable_in_embed': True,
d5d1df8a 2176 'channel_follower_count': int,
2177 'chapters': list,
109dd3b2 2178 },
2179 'params': {
2180 'format': '17', # 3gp format available on android
2181 'extractor_args': {'youtube': {'player_client': ['android']}},
2182 },
120916da 2183 },
109dd3b2 2184 {
2185 # Skip download of additional client configs (remix client config in this case)
2186 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
2187 'only_matching': True,
2188 'params': {
2189 'extractor_args': {'youtube': {'player_skip': ['configs']}},
2190 },
8fc54b12 2191 }, {
2192 # shorts
2193 'url': 'https://www.youtube.com/shorts/BGQWPY4IigY',
2194 'only_matching': True,
9222c381 2195 }, {
2196 'note': 'Storyboards',
2197 'url': 'https://www.youtube.com/watch?v=5KLPxDtMqe8',
2198 'info_dict': {
2199 'id': '5KLPxDtMqe8',
2200 'ext': 'mhtml',
2201 'format_id': 'sb0',
2202 'title': 'Your Brain is Plastic',
2203 'uploader_id': 'scishow',
2204 'description': 'md5:89cd86034bdb5466cd87c6ba206cd2bc',
2205 'upload_date': '20140324',
2206 'uploader': 'SciShow',
976ae3ea 2207 'like_count': int,
2208 'channel_id': 'UCZYTClx2T1of7BRZ86-8fow',
2209 'channel_url': 'https://www.youtube.com/channel/UCZYTClx2T1of7BRZ86-8fow',
2210 'view_count': int,
2211 'thumbnail': 'https://i.ytimg.com/vi/5KLPxDtMqe8/maxresdefault.jpg',
2212 'playable_in_embed': True,
2213 'tags': 'count:12',
2214 'uploader_url': 'http://www.youtube.com/user/scishow',
2215 'availability': 'public',
2216 'channel': 'SciShow',
2217 'live_status': 'not_live',
2218 'duration': 248,
2219 'categories': ['Education'],
2220 'age_limit': 0,
d5d1df8a 2221 'channel_follower_count': int,
2222 'chapters': list,
9222c381 2223 }, 'params': {'format': 'mhtml', 'skip_download': True}
992f9a73 2224 }, {
2225 # Ensure video upload_date is in UTC timezone (video was uploaded 1641170939)
2226 'url': 'https://www.youtube.com/watch?v=2NUZ8W2llS4',
2227 'info_dict': {
2228 'id': '2NUZ8W2llS4',
2229 'ext': 'mp4',
2230 'title': 'The NP that test your phone performance 🙂',
2231 'description': 'md5:144494b24d4f9dfacb97c1bbef5de84d',
2232 'uploader': 'Leon Nguyen',
2233 'uploader_id': 'VNSXIII',
2234 'uploader_url': 'http://www.youtube.com/user/VNSXIII',
2235 'channel_id': 'UCRqNBSOHgilHfAczlUmlWHA',
2236 'channel_url': 'https://www.youtube.com/channel/UCRqNBSOHgilHfAczlUmlWHA',
2237 'duration': 21,
2238 'view_count': int,
2239 'age_limit': 0,
2240 'categories': ['Gaming'],
2241 'tags': 'count:23',
2242 'playable_in_embed': True,
2243 'live_status': 'not_live',
2244 'upload_date': '20220103',
2245 'like_count': int,
2246 'availability': 'public',
2247 'channel': 'Leon Nguyen',
2248 'thumbnail': 'https://i.ytimg.com/vi_webp/2NUZ8W2llS4/maxresdefault.webp',
12a1b225 2249 'comment_count': int,
992f9a73 2250 'channel_follower_count': int
2251 }
1ff88b7a 2252 }, {
2253 # Same video as above, but with --compat-opt no-youtube-prefer-utc-upload-date
2254 'url': 'https://www.youtube.com/watch?v=2NUZ8W2llS4',
2255 'info_dict': {
2256 'id': '2NUZ8W2llS4',
2257 'ext': 'mp4',
2258 'title': 'The NP that test your phone performance 🙂',
2259 'description': 'md5:144494b24d4f9dfacb97c1bbef5de84d',
2260 'uploader': 'Leon Nguyen',
2261 'uploader_id': 'VNSXIII',
2262 'uploader_url': 'http://www.youtube.com/user/VNSXIII',
2263 'channel_id': 'UCRqNBSOHgilHfAczlUmlWHA',
2264 'channel_url': 'https://www.youtube.com/channel/UCRqNBSOHgilHfAczlUmlWHA',
2265 'duration': 21,
2266 'view_count': int,
2267 'age_limit': 0,
2268 'categories': ['Gaming'],
2269 'tags': 'count:23',
2270 'playable_in_embed': True,
2271 'live_status': 'not_live',
2272 'upload_date': '20220102',
2273 'like_count': int,
2274 'availability': 'public',
2275 'channel': 'Leon Nguyen',
2276 'thumbnail': 'https://i.ytimg.com/vi_webp/2NUZ8W2llS4/maxresdefault.webp',
2277 'comment_count': int,
2278 'channel_follower_count': int
2279 },
2280 'params': {'compat_opts': ['no-youtube-prefer-utc-upload-date']}
992f9a73 2281 }, {
2282 # date text is premiered video, ensure upload date in UTC (published 1641172509)
2283 'url': 'https://www.youtube.com/watch?v=mzZzzBU6lrM',
2284 'info_dict': {
2285 'id': 'mzZzzBU6lrM',
2286 'ext': 'mp4',
2287 'title': 'I Met GeorgeNotFound In Real Life...',
2288 'description': 'md5:cca98a355c7184e750f711f3a1b22c84',
2289 'uploader': 'Quackity',
2290 'uploader_id': 'QuackityHQ',
2291 'uploader_url': 'http://www.youtube.com/user/QuackityHQ',
2292 'channel_id': 'UC_8NknAFiyhOUaZqHR3lq3Q',
2293 'channel_url': 'https://www.youtube.com/channel/UC_8NknAFiyhOUaZqHR3lq3Q',
2294 'duration': 955,
2295 'view_count': int,
2296 'age_limit': 0,
2297 'categories': ['Entertainment'],
2298 'tags': 'count:26',
2299 'playable_in_embed': True,
2300 'live_status': 'not_live',
2301 'release_timestamp': 1641172509,
2302 'release_date': '20220103',
2303 'upload_date': '20220103',
2304 'like_count': int,
2305 'availability': 'public',
2306 'channel': 'Quackity',
2307 'thumbnail': 'https://i.ytimg.com/vi/mzZzzBU6lrM/maxresdefault.jpg',
2308 'channel_follower_count': int
2309 }
2310 },
2311 { # continuous livestream. Microformat upload date should be preferred.
2312 # Upload date was 2021-06-19 (not UTC), while stream start is 2021-11-27
2313 'url': 'https://www.youtube.com/watch?v=kgx4WGK0oNU',
2314 'info_dict': {
2315 'id': 'kgx4WGK0oNU',
2316 'title': r're:jazz\/lofi hip hop radio🌱chill beats to relax\/study to \[LIVE 24\/7\] \d{4}-\d{2}-\d{2} \d{2}:\d{2}',
2317 'ext': 'mp4',
2318 'channel_id': 'UC84whx2xxsiA1gXHXXqKGOA',
2319 'availability': 'public',
2320 'age_limit': 0,
2321 'release_timestamp': 1637975704,
2322 'upload_date': '20210619',
2323 'channel_url': 'https://www.youtube.com/channel/UC84whx2xxsiA1gXHXXqKGOA',
2324 'live_status': 'is_live',
2325 'thumbnail': 'https://i.ytimg.com/vi/kgx4WGK0oNU/maxresdefault.jpg',
2326 'uploader': '阿鲍Abao',
2327 'uploader_url': 'http://www.youtube.com/channel/UC84whx2xxsiA1gXHXXqKGOA',
2328 'channel': 'Abao in Tokyo',
2329 'channel_follower_count': int,
2330 'release_date': '20211127',
2331 'tags': 'count:39',
2332 'categories': ['People & Blogs'],
2333 'like_count': int,
2334 'uploader_id': 'UC84whx2xxsiA1gXHXXqKGOA',
2335 'view_count': int,
2336 'playable_in_embed': True,
2337 'description': 'md5:2ef1d002cad520f65825346e2084e49d',
867c66ff 2338 'concurrent_view_count': int,
992f9a73 2339 },
2340 'params': {'skip_download': True}
6e634cbe 2341 }, {
2342 # Story. Requires specific player params to work.
ee27297f 2343 'url': 'https://www.youtube.com/watch?v=vv8qTUWmulI',
6e634cbe 2344 'info_dict': {
ee27297f 2345 'id': 'vv8qTUWmulI',
6e634cbe 2346 'ext': 'mp4',
ee27297f 2347 'availability': 'unlisted',
2348 'view_count': int,
2349 'channel_id': 'UCzIZ8HrzDgc-pNQDUG6avBA',
2350 'upload_date': '20220526',
2351 'categories': ['Education'],
2352 'title': 'Story',
2353 'channel': 'IT\'S HISTORY',
2354 'description': '',
2355 'uploader_id': 'BlastfromthePast',
2356 'duration': 12,
2357 'uploader': 'IT\'S HISTORY',
6e634cbe 2358 'playable_in_embed': True,
6e634cbe 2359 'age_limit': 0,
6e634cbe 2360 'live_status': 'not_live',
ee27297f 2361 'tags': [],
2362 'thumbnail': 'https://i.ytimg.com/vi_webp/vv8qTUWmulI/maxresdefault.webp',
2363 'uploader_url': 'http://www.youtube.com/user/BlastfromthePast',
2364 'channel_url': 'https://www.youtube.com/channel/UCzIZ8HrzDgc-pNQDUG6avBA',
12a1b225
A
2365 },
2366 'skip': 'stories get removed after some period of time',
ee27297f 2367 }, {
2368 'url': 'https://www.youtube.com/watch?v=tjjjtzRLHvA',
2369 'info_dict': {
2370 'id': 'tjjjtzRLHvA',
2371 'ext': 'mp4',
2372 'title': 'ハッシュタグ無し };if window.ytcsi',
2373 'upload_date': '20220323',
2374 'like_count': int,
2375 'availability': 'unlisted',
2376 'channel': 'nao20010128nao',
2377 'thumbnail': 'https://i.ytimg.com/vi_webp/tjjjtzRLHvA/maxresdefault.webp',
2378 'age_limit': 0,
2379 'uploader': 'nao20010128nao',
2380 'uploader_id': 'nao20010128nao',
2381 'categories': ['Music'],
6e634cbe 2382 'view_count': int,
2383 'description': '',
ee27297f 2384 'channel_url': 'https://www.youtube.com/channel/UCdqltm_7iv1Vs6kp6Syke5A',
2385 'channel_id': 'UCdqltm_7iv1Vs6kp6Syke5A',
2386 'live_status': 'not_live',
2387 'playable_in_embed': True,
2388 'channel_follower_count': int,
2389 'duration': 6,
2390 'tags': [],
2391 'uploader_url': 'http://www.youtube.com/user/nao20010128nao',
6e634cbe 2392 }
c26f9b99 2393 }, {
2394 # Prefer primary title+description language metadata by default
2395 # Do not prefer translated description if primary is empty
2396 'url': 'https://www.youtube.com/watch?v=el3E4MbxRqQ',
2397 'info_dict': {
2398 'id': 'el3E4MbxRqQ',
2399 'ext': 'mp4',
2400 'title': 'dlp test video 2 - primary sv no desc',
2401 'description': '',
2402 'channel': 'cole-dlp-test-acc',
2403 'tags': [],
2404 'view_count': int,
2405 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2406 'like_count': int,
2407 'playable_in_embed': True,
2408 'availability': 'unlisted',
2409 'thumbnail': 'https://i.ytimg.com/vi_webp/el3E4MbxRqQ/maxresdefault.webp',
2410 'age_limit': 0,
2411 'duration': 5,
2412 'uploader_id': 'UCiu-3thuViMebBjw_5nWYrA',
2413 'uploader_url': 'http://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2414 'live_status': 'not_live',
2415 'upload_date': '20220908',
2416 'categories': ['People & Blogs'],
2417 'uploader': 'cole-dlp-test-acc',
2418 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
2419 },
2420 'params': {'skip_download': True}
2421 }, {
2422 # Extractor argument: prefer translated title+description
2423 'url': 'https://www.youtube.com/watch?v=gHKT4uU8Zng',
2424 'info_dict': {
2425 'id': 'gHKT4uU8Zng',
2426 'ext': 'mp4',
2427 'channel': 'cole-dlp-test-acc',
2428 'tags': [],
2429 'duration': 5,
2430 'live_status': 'not_live',
2431 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
2432 'upload_date': '20220728',
2433 'uploader_id': 'UCiu-3thuViMebBjw_5nWYrA',
2434 'view_count': int,
2435 'categories': ['People & Blogs'],
2436 'thumbnail': 'https://i.ytimg.com/vi_webp/gHKT4uU8Zng/maxresdefault.webp',
2437 'title': 'dlp test video title translated (fr)',
2438 'availability': 'public',
2439 'uploader': 'cole-dlp-test-acc',
2440 'age_limit': 0,
2441 'description': 'dlp test video description translated (fr)',
2442 'playable_in_embed': True,
2443 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2444 'uploader_url': 'http://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
2445 },
2446 'params': {'skip_download': True, 'extractor_args': {'youtube': {'lang': ['fr']}}},
2447 'expected_warnings': [r'Preferring "fr" translated fields'],
a4166234 2448 }, {
2449 'note': '6 channel audio',
2450 'url': 'https://www.youtube.com/watch?v=zgdo7-RRjgo',
2451 'only_matching': True,
6e634cbe 2452 }
2eb88d95
PH
2453 ]
2454
f2e8dbcc 2455 _WEBPAGE_TESTS = [
2456 # YouTube <object> embed
2457 {
2458 'url': 'http://www.improbable.com/2017/04/03/untrained-modern-youths-and-ancient-masters-in-selfie-portraits/',
2459 'md5': '873c81d308b979f0e23ee7e620b312a3',
2460 'info_dict': {
2461 'id': 'msN87y-iEx0',
2462 'ext': 'mp4',
2463 'title': 'Feynman: Mirrors FUN TO IMAGINE 6',
2464 'upload_date': '20080526',
2465 'description': 'md5:873c81d308b979f0e23ee7e620b312a3',
2466 'uploader': 'Christopher Sykes',
2467 'uploader_id': 'ChristopherJSykes',
2468 'age_limit': 0,
2469 'tags': ['feynman', 'mirror', 'science', 'physics', 'imagination', 'fun', 'cool', 'puzzle'],
2470 'channel_id': 'UCCeo--lls1vna5YJABWAcVA',
2471 'playable_in_embed': True,
2472 'thumbnail': 'https://i.ytimg.com/vi/msN87y-iEx0/hqdefault.jpg',
2473 'like_count': int,
2474 'comment_count': int,
2475 'channel': 'Christopher Sykes',
2476 'live_status': 'not_live',
2477 'channel_url': 'https://www.youtube.com/channel/UCCeo--lls1vna5YJABWAcVA',
2478 'availability': 'public',
2479 'duration': 195,
2480 'view_count': int,
2481 'categories': ['Science & Technology'],
2482 'channel_follower_count': int,
2483 'uploader_url': 'http://www.youtube.com/user/ChristopherJSykes',
2484 },
2485 'params': {
2486 'skip_download': True,
2487 }
2488 },
2489 ]
2490
201c1459 2491 @classmethod
2492 def suitable(cls, url):
4dfbf869 2493 from ..utils import parse_qs
2494
201c1459 2495 qs = parse_qs(url)
2496 if qs.get('list', [None])[0]:
2497 return False
86e5f3ed 2498 return super().suitable(url)
201c1459 2499
e0df6211 2500 def __init__(self, *args, **kwargs):
86e5f3ed 2501 super().__init__(*args, **kwargs)
545cc85d 2502 self._code_cache = {}
83799698 2503 self._player_cache = {}
e0df6211 2504
4d37720a 2505 def _prepare_live_from_start_formats(self, formats, video_id, live_start_time, url, webpage_url, smuggled_data, is_live):
adbc4ec4 2506 lock = threading.Lock()
185bf310 2507 start_time = time.time()
adbc4ec4
THD
2508 formats = [f for f in formats if f.get('is_from_start')]
2509
185bf310 2510 def refetch_manifest(format_id, delay):
2511 nonlocal formats, start_time, is_live
2512 if time.time() <= start_time + delay:
adbc4ec4
THD
2513 return
2514
2515 _, _, prs, player_url = self._download_player_responses(url, smuggled_data, video_id, webpage_url)
2516 video_details = traverse_obj(
2517 prs, (..., 'videoDetails'), expected_type=dict, default=[])
2518 microformats = traverse_obj(
2519 prs, (..., 'microformat', 'playerMicroformatRenderer'),
2520 expected_type=dict, default=[])
4d37720a
L
2521 _, live_status, _, formats, _ = self._list_formats(video_id, microformats, video_details, prs, player_url)
2522 is_live = live_status == 'is_live'
185bf310 2523 start_time = time.time()
adbc4ec4 2524
185bf310 2525 def mpd_feed(format_id, delay):
adbc4ec4
THD
2526 """
2527 @returns (manifest_url, manifest_stream_number, is_live) or None
2528 """
2529 with lock:
185bf310 2530 refetch_manifest(format_id, delay)
adbc4ec4
THD
2531
2532 f = next((f for f in formats if f['format_id'] == format_id), None)
2533 if not f:
185bf310 2534 if not is_live:
2535 self.to_screen(f'{video_id}: Video is no longer live')
2536 else:
2537 self.report_warning(
2538 f'Cannot find refreshed manifest for format {format_id}{bug_reports_message()}')
adbc4ec4
THD
2539 return None
2540 return f['manifest_url'], f['manifest_stream_number'], is_live
2541
2542 for f in formats:
4d37720a
L
2543 f['is_live'] = is_live
2544 gen = functools.partial(self._live_dash_fragments, video_id, f['format_id'],
2545 live_start_time, mpd_feed, not is_live and f.copy())
2546 if is_live:
2547 f['fragments'] = gen
2548 f['protocol'] = 'http_dash_segments_generator'
2549 else:
2550 f['fragments'] = LazyList(gen({}))
2551 del f['is_from_start']
adbc4ec4 2552
4d37720a 2553 def _live_dash_fragments(self, video_id, format_id, live_start_time, mpd_feed, manifestless_orig_fmt, ctx):
adbc4ec4
THD
2554 FETCH_SPAN, MAX_DURATION = 5, 432000
2555
2556 mpd_url, stream_number, is_live = None, None, True
2557
2558 begin_index = 0
2559 download_start_time = ctx.get('start') or time.time()
2560
2561 lack_early_segments = download_start_time - (live_start_time or download_start_time) > MAX_DURATION
2562 if lack_early_segments:
2563 self.report_warning(bug_reports_message(
2564 'Starting download from the last 120 hours of the live stream since '
2565 'YouTube does not have data before that. If you think this is wrong,'), only_once=True)
2566 lack_early_segments = True
2567
2568 known_idx, no_fragment_score, last_segment_url = begin_index, 0, None
2569 fragments, fragment_base_url = None, None
2570
a539f065 2571 def _extract_sequence_from_mpd(refresh_sequence, immediate):
adbc4ec4
THD
2572 nonlocal mpd_url, stream_number, is_live, no_fragment_score, fragments, fragment_base_url
2573 # Obtain from MPD's maximum seq value
2574 old_mpd_url = mpd_url
185bf310 2575 last_error = ctx.pop('last_error', None)
14f25df2 2576 expire_fast = immediate or last_error and isinstance(last_error, urllib.error.HTTPError) and last_error.code == 403
185bf310 2577 mpd_url, stream_number, is_live = (mpd_feed(format_id, 5 if expire_fast else 18000)
2578 or (mpd_url, stream_number, False))
2579 if not refresh_sequence:
2580 if expire_fast and not is_live:
2581 return False, last_seq
2582 elif old_mpd_url == mpd_url:
2583 return True, last_seq
4d37720a
L
2584 if manifestless_orig_fmt:
2585 fmt_info = manifestless_orig_fmt
2586 else:
2587 try:
2588 fmts, _ = self._extract_mpd_formats_and_subtitles(
2589 mpd_url, None, note=False, errnote=False, fatal=False)
2590 except ExtractorError:
2591 fmts = None
2592 if not fmts:
2593 no_fragment_score += 2
2594 return False, last_seq
2595 fmt_info = next(x for x in fmts if x['manifest_stream_number'] == stream_number)
adbc4ec4
THD
2596 fragments = fmt_info['fragments']
2597 fragment_base_url = fmt_info['fragment_base_url']
2598 assert fragment_base_url
2599
2600 _last_seq = int(re.search(r'(?:/|^)sq/(\d+)', fragments[-1]['path']).group(1))
2601 return True, _last_seq
2602
4d37720a 2603 self.write_debug(f'[{video_id}] Generating fragments for format {format_id}')
adbc4ec4
THD
2604 while is_live:
2605 fetch_time = time.time()
2606 if no_fragment_score > 30:
2607 return
2608 if last_segment_url:
2609 # Obtain from "X-Head-Seqnum" header value from each segment
2610 try:
2611 urlh = self._request_webpage(
2612 last_segment_url, None, note=False, errnote=False, fatal=False)
2613 except ExtractorError:
2614 urlh = None
2615 last_seq = try_get(urlh, lambda x: int_or_none(x.headers['X-Head-Seqnum']))
2616 if last_seq is None:
a539f065 2617 no_fragment_score += 2
adbc4ec4
THD
2618 last_segment_url = None
2619 continue
2620 else:
a539f065
LNO
2621 should_continue, last_seq = _extract_sequence_from_mpd(True, no_fragment_score > 15)
2622 no_fragment_score += 2
185bf310 2623 if not should_continue:
adbc4ec4
THD
2624 continue
2625
2626 if known_idx > last_seq:
2627 last_segment_url = None
2628 continue
2629
2630 last_seq += 1
2631
2632 if begin_index < 0 and known_idx < 0:
2633 # skip from the start when it's negative value
2634 known_idx = last_seq + begin_index
2635 if lack_early_segments:
2636 known_idx = max(known_idx, last_seq - int(MAX_DURATION // fragments[-1]['duration']))
2637 try:
2638 for idx in range(known_idx, last_seq):
2639 # do not update sequence here or you'll get skipped some part of it
a539f065 2640 should_continue, _ = _extract_sequence_from_mpd(False, False)
185bf310 2641 if not should_continue:
adbc4ec4
THD
2642 known_idx = idx - 1
2643 raise ExtractorError('breaking out of outer loop')
2644 last_segment_url = urljoin(fragment_base_url, 'sq/%d' % idx)
2645 yield {
2646 'url': last_segment_url,
36195c44 2647 'fragment_count': last_seq,
adbc4ec4
THD
2648 }
2649 if known_idx == last_seq:
2650 no_fragment_score += 5
2651 else:
2652 no_fragment_score = 0
2653 known_idx = last_seq
2654 except ExtractorError:
2655 continue
2656
4d37720a
L
2657 if manifestless_orig_fmt:
2658 # Stop at the first iteration if running for post-live manifestless;
2659 # fragment count no longer increase since it starts
2660 break
2661
adbc4ec4
THD
2662 time.sleep(max(0, FETCH_SPAN + fetch_time - time.time()))
2663
b6de707d 2664 def _extract_player_url(self, *ytcfgs, webpage=None):
2665 player_url = traverse_obj(
2666 ytcfgs, (..., 'PLAYER_JS_URL'), (..., 'WEB_PLAYER_CONTEXT_CONFIGS', ..., 'jsUrl'),
14f25df2 2667 get_all=False, expected_type=str)
11f9be09 2668 if not player_url:
b6de707d 2669 return
60f393e4 2670 return urljoin('https://www.youtube.com', player_url)
109dd3b2 2671
b6de707d 2672 def _download_player_url(self, video_id, fatal=False):
2673 res = self._download_webpage(
2674 'https://www.youtube.com/iframe_api',
2675 note='Downloading iframe API JS', video_id=video_id, fatal=fatal)
2676 if res:
2677 player_version = self._search_regex(
2678 r'player\\?/([0-9a-fA-F]{8})\\?/', res, 'player version', fatal=fatal)
2679 if player_version:
2680 return f'https://www.youtube.com/s/player/{player_version}/player_ias.vflset/en_US/base.js'
2681
60064c53
PH
2682 def _signature_cache_id(self, example_sig):
2683 """ Return a string representation of a signature """
14f25df2 2684 return '.'.join(str(len(part)) for part in example_sig.split('.'))
60064c53 2685
e40c758c
S
2686 @classmethod
2687 def _extract_player_info(cls, player_url):
2688 for player_re in cls._PLAYER_INFO_RE:
2689 id_m = re.search(player_re, player_url)
2690 if id_m:
2691 break
2692 else:
c081b35c 2693 raise ExtractorError('Cannot identify player %r' % player_url)
545cc85d 2694 return id_m.group('id')
e40c758c 2695
404f611f 2696 def _load_player(self, video_id, player_url, fatal=True):
109dd3b2 2697 player_id = self._extract_player_info(player_url)
2698 if player_id not in self._code_cache:
1276a43a 2699 code = self._download_webpage(
109dd3b2 2700 player_url, video_id, fatal=fatal,
2701 note='Downloading player ' + player_id,
2702 errnote='Download of %s failed' % player_url)
1276a43a 2703 if code:
2704 self._code_cache[player_id] = code
404f611f 2705 return self._code_cache.get(player_id)
109dd3b2 2706
e40c758c 2707 def _extract_signature_function(self, video_id, player_url, example_sig):
545cc85d 2708 player_id = self._extract_player_info(player_url)
e0df6211 2709
c4417ddb 2710 # Read from filesystem cache
86e5f3ed 2711 func_id = f'js_{player_id}_{self._signature_cache_id(example_sig)}'
c4417ddb 2712 assert os.path.basename(func_id) == func_id
a0e07d31 2713
ae61d108 2714 self.write_debug(f'Extracting signature function {func_id}')
580ce007 2715 cache_spec, code = self.cache.load('youtube-sigfuncs', func_id), None
83799698 2716
580ce007 2717 if not cache_spec:
2718 code = self._load_player(video_id, player_url)
404f611f 2719 if code:
109dd3b2 2720 res = self._parse_sig_js(code)
ac668111 2721 test_string = ''.join(map(chr, range(len(example_sig))))
580ce007 2722 cache_spec = [ord(c) for c in res(test_string)]
9809740b 2723 self.cache.store('youtube-sigfuncs', func_id, cache_spec)
580ce007 2724
2725 return lambda s: ''.join(s[i] for i in cache_spec)
83799698 2726
60064c53 2727 def _print_sig_code(self, func, example_sig):
404f611f 2728 if not self.get_param('youtube_print_sig_code'):
2729 return
2730
edf3e38e
PH
2731 def gen_sig_code(idxs):
2732 def _genslice(start, end, step):
78caa52a 2733 starts = '' if start == 0 else str(start)
8bcc8756 2734 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
69ea8ca4 2735 steps = '' if step == 1 else (':%d' % step)
86e5f3ed 2736 return f's[{starts}{ends}{steps}]'
edf3e38e
PH
2737
2738 step = None
7af808a5
PH
2739 # Quelch pyflakes warnings - start will be set when step is set
2740 start = '(Never used)'
edf3e38e
PH
2741 for i, prev in zip(idxs[1:], idxs[:-1]):
2742 if step is not None:
2743 if i - prev == step:
2744 continue
2745 yield _genslice(start, prev, step)
2746 step = None
2747 continue
2748 if i - prev in [-1, 1]:
2749 step = i - prev
2750 start = prev
2751 continue
2752 else:
78caa52a 2753 yield 's[%d]' % prev
edf3e38e 2754 if step is None:
78caa52a 2755 yield 's[%d]' % i
edf3e38e
PH
2756 else:
2757 yield _genslice(start, i, step)
2758
ac668111 2759 test_string = ''.join(map(chr, range(len(example_sig))))
c705320f 2760 cache_res = func(test_string)
edf3e38e 2761 cache_spec = [ord(c) for c in cache_res]
78caa52a 2762 expr_code = ' + '.join(gen_sig_code(cache_spec))
60064c53 2763 signature_id_tuple = '(%s)' % (
14f25df2 2764 ', '.join(str(len(p)) for p in example_sig.split('.')))
69ea8ca4 2765 code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
78caa52a 2766 ' return %s\n') % (signature_id_tuple, expr_code)
69ea8ca4 2767 self.to_screen('Extracted signature function:\n' + code)
edf3e38e 2768
e0df6211
PH
2769 def _parse_sig_js(self, jscode):
2770 funcname = self._search_regex(
abefc03f
S
2771 (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2772 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
858a65ec
P
2773 r'\bm=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(h\.s\)\)',
2774 r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(c\)\)',
2775 r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\);[a-zA-Z0-9$]{2}\.[a-zA-Z0-9$]{2}\(a,\d+\)',
2776 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*\)',
31ce6e99 2777 r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
abefc03f
S
2778 # Obsolete patterns
2779 r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
9a47fa35 2780 r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
abefc03f
S
2781 r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2782 r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2783 r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2784 r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2785 r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
2786 r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
3c90cc8b 2787 jscode, 'Initial JS player signature function name', group='sig')
2b25cb5d
PH
2788
2789 jsi = JSInterpreter(jscode)
2790 initial_function = jsi.extract_function(funcname)
e0df6211
PH
2791 return lambda s: initial_function([s])
2792
580ce007 2793 def _cached(self, func, *cache_id):
2794 def inner(*args, **kwargs):
2795 if cache_id not in self._player_cache:
2796 try:
2797 self._player_cache[cache_id] = func(*args, **kwargs)
2798 except ExtractorError as e:
2799 self._player_cache[cache_id] = e
2800 except Exception as e:
2801 self._player_cache[cache_id] = ExtractorError(traceback.format_exc(), cause=e)
2802
2803 ret = self._player_cache[cache_id]
2804 if isinstance(ret, Exception):
2805 raise ret
2806 return ret
2807 return inner
2808
545cc85d 2809 def _decrypt_signature(self, s, video_id, player_url):
257a2501 2810 """Turn the encrypted s field into a working signature"""
580ce007 2811 extract_sig = self._cached(
2812 self._extract_signature_function, 'sig', player_url, self._signature_cache_id(s))
2813 func = extract_sig(video_id, player_url, s)
2814 self._print_sig_code(func, s)
2815 return func(s)
404f611f 2816
2817 def _decrypt_nsig(self, s, video_id, player_url):
2818 """Turn the encrypted n field into a working signature"""
2819 if player_url is None:
2820 raise ExtractorError('Cannot decrypt nsig without player_url')
60f393e4 2821 player_url = urljoin('https://www.youtube.com', player_url)
404f611f 2822
b505e851 2823 try:
2824 jsi, player_id, func_code = self._extract_n_function_code(video_id, player_url)
2825 except ExtractorError as e:
2826 raise ExtractorError('Unable to extract nsig function code', cause=e)
580ce007 2827 if self.get_param('youtube_print_sig_code'):
2828 self.to_screen(f'Extracted nsig function from {player_id}:\n{func_code[1]}\n')
404f611f 2829
25836db6 2830 try:
2831 extract_nsig = self._cached(self._extract_n_function_from_code, 'nsig func', player_url)
2832 ret = extract_nsig(jsi, func_code)(s)
2833 except JSInterpreter.Exception as e:
2834 try:
992dc6b4 2835 jsi = PhantomJSwrapper(self, timeout=5000)
25836db6 2836 except ExtractorError:
2837 raise e
2838 self.report_warning(
2839 f'Native nsig extraction failed: Trying with PhantomJS\n'
2840 f' n = {s} ; player = {player_url}', video_id)
0468a3b3 2841 self.write_debug(e, only_once=True)
25836db6 2842
2843 args, func_body = func_code
2844 ret = jsi.execute(
2845 f'console.log(function({", ".join(args)}) {{ {func_body} }}({s!r}));',
2846 video_id=video_id, note='Executing signature code').strip()
580ce007 2847
2848 self.write_debug(f'Decrypted nsig {s} => {ret}')
2849 return ret
2850
90a1df30 2851 def _extract_n_function_name(self, jscode):
2852 funcname, idx = self._search_regex(
2853 r'\.get\("n"\)\)&&\(b=(?P<nfunc>[a-zA-Z0-9$]+)(?:\[(?P<idx>\d+)\])?\([a-zA-Z0-9]\)',
2854 jscode, 'Initial JS player n function name', group=('nfunc', 'idx'))
2855 if not idx:
2856 return funcname
2857
2858 return json.loads(js_to_json(self._search_regex(
2859 rf'var {re.escape(funcname)}\s*=\s*(\[.+?\]);', jscode,
2860 f'Initial JS player n function list ({funcname}.{idx})')))[int(idx)]
2861
580ce007 2862 def _extract_n_function_code(self, video_id, player_url):
404f611f 2863 player_id = self._extract_player_info(player_url)
05deb747 2864 func_code = self.cache.load('youtube-nsig', player_id, min_ver='2022.09.1')
580ce007 2865 jscode = func_code or self._load_player(video_id, player_url)
2866 jsi = JSInterpreter(jscode)
404f611f 2867
2868 if func_code:
580ce007 2869 return jsi, player_id, func_code
404f611f 2870
b505e851 2871 func_name = self._extract_n_function_name(jscode)
2872
2873 # For redundancy
2874 func_code = self._search_regex(
2875 r'''(?xs)%s\s*=\s*function\s*\((?P<var>[\w$]+)\)\s*
2876 # NB: The end of the regex is intentionally kept strict
2877 {(?P<code>.+?}\s*return\ [\w$]+.join\(""\))};''' % func_name,
2878 jscode, 'nsig function', group=('var', 'code'), default=None)
2879 if func_code:
2880 func_code = ([func_code[0]], func_code[1])
2881 else:
2882 self.write_debug('Extracting nsig function with jsinterp')
2883 func_code = jsi.extract_function_code(func_name)
2884
580ce007 2885 self.cache.store('youtube-nsig', player_id, func_code)
2886 return jsi, player_id, func_code
2887
2888 def _extract_n_function_from_code(self, jsi, func_code):
8f53dc44 2889 func = jsi.extract_function_from_code(*func_code)
f6ca640b 2890
580ce007 2891 def extract_nsig(s):
25836db6 2892 try:
2893 ret = func([s])
2894 except JSInterpreter.Exception:
2895 raise
2896 except Exception as e:
2897 raise JSInterpreter.Exception(traceback.format_exc(), cause=e)
2898
f6ca640b 2899 if ret.startswith('enhanced_except_'):
25836db6 2900 raise JSInterpreter.Exception('Signature function returned an exception')
f6ca640b 2901 return ret
580ce007 2902
2903 return extract_nsig
e0df6211 2904
109dd3b2 2905 def _extract_signature_timestamp(self, video_id, player_url, ytcfg=None, fatal=False):
2906 """
2907 Extract signatureTimestamp (sts)
2908 Required to tell API what sig/player version is in use.
2909 """
2910 sts = None
2911 if isinstance(ytcfg, dict):
2912 sts = int_or_none(ytcfg.get('STS'))
2913
2914 if not sts:
2915 # Attempt to extract from player
2916 if player_url is None:
2917 error_msg = 'Cannot extract signature timestamp without player_url.'
2918 if fatal:
2919 raise ExtractorError(error_msg)
2920 self.report_warning(error_msg)
2921 return
404f611f 2922 code = self._load_player(video_id, player_url, fatal=fatal)
2923 if code:
109dd3b2 2924 sts = int_or_none(self._search_regex(
2925 r'(?:signatureTimestamp|sts)\s*:\s*(?P<sts>[0-9]{5})', code,
2926 'JS player signature timestamp', group='sts', fatal=fatal))
2927 return sts
2928
11f9be09 2929 def _mark_watched(self, video_id, player_responses):
06cc8f10
B
2930 for is_full, key in enumerate(('videostatsPlaybackUrl', 'videostatsWatchtimeUrl')):
2931 label = 'fully ' if is_full else ''
2932 url = get_first(player_responses, ('playbackTracking', key, 'baseUrl'),
2933 expected_type=url_or_none)
2934 if not url:
2935 self.report_warning(f'Unable to mark {label}watched')
2936 return
14f25df2 2937 parsed_url = urllib.parse.urlparse(url)
2938 qs = urllib.parse.parse_qs(parsed_url.query)
06cc8f10
B
2939
2940 # cpn generation algorithm is reverse engineered from base.js.
2941 # In fact it works even with dummy cpn.
2942 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
2943 cpn = ''.join(CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16))
2944
2945 # # more consistent results setting it to right before the end
2946 video_length = [str(float((qs.get('len') or ['1.5'])[0]) - 1)]
2947
2948 qs.update({
2949 'ver': ['2'],
2950 'cpn': [cpn],
2951 'cmt': video_length,
2952 'el': 'detailpage', # otherwise defaults to "shorts"
2953 })
2954
2955 if is_full:
2956 # these seem to mark watchtime "history" in the real world
2957 # they're required, so send in a single value
2958 qs.update({
5318156f 2959 'st': 0,
06cc8f10
B
2960 'et': video_length,
2961 })
2962
14f25df2 2963 url = urllib.parse.urlunparse(
2964 parsed_url._replace(query=urllib.parse.urlencode(qs, True)))
06cc8f10
B
2965
2966 self._download_webpage(
2967 url, video_id, f'Marking {label}watched',
2968 'Unable to mark watched', fatal=False)
d77ab8e2 2969
bfd973ec 2970 @classmethod
2971 def _extract_from_webpage(cls, url, webpage):
2972 # Invidious Instances
2973 # https://github.com/yt-dlp/yt-dlp/issues/195
2974 # https://github.com/iv-org/invidious/pull/1730
2975 mobj = re.search(
2976 r'<link rel="alternate" href="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"',
2977 webpage)
2978 if mobj:
2979 yield cls.url_result(mobj.group('url'), cls)
2980 raise cls.StopExtraction()
2981
2982 yield from super()._extract_from_webpage(url, webpage)
66c9fa36
S
2983
2984 # lazyYT YouTube embed
bfd973ec 2985 for id_ in re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage):
2986 yield cls.url_result(unescapeHTML(id_), cls, id_)
66c9fa36
S
2987
2988 # Wordpress "YouTube Video Importer" plugin
bfd973ec 2989 for m in re.findall(r'''(?x)<div[^>]+
2990 class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
2991 data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage):
2992 yield cls.url_result(m[-1], cls, m[-1])
66c9fa36 2993
97665381
PH
2994 @classmethod
2995 def extract_id(cls, url):
ae61d108 2996 video_id = cls.get_temp_id(url)
2997 if not video_id:
2998 raise ExtractorError(f'Invalid URL: {url}')
2999 return video_id
c5e8d7af 3000
7c365c21 3001 def _extract_chapters_from_json(self, data, duration):
3002 chapter_list = traverse_obj(
3003 data, (
3004 'playerOverlays', 'playerOverlayRenderer', 'decoratedPlayerBarRenderer',
3005 'decoratedPlayerBarRenderer', 'playerBar', 'chapteredPlayerBarRenderer', 'chapters'
3006 ), expected_type=list)
3007
3008 return self._extract_chapters(
3009 chapter_list,
3010 chapter_time=lambda chapter: float_or_none(
3011 traverse_obj(chapter, ('chapterRenderer', 'timeRangeStartMillis')), scale=1000),
3012 chapter_title=lambda chapter: traverse_obj(
3013 chapter, ('chapterRenderer', 'title', 'simpleText'), expected_type=str),
3014 duration=duration)
3015
3016 def _extract_chapters_from_engagement_panel(self, data, duration):
3017 content_list = traverse_obj(
8bdd16b4 3018 data,
7c365c21 3019 ('engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'macroMarkersListRenderer', 'contents'),
da503b7a 3020 expected_type=list, default=[])
052e1350 3021 chapter_time = lambda chapter: parse_duration(self._get_text(chapter, 'timeDescription'))
3022 chapter_title = lambda chapter: self._get_text(chapter, 'title')
7c365c21 3023
1890fc63 3024 return next(filter(None, (
3025 self._extract_chapters(traverse_obj(contents, (..., 'macroMarkersListItemRenderer')),
3026 chapter_time, chapter_title, duration)
3027 for contents in content_list)), [])
7c365c21 3028
1890fc63 3029 def _extract_chapters_from_description(self, description, duration):
2e30b46f 3030 duration_re = r'(?:\d+:)?\d{1,2}:\d{2}'
3031 sep_re = r'(?m)^\s*(%s)\b\W*\s(%s)\s*$'
1890fc63 3032 return self._extract_chapters(
2e30b46f 3033 re.findall(sep_re % (duration_re, r'.+?'), description or ''),
1890fc63 3034 chapter_time=lambda x: parse_duration(x[0]), chapter_title=lambda x: x[1],
2e30b46f 3035 duration=duration, strict=False) or self._extract_chapters(
3036 re.findall(sep_re % (r'.+?', duration_re), description or ''),
3037 chapter_time=lambda x: parse_duration(x[1]), chapter_title=lambda x: x[0],
1890fc63 3038 duration=duration, strict=False)
84213ea8 3039
1890fc63 3040 def _extract_chapters(self, chapter_list, chapter_time, chapter_title, duration, strict=True):
3041 if not duration:
3042 return
3043 chapter_list = [{
3044 'start_time': chapter_time(chapter),
3045 'title': chapter_title(chapter),
3046 } for chapter in chapter_list or []]
3047 if not strict:
3048 chapter_list.sort(key=lambda c: c['start_time'] or 0)
3049
a3976e07 3050 chapters = [{'start_time': 0}]
1890fc63 3051 for idx, chapter in enumerate(chapter_list):
a3976e07 3052 if chapter['start_time'] is None:
1890fc63 3053 self.report_warning(f'Incomplete chapter {idx}')
3054 elif chapters[-1]['start_time'] <= chapter['start_time'] <= duration:
1890fc63 3055 chapters.append(chapter)
709ee214 3056 elif chapter not in chapters:
3057 self.report_warning(
3058 f'Invalid start time ({chapter["start_time"]} < {chapters[-1]["start_time"]}) for chapter "{chapter["title"]}"')
a3976e07 3059 return chapters[1:]
84213ea8 3060
a1c5d2ca
M
3061 def _extract_comment(self, comment_renderer, parent=None):
3062 comment_id = comment_renderer.get('commentId')
3063 if not comment_id:
3064 return
fe93e2c4 3065
052e1350 3066 text = self._get_text(comment_renderer, 'contentText')
fe93e2c4 3067
c26f9b99 3068 # Timestamp is an estimate calculated from the current time and time_text
3069 time_text = self._get_text(comment_renderer, 'publishedTimeText') or ''
3070 timestamp = self._parse_time_text(time_text)
3071
052e1350 3072 author = self._get_text(comment_renderer, 'authorText')
a1c5d2ca 3073 author_id = try_get(comment_renderer,
14f25df2 3074 lambda x: x['authorEndpoint']['browseEndpoint']['browseId'], str)
fe93e2c4 3075
49bd8c66 3076 votes = parse_count(try_get(comment_renderer, (lambda x: x['voteCount']['simpleText'],
14f25df2 3077 lambda x: x['likeCount']), str)) or 0
a1c5d2ca 3078 author_thumbnail = try_get(comment_renderer,
14f25df2 3079 lambda x: x['authorThumbnail']['thumbnails'][-1]['url'], str)
a1c5d2ca
M
3080
3081 author_is_uploader = try_get(comment_renderer, lambda x: x['authorIsChannelOwner'], bool)
97524332 3082 is_favorited = 'creatorHeart' in (try_get(
3083 comment_renderer, lambda x: x['actionButtons']['commentActionButtonsRenderer'], dict) or {})
a1c5d2ca
M
3084 return {
3085 'id': comment_id,
3086 'text': text,
d92f5d5a 3087 'timestamp': timestamp,
a1c5d2ca
M
3088 'time_text': time_text,
3089 'like_count': votes,
97524332 3090 'is_favorited': is_favorited,
a1c5d2ca
M
3091 'author': author,
3092 'author_id': author_id,
3093 'author_thumbnail': author_thumbnail,
3094 'author_is_uploader': author_is_uploader,
3095 'parent': parent or 'root'
3096 }
3097
46383212 3098 def _comment_entries(self, root_continuation_data, ytcfg, video_id, parent=None, tracker=None):
3099
3100 get_single_config_arg = lambda c: self._configuration_arg(c, [''])[0]
2d6659b9 3101
3102 def extract_header(contents):
2d6659b9 3103 _continuation = None
3104 for content in contents:
46383212 3105 comments_header_renderer = traverse_obj(content, 'commentsHeaderRenderer')
f0d785d3 3106 expected_comment_count = self._get_count(
3107 comments_header_renderer, 'countText', 'commentsCount')
fe93e2c4 3108
2d6659b9 3109 if expected_comment_count:
46383212 3110 tracker['est_total'] = expected_comment_count
3111 self.to_screen(f'Downloading ~{expected_comment_count} comments')
3112 comment_sort_index = int(get_single_config_arg('comment_sort') != 'top') # 1 = new, 0 = top
2d6659b9 3113
3114 sort_menu_item = try_get(
3115 comments_header_renderer,
3116 lambda x: x['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems'][comment_sort_index], dict) or {}
3117 sort_continuation_ep = sort_menu_item.get('serviceEndpoint') or {}
3118
3119 _continuation = self._extract_continuation_ep_data(sort_continuation_ep) or self._extract_continuation(sort_menu_item)
3120 if not _continuation:
3121 continue
3122
46383212 3123 sort_text = str_or_none(sort_menu_item.get('title'))
3124 if not sort_text:
2d6659b9 3125 sort_text = 'top comments' if comment_sort_index == 0 else 'newest first'
46383212 3126 self.to_screen('Sorting comments by %s' % sort_text.lower())
2d6659b9 3127 break
a2160aa4 3128 return _continuation
a1c5d2ca 3129
2d6659b9 3130 def extract_thread(contents):
a1c5d2ca 3131 if not parent:
46383212 3132 tracker['current_page_thread'] = 0
a1c5d2ca 3133 for content in contents:
46383212 3134 if not parent and tracker['total_parent_comments'] >= max_parents:
3135 yield
a1c5d2ca 3136 comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
46383212 3137 comment_renderer = get_first(
3138 (comment_thread_renderer, content), [['commentRenderer', ('comment', 'commentRenderer')]],
3139 expected_type=dict, default={})
a1c5d2ca 3140
a1c5d2ca
M
3141 comment = self._extract_comment(comment_renderer, parent)
3142 if not comment:
3143 continue
46383212 3144
3145 tracker['running_total'] += 1
3146 tracker['total_reply_comments' if parent else 'total_parent_comments'] += 1
a1c5d2ca 3147 yield comment
46383212 3148
a1c5d2ca
M
3149 # Attempt to get the replies
3150 comment_replies_renderer = try_get(
3151 comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
3152
3153 if comment_replies_renderer:
46383212 3154 tracker['current_page_thread'] += 1
a1c5d2ca 3155 comment_entries_iter = self._comment_entries(
99e9e001 3156 comment_replies_renderer, ytcfg, video_id,
46383212 3157 parent=comment.get('id'), tracker=tracker)
86e5f3ed 3158 yield from itertools.islice(comment_entries_iter, min(
3159 max_replies_per_thread, max(0, max_replies - tracker['total_reply_comments'])))
a1c5d2ca 3160
46383212 3161 # Keeps track of counts across recursive calls
3162 if not tracker:
3163 tracker = dict(
3164 running_total=0,
3165 est_total=0,
3166 current_page_thread=0,
3167 total_parent_comments=0,
3168 total_reply_comments=0)
3169
3170 # TODO: Deprecated
2d6659b9 3171 # YouTube comments have a max depth of 2
46383212 3172 max_depth = int_or_none(get_single_config_arg('max_comment_depth'))
3173 if max_depth:
da4db748 3174 self._downloader.deprecated_feature('[youtube] max_comment_depth extractor argument is deprecated. '
3175 'Set max replies in the max-comments extractor argument instead')
2d6659b9 3176 if max_depth == 1 and parent:
3177 return
a1c5d2ca 3178
46383212 3179 max_comments, max_parents, max_replies, max_replies_per_thread, *_ = map(
3180 lambda p: int_or_none(p, default=sys.maxsize), self._configuration_arg('max_comments', ) + [''] * 4)
2d6659b9 3181
46383212 3182 continuation = self._extract_continuation(root_continuation_data)
aae16f6e 3183
46383212 3184 response = None
6e634cbe 3185 is_forced_continuation = False
2d6659b9 3186 is_first_continuation = parent is None
6e634cbe 3187 if is_first_continuation and not continuation:
3188 # Sometimes you can get comments by generating the continuation yourself,
3189 # even if YouTube initially reports them being disabled - e.g. stories comments.
3190 # Note: if the comment section is actually disabled, YouTube may return a response with
3191 # required check_get_keys missing. So we will disable that check initially in this case.
3192 continuation = self._build_api_continuation_query(self._generate_comment_continuation(video_id))
3193 is_forced_continuation = True
a1c5d2ca
M
3194
3195 for page_num in itertools.count(0):
3196 if not continuation:
3197 break
46383212 3198 headers = self.generate_api_headers(ytcfg=ytcfg, visitor_data=self._extract_visitor_data(response))
3199 comment_prog_str = f"({tracker['running_total']}/{tracker['est_total']})"
2d6659b9 3200 if page_num == 0:
3201 if is_first_continuation:
3202 note_prefix = 'Downloading comment section API JSON'
a1c5d2ca 3203 else:
2d6659b9 3204 note_prefix = ' Downloading comment API JSON reply thread %d %s' % (
46383212 3205 tracker['current_page_thread'], comment_prog_str)
2d6659b9 3206 else:
3207 note_prefix = '%sDownloading comment%s API JSON page %d %s' % (
3208 ' ' if parent else '', ' replies' if parent else '',
3209 page_num, comment_prog_str)
3210
3211 response = self._extract_response(
fe93e2c4 3212 item_id=None, query=continuation,
2d6659b9 3213 ep='next', ytcfg=ytcfg, headers=headers, note=note_prefix,
6e634cbe 3214 check_get_keys='onResponseReceivedEndpoints' if not is_forced_continuation else None)
3215 is_forced_continuation = False
46383212 3216 continuation_contents = traverse_obj(
3217 response, 'onResponseReceivedEndpoints', expected_type=list, default=[])
a1c5d2ca 3218
2d6659b9 3219 continuation = None
46383212 3220 for continuation_section in continuation_contents:
3221 continuation_items = traverse_obj(
3222 continuation_section,
3223 (('reloadContinuationItemsCommand', 'appendContinuationItemsAction'), 'continuationItems'),
3224 get_all=False, expected_type=list) or []
3225 if is_first_continuation:
3226 continuation = extract_header(continuation_items)
3227 is_first_continuation = False
2d6659b9 3228 if continuation:
a1c5d2ca 3229 break
46383212 3230 continue
a1c5d2ca 3231
46383212 3232 for entry in extract_thread(continuation_items):
3233 if not entry:
3234 return
3235 yield entry
3236 continuation = self._extract_continuation({'contents': continuation_items})
3237 if continuation:
2d6659b9 3238 break
a1c5d2ca 3239
6e634cbe 3240 message = self._get_text(root_continuation_data, ('contents', ..., 'messageRenderer', 'text'), max_runs=1)
3241 if message and not parent and tracker['running_total'] == 0:
3242 self.report_warning(f'Youtube said: {message}', video_id=video_id, only_once=True)
3243
3244 @staticmethod
3245 def _generate_comment_continuation(video_id):
3246 """
3247 Generates initial comment section continuation token from given video id
3248 """
3249 token = f'\x12\r\x12\x0b{video_id}\x18\x062\'"\x11"\x0b{video_id}0\x00x\x020\x00B\x10comments-section'
3250 return base64.b64encode(token.encode()).decode()
3251
a2160aa4 3252 def _get_comments(self, ytcfg, video_id, contents, webpage):
a1c5d2ca 3253 """Entry for comment extraction"""
2d6659b9 3254 def _real_comment_extract(contents):
aae16f6e 3255 renderer = next((
3256 item for item in traverse_obj(contents, (..., 'itemSectionRenderer'), default={})
3257 if item.get('sectionIdentifier') == 'comment-item-section'), None)
3258 yield from self._comment_entries(renderer, ytcfg, video_id)
99e9e001 3259
a2160aa4 3260 max_comments = int_or_none(self._configuration_arg('max_comments', [''])[0])
a2160aa4 3261 return itertools.islice(_real_comment_extract(contents), 0, max_comments)
a1c5d2ca 3262
109dd3b2 3263 @staticmethod
99e9e001 3264 def _get_checkok_params():
3265 return {'contentCheckOk': True, 'racyCheckOk': True}
3266
3267 @classmethod
3268 def _generate_player_context(cls, sts=None):
109dd3b2 3269 context = {
3270 'html5Preference': 'HTML5_PREF_WANTS',
3271 }
3272 if sts is not None:
3273 context['signatureTimestamp'] = sts
3274 return {
3275 'playbackContext': {
3276 'contentPlaybackContext': context
a1a7907b 3277 },
99e9e001 3278 **cls._get_checkok_params()
109dd3b2 3279 }
3280
e7e94f2a
D
3281 @staticmethod
3282 def _is_agegated(player_response):
3283 if traverse_obj(player_response, ('playabilityStatus', 'desktopLegacyAgeGateReason')):
9275f62c 3284 return True
e7e94f2a
D
3285
3286 reasons = traverse_obj(player_response, ('playabilityStatus', ('status', 'reason')), default=[])
3287 AGE_GATE_REASONS = (
3288 'confirm your age', 'age-restricted', 'inappropriate', # reason
3289 'age_verification_required', 'age_check_required', # status
3290 )
3291 return any(expected in reason for expected in AGE_GATE_REASONS for reason in reasons)
3292
3293 @staticmethod
3294 def _is_unplayable(player_response):
3295 return traverse_obj(player_response, ('playabilityStatus', 'status')) == 'UNPLAYABLE'
9275f62c 3296
50ac0e54 3297 _STORY_PLAYER_PARAMS = '8AEB'
3298
3299 def _extract_player_response(self, client, video_id, master_ytcfg, player_ytcfg, player_url, initial_pr, smuggled_data):
109dd3b2 3300
11f9be09 3301 session_index = self._extract_session_index(player_ytcfg, master_ytcfg)
3302 syncid = self._extract_account_syncid(player_ytcfg, master_ytcfg, initial_pr)
b6de707d 3303 sts = self._extract_signature_timestamp(video_id, player_url, master_ytcfg, fatal=False) if player_url else None
11f9be09 3304 headers = self.generate_api_headers(
99e9e001 3305 ytcfg=player_ytcfg, account_syncid=syncid, session_index=session_index, default_client=client)
9297939e 3306
6e634cbe 3307 yt_query = {
3308 'videoId': video_id,
6e634cbe 3309 }
50ac0e54 3310 if smuggled_data.get('is_story') or _split_innertube_client(client)[0] == 'android':
3311 yt_query['params'] = self._STORY_PLAYER_PARAMS
3312
11f9be09 3313 yt_query.update(self._generate_player_context(sts))
3314 return self._extract_response(
3315 item_id=video_id, ep='player', query=yt_query,
379e44ed 3316 ytcfg=player_ytcfg, headers=headers, fatal=True,
000c15a4 3317 default_client=client,
11f9be09 3318 note='Downloading %s player API JSON' % client.replace('_', ' ').strip()
3319 ) or None
3320
11f9be09 3321 def _get_requested_clients(self, url, smuggled_data):
b4c055ba 3322 requested_clients = []
d0d012d4 3323 default = ['android', 'web']
000c15a4 3324 allowed_clients = sorted(
86e5f3ed 3325 (client for client in INNERTUBE_CLIENTS.keys() if client[:1] != '_'),
000c15a4 3326 key=lambda client: INNERTUBE_CLIENTS[client]['priority'], reverse=True)
b4c055ba 3327 for client in self._configuration_arg('player_client'):
3328 if client in allowed_clients:
3329 requested_clients.append(client)
d0d012d4 3330 elif client == 'default':
3331 requested_clients.extend(default)
b4c055ba 3332 elif client == 'all':
3333 requested_clients.extend(allowed_clients)
3334 else:
3335 self.report_warning(f'Skipping unsupported client {client}')
11f9be09 3336 if not requested_clients:
d0d012d4 3337 requested_clients = default
cf7e015f 3338
11f9be09 3339 if smuggled_data.get('is_music_url') or self.is_music_url(url):
3340 requested_clients.extend(
e7e94f2a 3341 f'{client}_music' for client in requested_clients if f'{client}_music' in INNERTUBE_CLIENTS)
dbdaaa23 3342
11f9be09 3343 return orderedSet(requested_clients)
cf7e015f 3344
50ac0e54 3345 def _extract_player_responses(self, clients, video_id, webpage, master_ytcfg, smuggled_data):
11f9be09 3346 initial_pr = None
3347 if webpage:
b7c47b74 3348 initial_pr = self._search_json(
3349 self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response', video_id, fatal=False)
6b09401b 3350
ae729626 3351 all_clients = set(clients)
c0bc527b 3352 clients = clients[::-1]
b6de707d 3353 prs = []
e7e94f2a 3354
ae729626 3355 def append_client(*client_names):
e7870111 3356 """ Append the first client name that exists but not already used """
ae729626 3357 for client_name in client_names:
e7870111
D
3358 actual_client = _split_innertube_client(client_name)[0]
3359 if actual_client in INNERTUBE_CLIENTS:
3360 if actual_client not in all_clients:
ae729626 3361 clients.append(client_name)
e7870111
D
3362 all_clients.add(actual_client)
3363 return
e7e94f2a 3364
379e44ed 3365 # Android player_response does not have microFormats which are needed for
3366 # extraction of some data. So we return the initial_pr with formats
3367 # stripped out even if not requested by the user
3368 # See: https://github.com/yt-dlp/yt-dlp/issues/501
379e44ed 3369 if initial_pr:
3370 pr = dict(initial_pr)
3371 pr['streamingData'] = None
b6de707d 3372 prs.append(pr)
379e44ed 3373
3374 last_error = None
b6de707d 3375 tried_iframe_fallback = False
3376 player_url = None
c0bc527b 3377 while clients:
e7870111 3378 client, base_client, variant = _split_innertube_client(clients.pop())
11f9be09 3379 player_ytcfg = master_ytcfg if client == 'web' else {}
a25bca9f 3380 if 'configs' not in self._configuration_arg('player_skip') and client != 'web':
3381 player_ytcfg = self._download_ytcfg(client, video_id) or player_ytcfg
c0bc527b 3382
b6de707d 3383 player_url = player_url or self._extract_player_url(master_ytcfg, player_ytcfg, webpage=webpage)
3384 require_js_player = self._get_default_ytcfg(client).get('REQUIRE_JS_PLAYER')
3385 if 'js' in self._configuration_arg('player_skip'):
3386 require_js_player = False
3387 player_url = None
3388
3389 if not player_url and not tried_iframe_fallback and require_js_player:
3390 player_url = self._download_player_url(video_id)
3391 tried_iframe_fallback = True
3392
379e44ed 3393 try:
3394 pr = initial_pr if client == 'web' and initial_pr else self._extract_player_response(
50ac0e54 3395 client, video_id, player_ytcfg or master_ytcfg, player_ytcfg, player_url if require_js_player else None, initial_pr, smuggled_data)
379e44ed 3396 except ExtractorError as e:
3397 if last_error:
3398 self.report_warning(last_error)
3399 last_error = e
3400 continue
3401
11f9be09 3402 if pr:
a3e96421 3403 # YouTube may return a different video player response than expected.
3404 # See: https://github.com/TeamNewPipe/NewPipe/issues/8713
3405 pr_video_id = traverse_obj(pr, ('videoDetails', 'videoId'))
3406 if pr_video_id and pr_video_id != video_id:
3407 self.report_warning(
c7dcf0b3 3408 f'Skipping player response from {client} client (got player response for video "{pr_video_id}" instead of "{video_id}")' + bug_reports_message())
a3e96421 3409 else:
3410 prs.append(pr)
c0bc527b 3411
e7e94f2a 3412 # creator clients can bypass AGE_VERIFICATION_REQUIRED if logged in
e7870111
D
3413 if variant == 'embedded' and self._is_unplayable(pr) and self.is_authenticated:
3414 append_client(f'{base_client}_creator')
e7e94f2a 3415 elif self._is_agegated(pr):
e7870111
D
3416 if variant == 'tv_embedded':
3417 append_client(f'{base_client}_embedded')
3418 elif not variant:
3419 append_client(f'tv_embedded.{base_client}', f'{base_client}_embedded')
c0bc527b 3420
379e44ed 3421 if last_error:
b6de707d 3422 if not len(prs):
379e44ed 3423 raise last_error
3424 self.report_warning(last_error)
b6de707d 3425 return prs, player_url
11f9be09 3426
4d37720a
L
3427 def _needs_live_processing(self, live_status, duration):
3428 if (live_status == 'is_live' and self.get_param('live_from_start')
3429 or live_status == 'post_live' and (duration or 0) > 4 * 3600):
3430 return live_status
3431
3432 def _extract_formats_and_subtitles(self, streaming_data, video_id, player_url, live_status, duration):
a0bb6ce5 3433 itags, stream_ids = {}, []
b25cac65 3434 itag_qualities, res_qualities = {}, {0: None}
d3fc8074 3435 q = qualities([
2a9c6dcd 3436 # Normally tiny is the smallest video-only formats. But
3437 # audio-only formats with unknown quality may get tagged as tiny
3438 'tiny',
3439 'audio_quality_ultralow', 'audio_quality_low', 'audio_quality_medium', 'audio_quality_high', # Audio only formats
d3fc8074 3440 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'
3441 ])
11f9be09 3442 streaming_formats = traverse_obj(streaming_data, (..., ('formats', 'adaptiveFormats'), ...), default=[])
9297939e 3443
545cc85d 3444 for fmt in streaming_formats:
727029c5 3445 if fmt.get('targetDurationSec'):
545cc85d 3446 continue
321bf820 3447
cc2db878 3448 itag = str_or_none(fmt.get('itag'))
9297939e 3449 audio_track = fmt.get('audioTrack') or {}
3450 stream_id = '%s.%s' % (itag or '', audio_track.get('id', ''))
3451 if stream_id in stream_ids:
3452 continue
3453
cc2db878 3454 quality = fmt.get('quality')
2a9c6dcd 3455 height = int_or_none(fmt.get('height'))
d3fc8074 3456 if quality == 'tiny' or not quality:
3457 quality = fmt.get('audioQuality', '').lower() or quality
2a9c6dcd 3458 # The 3gp format (17) in android client has a quality of "small",
3459 # but is actually worse than other formats
3460 if itag == '17':
3461 quality = 'tiny'
3462 if quality:
3463 if itag:
3464 itag_qualities[itag] = quality
3465 if height:
3466 res_qualities[height] = quality
cc2db878 3467 # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
3468 # (adding `&sq=0` to the URL) and parsing emsg box to determine the
3469 # number of fragment that would subsequently requested with (`&sq=N`)
3470 if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
3471 continue
3472
545cc85d 3473 fmt_url = fmt.get('url')
3474 if not fmt_url:
14f25df2 3475 sc = urllib.parse.parse_qs(fmt.get('signatureCipher'))
545cc85d 3476 fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
3477 encrypted_sig = try_get(sc, lambda x: x['s'][0])
52023f12 3478 if not all((sc, fmt_url, player_url, encrypted_sig)):
545cc85d 3479 continue
52023f12 3480 try:
3481 fmt_url += '&%s=%s' % (
3482 traverse_obj(sc, ('sp', -1)) or 'signature',
3483 self._decrypt_signature(encrypted_sig, video_id, player_url)
3484 )
3485 except ExtractorError as e:
580ce007 3486 self.report_warning('Signature extraction failed: Some formats may be missing',
3487 video_id=video_id, only_once=True)
52023f12 3488 self.write_debug(e, only_once=True)
201e9eaa 3489 continue
545cc85d 3490
404f611f 3491 query = parse_qs(fmt_url)
3492 throttled = False
b2916526 3493 if query.get('n'):
404f611f 3494 try:
580ce007 3495 decrypt_nsig = self._cached(self._decrypt_nsig, 'nsig', query['n'][0])
404f611f 3496 fmt_url = update_url_query(fmt_url, {
580ce007 3497 'n': decrypt_nsig(query['n'][0], video_id, player_url)
3498 })
404f611f 3499 except ExtractorError as e:
25836db6 3500 phantomjs_hint = ''
3501 if isinstance(e, JSInterpreter.Exception):
d81ba7d4 3502 phantomjs_hint = (f' Install {self._downloader._format_err("PhantomJS", self._downloader.Styles.EMPHASIS)} '
3503 f'to workaround the issue. {PhantomJSwrapper.INSTALL_HINT}\n')
17ffed18 3504 if player_url:
3505 self.report_warning(
3506 f'nsig extraction failed: You may experience throttling for some formats\n{phantomjs_hint}'
3507 f' n = {query["n"][0]} ; player = {player_url}', video_id=video_id, only_once=True)
3508 self.write_debug(e, only_once=True)
3509 else:
3510 self.report_warning(
3511 'Cannot decrypt nsig without player_url: You may experience throttling for some formats',
3512 video_id=video_id, only_once=True)
404f611f 3513 throttled = True
3514
545cc85d 3515 if itag:
a0bb6ce5 3516 itags[itag] = 'https'
9297939e 3517 stream_ids.append(stream_id)
3518
0ad92dfb 3519 tbr = float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
ab6df717 3520 language_preference = (
3521 10 if audio_track.get('audioIsDefault') and 10
3522 else -10 if 'descriptive' in (audio_track.get('displayName') or '').lower() and -10
3523 else -1)
0ad92dfb 3524 # Some formats may have much smaller duration than others (possibly damaged during encoding)
62b58c09 3525 # E.g. 2-nOtRESiUc Ref: https://github.com/yt-dlp/yt-dlp/issues/2823
a1b2d843 3526 # Make sure to avoid false positives with small duration differences.
62b58c09 3527 # E.g. __2ABJjxzNo, ySuUZEjARPY
a1b2d843 3528 is_damaged = try_get(fmt, lambda x: float(x['approxDurationMs']) / duration < 500)
08d30158 3529 if is_damaged:
0f06bcd7 3530 self.report_warning(
3531 f'{video_id}: Some formats are possibly damaged. They will be deprioritized', only_once=True)
545cc85d 3532 dct = {
3533 'asr': int_or_none(fmt.get('audioSampleRate')),
3534 'filesize': int_or_none(fmt.get('contentLength')),
3535 'format_id': itag,
34921b43 3536 'format_note': join_nonempty(
26e8e044 3537 '%s%s' % (audio_track.get('displayName') or '',
ab6df717 3538 ' (default)' if language_preference > 0 else ''),
404f611f 3539 fmt.get('qualityLabel') or quality.replace('audio_quality_', ''),
a4166234 3540 try_get(fmt, lambda x: x['projectionType'].replace('RECTANGULAR', '').lower()),
3541 try_get(fmt, lambda x: x['spatialAudioType'].replace('SPATIAL_AUDIO_TYPE_', '').lower()),
0ad92dfb 3542 throttled and 'THROTTLED', is_damaged and 'DAMAGED', delim=', '),
91e5e839 3543 # Format 22 is likely to be damaged. See https://github.com/yt-dlp/yt-dlp/issues/3372
3544 'source_preference': -10 if throttled else -5 if itag == '22' else -1,
a4211baf 3545 'fps': int_or_none(fmt.get('fps')) or None,
a4166234 3546 'audio_channels': fmt.get('audioChannels'),
2a9c6dcd 3547 'height': height,
dca3ff4a 3548 'quality': q(quality),
727029c5 3549 'has_drm': bool(fmt.get('drmFamilies')),
cc2db878 3550 'tbr': tbr,
545cc85d 3551 'url': fmt_url,
2a9c6dcd 3552 'width': int_or_none(fmt.get('width')),
ab6df717 3553 'language': join_nonempty(audio_track.get('id', '').split('.')[0],
3554 'desc' if language_preference < -1 else ''),
3555 'language_preference': language_preference,
a405b38f 3556 # Strictly de-prioritize damaged and 3gp formats
3557 'preference': -10 if is_damaged else -2 if itag == '17' else None,
545cc85d 3558 }
60bdb7bd 3559 mime_mobj = re.match(
3560 r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', fmt.get('mimeType') or '')
3561 if mime_mobj:
3562 dct['ext'] = mimetype2ext(mime_mobj.group(1))
3563 dct.update(parse_codecs(mime_mobj.group(2)))
cc2db878 3564 no_audio = dct.get('acodec') == 'none'
3565 no_video = dct.get('vcodec') == 'none'
3566 if no_audio:
3567 dct['vbr'] = tbr
3568 if no_video:
3569 dct['abr'] = tbr
3570 if no_audio or no_video:
545cc85d 3571 dct['downloader_options'] = {
3572 # Youtube throttles chunks >~10M
3573 'http_chunk_size': 10485760,
bf1317d2 3574 }
7c60c33e 3575 if dct.get('ext'):
3576 dct['container'] = dct['ext'] + '_dash'
11f9be09 3577 yield dct
545cc85d 3578
4d37720a
L
3579 needs_live_processing = self._needs_live_processing(live_status, duration)
3580 skip_bad_formats = not self._configuration_arg('include_incomplete_formats')
3581
3582 skip_manifests = set(self._configuration_arg('skip'))
3583 if (not self.get_param('youtube_include_hls_manifest', True)
3584 or needs_live_processing == 'is_live' # These will be filtered out by YoutubeDL anyway
3585 or needs_live_processing and skip_bad_formats):
3586 skip_manifests.add('hls')
3587
0f06bcd7 3588 if not self.get_param('youtube_include_dash_manifest', True):
4d37720a
L
3589 skip_manifests.add('dash')
3590 if self._configuration_arg('include_live_dash'):
3591 self._downloader.deprecated_feature('[youtube] include_live_dash extractor argument is deprecated. '
3592 'Use include_incomplete_formats extractor argument instead')
3593 elif skip_bad_formats and live_status == 'is_live' and needs_live_processing != 'is_live':
3594 skip_manifests.add('dash')
5d3a0e79 3595
a0bb6ce5 3596 def process_manifest_format(f, proto, itag):
3597 if itag in itags:
3598 if itags[itag] == proto or f'{itag}-{proto}' in itags:
3599 return False
3600 itag = f'{itag}-{proto}'
3601 if itag:
3602 f['format_id'] = itag
3603 itags[itag] = proto
3604
b25cac65 3605 f['quality'] = q(itag_qualities.get(try_get(f, lambda f: f['format_id'].split('-')[0]), -1))
5c6d2ef9 3606 if f['quality'] == -1 and f.get('height'):
3607 f['quality'] = q(res_qualities[min(res_qualities, key=lambda x: abs(x - f['height']))])
a0bb6ce5 3608 return True
2a9c6dcd 3609
c646d76f 3610 subtitles = {}
11f9be09 3611 for sd in streaming_data:
4d37720a 3612 hls_manifest_url = 'hls' not in skip_manifests and sd.get('hlsManifestUrl')
9297939e 3613 if hls_manifest_url:
4d37720a
L
3614 fmts, subs = self._extract_m3u8_formats_and_subtitles(
3615 hls_manifest_url, video_id, 'mp4', fatal=False, live=live_status == 'is_live')
c646d76f 3616 subtitles = self._merge_subtitles(subs, subtitles)
3617 for f in fmts:
a0bb6ce5 3618 if process_manifest_format(f, 'hls', self._search_regex(
3619 r'/itag/(\d+)', f['url'], 'itag', default=None)):
3620 yield f
545cc85d 3621
4d37720a 3622 dash_manifest_url = 'dash' not in skip_manifests and sd.get('dashManifestUrl')
5d3a0e79 3623 if dash_manifest_url:
c646d76f 3624 formats, subs = self._extract_mpd_formats_and_subtitles(dash_manifest_url, video_id, fatal=False)
3625 subtitles = self._merge_subtitles(subs, subtitles) # Prioritize HLS subs over DASH
3626 for f in formats:
a0bb6ce5 3627 if process_manifest_format(f, 'dash', f['format_id']):
3628 f['filesize'] = int_or_none(self._search_regex(
3629 r'/clen/(\d+)', f.get('fragment_base_url') or f['url'], 'file size', default=None))
4d37720a 3630 if needs_live_processing:
adbc4ec4
THD
3631 f['is_from_start'] = True
3632
a0bb6ce5 3633 yield f
c646d76f 3634 yield subtitles
11f9be09 3635
720c3099 3636 def _extract_storyboard(self, player_responses, duration):
3637 spec = get_first(
3638 player_responses, ('storyboards', 'playerStoryboardSpecRenderer', 'spec'), default='').split('|')[::-1]
596379e2 3639 base_url = url_or_none(urljoin('https://i.ytimg.com/', spec.pop() or None))
3640 if not base_url:
720c3099 3641 return
720c3099 3642 L = len(spec) - 1
3643 for i, args in enumerate(spec):
3644 args = args.split('#')
3645 counts = list(map(int_or_none, args[:5]))
3646 if len(args) != 8 or not all(counts):
3647 self.report_warning(f'Malformed storyboard {i}: {"#".join(args)}{bug_reports_message()}')
3648 continue
3649 width, height, frame_count, cols, rows = counts
3650 N, sigh = args[6:]
3651
3652 url = base_url.replace('$L', str(L - i)).replace('$N', N) + f'&sigh={sigh}'
3653 fragment_count = frame_count / (cols * rows)
3654 fragment_duration = duration / fragment_count
3655 yield {
3656 'format_id': f'sb{i}',
3657 'format_note': 'storyboard',
3658 'ext': 'mhtml',
3659 'protocol': 'mhtml',
3660 'acodec': 'none',
3661 'vcodec': 'none',
3662 'url': url,
3663 'width': width,
3664 'height': height,
45e8a04e 3665 'fps': frame_count / duration,
3666 'rows': rows,
3667 'columns': cols,
720c3099 3668 'fragments': [{
b3edc806 3669 'url': url.replace('$M', str(j)),
720c3099 3670 'duration': min(fragment_duration, duration - (j * fragment_duration)),
3671 } for j in range(math.ceil(fragment_count))],
3672 }
3673
adbc4ec4 3674 def _download_player_responses(self, url, smuggled_data, video_id, webpage_url):
b6de707d 3675 webpage = None
3676 if 'webpage' not in self._configuration_arg('player_skip'):
50ac0e54 3677 query = {'bpctr': '9999999999', 'has_verified': '1'}
3678 if smuggled_data.get('is_story'):
3679 query['pp'] = self._STORY_PLAYER_PARAMS
b6de707d 3680 webpage = self._download_webpage(
50ac0e54 3681 webpage_url, video_id, fatal=False, query=query)
11f9be09 3682
3683 master_ytcfg = self.extract_ytcfg(video_id, webpage) or self._get_default_ytcfg()
11f9be09 3684
b6de707d 3685 player_responses, player_url = self._extract_player_responses(
11f9be09 3686 self._get_requested_clients(url, smuggled_data),
50ac0e54 3687 video_id, webpage, master_ytcfg, smuggled_data)
11f9be09 3688
adbc4ec4
THD
3689 return webpage, master_ytcfg, player_responses, player_url
3690
a1b2d843 3691 def _list_formats(self, video_id, microformats, video_details, player_responses, player_url, duration=None):
adbc4ec4
THD
3692 live_broadcast_details = traverse_obj(microformats, (..., 'liveBroadcastDetails'))
3693 is_live = get_first(video_details, 'isLive')
3694 if is_live is None:
3695 is_live = get_first(live_broadcast_details, 'isLiveNow')
4d37720a
L
3696 live_content = get_first(video_details, 'isLiveContent')
3697 is_upcoming = get_first(video_details, 'isUpcoming')
4d37720a
L
3698 post_live = get_first(video_details, 'isPostLiveDvr')
3699 live_status = ('post_live' if post_live
3700 else 'is_live' if is_live
3701 else 'is_upcoming' if is_upcoming
6678a4f0 3702 else 'was_live' if live_content
3703 else 'not_live' if False in (is_live, live_content)
3704 else None)
adbc4ec4 3705 streaming_data = traverse_obj(player_responses, (..., 'streamingData'), default=[])
4d37720a 3706 *formats, subtitles = self._extract_formats_and_subtitles(streaming_data, video_id, player_url, live_status, duration)
adbc4ec4 3707
4d37720a 3708 return live_broadcast_details, live_status, streaming_data, formats, subtitles
adbc4ec4
THD
3709
3710 def _real_extract(self, url):
3711 url, smuggled_data = unsmuggle_url(url, {})
3712 video_id = self._match_id(url)
3713
3714 base_url = self.http_scheme() + '//www.youtube.com/'
3715 webpage_url = base_url + 'watch?v=' + video_id
3716
3717 webpage, master_ytcfg, player_responses, player_url = self._download_player_responses(url, smuggled_data, video_id, webpage_url)
3718
11f9be09 3719 playability_statuses = traverse_obj(
3720 player_responses, (..., 'playabilityStatus'), expected_type=dict, default=[])
3721
3722 trailer_video_id = get_first(
3723 playability_statuses,
3724 ('errorScreen', 'playerLegacyDesktopYpcTrailerRenderer', 'trailerVideoId'),
3725 expected_type=str)
3726 if trailer_video_id:
3727 return self.url_result(
3728 trailer_video_id, self.ie_key(), trailer_video_id)
3729
3730 search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None))
3731 if webpage else (lambda x: None))
3732
3733 video_details = traverse_obj(
3734 player_responses, (..., 'videoDetails'), expected_type=dict, default=[])
3735 microformats = traverse_obj(
3736 player_responses, (..., 'microformat', 'playerMicroformatRenderer'),
3737 expected_type=dict, default=[])
c26f9b99 3738
3739 translated_title = self._get_text(microformats, (..., 'title'))
3740 video_title = (self._preferred_lang and translated_title
3741 or get_first(video_details, 'title') # primary
3742 or translated_title
3743 or search_meta(['og:title', 'twitter:title', 'title']))
3744 translated_description = self._get_text(microformats, (..., 'description'))
3745 original_description = get_first(video_details, 'shortDescription')
3746 video_description = (
3747 self._preferred_lang and translated_description
3748 # If original description is blank, it will be an empty string.
3749 # Do not prefer translated description in this case.
3750 or original_description if original_description is not None else translated_description)
11f9be09 3751
d89257f3 3752 multifeed_metadata_list = get_first(
3753 player_responses,
3754 ('multicamera', 'playerLegacyMulticameraRenderer', 'metadataList'),
3755 expected_type=str)
3756 if multifeed_metadata_list and not smuggled_data.get('force_singlefeed'):
3757 if self.get_param('noplaylist'):
11f9be09 3758 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
d89257f3 3759 else:
3760 entries = []
3761 feed_ids = []
3762 for feed in multifeed_metadata_list.split(','):
3763 # Unquote should take place before split on comma (,) since textual
3764 # fields may contain comma as well (see
3765 # https://github.com/ytdl-org/youtube-dl/issues/8536)
14f25df2 3766 feed_data = urllib.parse.parse_qs(
ac668111 3767 urllib.parse.unquote_plus(feed))
d89257f3 3768
3769 def feed_entry(name):
3770 return try_get(
14f25df2 3771 feed_data, lambda x: x[name][0], str)
d89257f3 3772
3773 feed_id = feed_entry('id')
3774 if not feed_id:
3775 continue
3776 feed_title = feed_entry('title')
3777 title = video_title
3778 if feed_title:
3779 title += ' (%s)' % feed_title
3780 entries.append({
3781 '_type': 'url_transparent',
3782 'ie_key': 'Youtube',
3783 'url': smuggle_url(
3784 '%swatch?v=%s' % (base_url, feed_data['id'][0]),
3785 {'force_singlefeed': True}),
3786 'title': title,
3787 })
3788 feed_ids.append(feed_id)
3789 self.to_screen(
3790 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
3791 % (', '.join(feed_ids), video_id))
3792 return self.playlist_result(
3793 entries, video_id, video_title, video_description)
11f9be09 3794
9da6612b 3795 duration = (int_or_none(get_first(video_details, 'lengthSeconds'))
3796 or int_or_none(get_first(microformats, 'lengthSeconds'))
3797 or parse_duration(search_meta('duration')) or None)
a1b2d843 3798
4d37720a
L
3799 live_broadcast_details, live_status, streaming_data, formats, automatic_captions = \
3800 self._list_formats(video_id, microformats, video_details, player_responses, player_url, duration)
3801 if live_status == 'post_live':
3802 self.write_debug(f'{video_id}: Video is in Post-Live Manifestless mode')
bf1317d2 3803
545cc85d 3804 if not formats:
11f9be09 3805 if not self.get_param('allow_unplayable_formats') and traverse_obj(streaming_data, (..., 'licenseInfos')):
88acdbc2 3806 self.report_drm(video_id)
11f9be09 3807 pemr = get_first(
3808 playability_statuses,
3809 ('errorScreen', 'playerErrorMessageRenderer'), expected_type=dict) or {}
3810 reason = self._get_text(pemr, 'reason') or get_first(playability_statuses, 'reason')
3811 subreason = clean_html(self._get_text(pemr, 'subreason') or '')
545cc85d 3812 if subreason:
545cc85d 3813 if subreason == 'The uploader has not made this video available in your country.':
11f9be09 3814 countries = get_first(microformats, 'availableCountries')
545cc85d 3815 if not countries:
3816 regions_allowed = search_meta('regionsAllowed')
3817 countries = regions_allowed.split(',') if regions_allowed else None
b7da73eb 3818 self.raise_geo_restricted(subreason, countries, metadata_available=True)
11f9be09 3819 reason += f'. {subreason}'
545cc85d 3820 if reason:
b7da73eb 3821 self.raise_no_formats(reason, expected=True)
bf1317d2 3822
11f9be09 3823 keywords = get_first(video_details, 'keywords', expected_type=list) or []
545cc85d 3824 if not keywords and webpage:
3825 keywords = [
3826 unescapeHTML(m.group('content'))
3827 for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
3828 for keyword in keywords:
3829 if keyword.startswith('yt:stretch='):
201c1459 3830 mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
3831 if mobj:
3832 # NB: float is intentional for forcing float division
3833 w, h = (float(v) for v in mobj.groups())
3834 if w > 0 and h > 0:
3835 ratio = w / h
3836 for f in formats:
3837 if f.get('vcodec') != 'none':
3838 f['stretched_ratio'] = ratio
3839 break
a709d873 3840 thumbnails = self._extract_thumbnails((video_details, microformats), (..., ..., 'thumbnail'))
ff2751ac 3841 thumbnail_url = search_meta(['og:image', 'twitter:image'])
3842 if thumbnail_url:
3843 thumbnails.append({
3844 'url': thumbnail_url,
ff2751ac 3845 })
fccf5021 3846 original_thumbnails = thumbnails.copy()
3847
0ba692ac 3848 # The best resolution thumbnails sometimes does not appear in the webpage
bfec31be 3849 # See: https://github.com/yt-dlp/yt-dlp/issues/340
cca80fe6 3850 # List of possible thumbnails - Ref: <https://stackoverflow.com/a/20542029>
e820fbaa 3851 thumbnail_names = [
962ffcf8 3852 # While the *1,*2,*3 thumbnails are just below their corresponding "*default" variants
bfec31be 3853 # in resolution, these are not the custom thumbnail. So de-prioritize them
3854 'maxresdefault', 'hq720', 'sddefault', 'hqdefault', '0', 'mqdefault', 'default',
3855 'sd1', 'sd2', 'sd3', 'hq1', 'hq2', 'hq3', 'mq1', 'mq2', 'mq3', '1', '2', '3'
cca80fe6 3856 ]
cca80fe6 3857 n_thumbnail_names = len(thumbnail_names)
0ba692ac 3858 thumbnails.extend({
3859 'url': 'https://i.ytimg.com/vi{webp}/{video_id}/{name}{live}.{ext}'.format(
3860 video_id=video_id, name=name, ext=ext,
4d37720a 3861 webp='_webp' if ext == 'webp' else '', live='_live' if live_status == 'is_live' else ''),
cca80fe6 3862 } for name in thumbnail_names for ext in ('webp', 'jpg'))
0ba692ac 3863 for thumb in thumbnails:
cca80fe6 3864 i = next((i for i, t in enumerate(thumbnail_names) if f'/{video_id}/{t}' in thumb['url']), n_thumbnail_names)
0ba692ac 3865 thumb['preference'] = (0 if '.webp' in thumb['url'] else -1) - (2 * i)
ff2751ac 3866 self._remove_duplicate_formats(thumbnails)
fccf5021 3867 self._downloader._sort_thumbnails(original_thumbnails)
545cc85d 3868
7ea65411 3869 category = get_first(microformats, 'category') or search_meta('genre')
3870 channel_id = str_or_none(
3871 get_first(video_details, 'channelId')
3872 or get_first(microformats, 'externalChannelId')
3873 or search_meta('channelId'))
7ea65411 3874 owner_profile_url = get_first(microformats, 'ownerProfileUrl')
3875
adbc4ec4
THD
3876 live_start_time = parse_iso8601(get_first(live_broadcast_details, 'startTimestamp'))
3877 live_end_time = parse_iso8601(get_first(live_broadcast_details, 'endTimestamp'))
3878 if not duration and live_end_time and live_start_time:
3879 duration = live_end_time - live_start_time
3880
4d37720a
L
3881 needs_live_processing = self._needs_live_processing(live_status, duration)
3882
3883 def is_bad_format(fmt):
3884 if needs_live_processing and not fmt.get('is_from_start'):
3885 return True
3886 elif (live_status == 'is_live' and needs_live_processing != 'is_live'
3887 and fmt.get('protocol') == 'http_dash_segments'):
3888 return True
3889
3890 for fmt in filter(is_bad_format, formats):
3891 fmt['preference'] = (fmt.get('preference') or -1) - 10
3892 fmt['format_note'] = join_nonempty(fmt.get('format_note'), '(Last 4 hours)', delim=' ')
3893
3894 if needs_live_processing:
3895 self._prepare_live_from_start_formats(
3896 formats, video_id, live_start_time, url, webpage_url, smuggled_data, live_status == 'is_live')
7ea65411 3897
720c3099 3898 formats.extend(self._extract_storyboard(player_responses, duration))
3899
31b532a1 3900 # source_preference is lower for throttled/potentially damaged formats
7e798d72 3901 self._sort_formats(formats, (
3902 'quality', 'res', 'fps', 'hdr:12', 'source', 'vcodec:vp9.2', 'channels', 'acodec', 'lang', 'proto'))
720c3099 3903
545cc85d 3904 info = {
3905 'id': video_id,
39ca3b5c 3906 'title': video_title,
545cc85d 3907 'formats': formats,
3908 'thumbnails': thumbnails,
fccf5021 3909 # The best thumbnail that we are sure exists. Prevents unnecessary
3910 # URL checking if user don't care about getting the best possible thumbnail
3911 'thumbnail': traverse_obj(original_thumbnails, (-1, 'url')),
545cc85d 3912 'description': video_description,
11f9be09 3913 'uploader': get_first(video_details, 'author'),
545cc85d 3914 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
3915 'uploader_url': owner_profile_url,
3916 'channel_id': channel_id,
a70635b8 3917 'channel_url': format_field(channel_id, None, 'https://www.youtube.com/channel/%s'),
545cc85d 3918 'duration': duration,
3919 'view_count': int_or_none(
11f9be09 3920 get_first((video_details, microformats), (..., 'viewCount'))
545cc85d 3921 or search_meta('interactionCount')),
11f9be09 3922 'average_rating': float_or_none(get_first(video_details, 'averageRating')),
545cc85d 3923 'age_limit': 18 if (
11f9be09 3924 get_first(microformats, 'isFamilySafe') is False
545cc85d 3925 or search_meta('isFamilyFriendly') == 'false'
3926 or search_meta('og:restrictions:age') == '18+') else 0,
3927 'webpage_url': webpage_url,
3928 'categories': [category] if category else None,
3929 'tags': keywords,
11f9be09 3930 'playable_in_embed': get_first(playability_statuses, 'playableInEmbed'),
4d37720a 3931 'live_status': live_status,
adbc4ec4 3932 'release_timestamp': live_start_time,
545cc85d 3933 }
b477fc13 3934
c646d76f 3935 subtitles = {}
3944e7af 3936 pctr = traverse_obj(player_responses, (..., 'captions', 'playerCaptionsTracklistRenderer'), expected_type=dict)
545cc85d 3937 if pctr:
ecdc9049 3938 def get_lang_code(track):
3939 return (remove_start(track.get('vssId') or '', '.').replace('.', '-')
3940 or track.get('languageCode'))
3941
3942 # Converted into dicts to remove duplicates
3943 captions = {
3944 get_lang_code(sub): sub
3945 for sub in traverse_obj(pctr, (..., 'captionTracks', ...), default=[])}
3946 translation_languages = {
3947 lang.get('languageCode'): self._get_text(lang.get('languageName'), max_runs=1)
3948 for lang in traverse_obj(pctr, (..., 'translationLanguages', ...), default=[])}
3949
774d79cc 3950 def process_language(container, base_url, lang_code, sub_name, query):
120916da 3951 lang_subs = container.setdefault(lang_code, [])
545cc85d 3952 for fmt in self._SUBTITLE_FORMATS:
3953 query.update({
3954 'fmt': fmt,
3955 })
3956 lang_subs.append({
3957 'ext': fmt,
60f393e4 3958 'url': urljoin('https://www.youtube.com', update_url_query(base_url, query)),
774d79cc 3959 'name': sub_name,
545cc85d 3960 })
7e72694b 3961
07b47084 3962 # NB: Constructing the full subtitle dictionary is slow
3963 get_translated_subs = 'translated_subs' not in self._configuration_arg('skip') and (
3964 self.get_param('writeautomaticsub', False) or self.get_param('listsubtitles'))
ecdc9049 3965 for lang_code, caption_track in captions.items():
3966 base_url = caption_track.get('baseUrl')
1235d333 3967 orig_lang = parse_qs(base_url).get('lang', [None])[-1]
545cc85d 3968 if not base_url:
3969 continue
ecdc9049 3970 lang_name = self._get_text(caption_track, 'name', max_runs=1)
545cc85d 3971 if caption_track.get('kind') != 'asr':
545cc85d 3972 if not lang_code:
3973 continue
3974 process_language(
ecdc9049 3975 subtitles, base_url, lang_code, lang_name, {})
3976 if not caption_track.get('isTranslatable'):
3977 continue
3944e7af 3978 for trans_code, trans_name in translation_languages.items():
3979 if not trans_code:
545cc85d 3980 continue
1235d333 3981 orig_trans_code = trans_code
ecdc9049 3982 if caption_track.get('kind') != 'asr':
07b47084 3983 if not get_translated_subs:
18e49408 3984 continue
ecdc9049 3985 trans_code += f'-{lang_code}'
a70635b8 3986 trans_name += format_field(lang_name, None, ' from %s')
d49669ac 3987 # Add an "-orig" label to the original language so that it can be distinguished.
3988 # The subs are returned without "-orig" as well for compatibility
1235d333 3989 if lang_code == f'a-{orig_trans_code}':
0c8d9e5f 3990 process_language(
d49669ac 3991 automatic_captions, base_url, f'{trans_code}-orig', f'{trans_name} (Original)', {})
3992 # Setting tlang=lang returns damaged subtitles.
d49669ac 3993 process_language(automatic_captions, base_url, trans_code, trans_name,
1235d333 3994 {} if orig_lang == orig_trans_code else {'tlang': trans_code})
c646d76f 3995
3996 info['automatic_captions'] = automatic_captions
3997 info['subtitles'] = subtitles
7e72694b 3998
14f25df2 3999 parsed_url = urllib.parse.urlparse(url)
545cc85d 4000 for component in [parsed_url.fragment, parsed_url.query]:
14f25df2 4001 query = urllib.parse.parse_qs(component)
545cc85d 4002 for k, v in query.items():
4003 for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
4004 d_k += '_time'
4005 if d_k not in info and k in s_ks:
4006 info[d_k] = parse_duration(query[k][0])
822b9d9c
RA
4007
4008 # Youtube Music Auto-generated description
822b9d9c 4009 if video_description:
1890fc63 4010 mobj = re.search(
4011 r'''(?xs)
4012 (?P<track>[^·\n]+)·(?P<artist>[^\n]+)\n+
4013 (?P<album>[^\n]+)
4014 (?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?
4015 (?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?
4016 (.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?
4017 .+\nAuto-generated\ by\ YouTube\.\s*$
4018 ''', video_description)
822b9d9c 4019 if mobj:
822b9d9c
RA
4020 release_year = mobj.group('release_year')
4021 release_date = mobj.group('release_date')
4022 if release_date:
4023 release_date = release_date.replace('-', '')
4024 if not release_year:
545cc85d 4025 release_year = release_date[:4]
4026 info.update({
4027 'album': mobj.group('album'.strip()),
4028 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
4029 'track': mobj.group('track').strip(),
4030 'release_date': release_date,
cc2db878 4031 'release_year': int_or_none(release_year),
545cc85d 4032 })
7e72694b 4033
545cc85d 4034 initial_data = None
4035 if webpage:
56ba69e4 4036 initial_data = self.extract_yt_initial_data(video_id, webpage, fatal=False)
545cc85d 4037 if not initial_data:
99e9e001 4038 query = {'videoId': video_id}
4039 query.update(self._get_checkok_params())
109dd3b2 4040 initial_data = self._extract_response(
4041 item_id=video_id, ep='next', fatal=False,
99e9e001 4042 ytcfg=master_ytcfg, query=query,
4043 headers=self.generate_api_headers(ytcfg=master_ytcfg),
109dd3b2 4044 note='Downloading initial data API JSON')
545cc85d 4045
0df111a3 4046 info['comment_count'] = traverse_obj(initial_data, (
4047 'contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'itemSectionRenderer',
4048 'contents', ..., 'commentsEntryPointHeaderRenderer', 'commentCount', 'simpleText'
4049 ), (
4050 'engagementPanels', lambda _, v: v['engagementPanelSectionListRenderer']['panelIdentifier'] == 'comment-item-section',
4051 'engagementPanelSectionListRenderer', 'header', 'engagementPanelTitleHeaderRenderer', 'contextualInfo', 'runs', ..., 'text'
4052 ), expected_type=int_or_none, get_all=False)
4053
19a03940 4054 try: # This will error if there is no livechat
c60ee3a2 4055 initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
19a03940 4056 except (KeyError, IndexError, TypeError):
4057 pass
4058 else:
ecdc9049 4059 info.setdefault('subtitles', {})['live_chat'] = [{
4ce05f57 4060 # url is needed to set cookies
4061 'url': f'https://www.youtube.com/watch?v={video_id}&bpctr=9999999999&has_verified=1',
c60ee3a2 4062 'video_id': video_id,
4063 'ext': 'json',
4d37720a
L
4064 'protocol': ('youtube_live_chat' if live_status in ('is_live', 'is_upcoming')
4065 else 'youtube_live_chat_replay'),
c60ee3a2 4066 }]
545cc85d 4067
4068 if initial_data:
7c365c21 4069 info['chapters'] = (
4070 self._extract_chapters_from_json(initial_data, duration)
4071 or self._extract_chapters_from_engagement_panel(initial_data, duration)
0fe51254 4072 or self._extract_chapters_from_description(video_description, duration)
7c365c21 4073 or None)
545cc85d 4074
17322130 4075 contents = traverse_obj(
4076 initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents'),
4077 expected_type=list, default=[])
4078
4079 vpir = get_first(contents, 'videoPrimaryInfoRenderer')
4080 if vpir:
4081 stl = vpir.get('superTitleLink')
4082 if stl:
4083 stl = self._get_text(stl)
4084 if try_get(
4085 vpir,
4086 lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
4087 info['location'] = stl
4088 else:
affc4fef 4089 mobj = re.search(r'(.+?)\s*S(\d+)\s*•?\s*E(\d+)', stl)
17322130 4090 if mobj:
545cc85d 4091 info.update({
17322130 4092 'series': mobj.group(1),
4093 'season_number': int(mobj.group(2)),
4094 'episode_number': int(mobj.group(3)),
545cc85d 4095 })
17322130 4096 for tlb in (try_get(
4097 vpir,
4098 lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
4099 list) or []):
3ffb2f5b 4100 tbrs = variadic(
4101 traverse_obj(
4102 tlb, 'toggleButtonRenderer',
4103 ('segmentedLikeDislikeButtonRenderer', ..., 'toggleButtonRenderer'),
4104 default=[]))
4105 for tbr in tbrs:
4106 for getter, regex in [(
4107 lambda x: x['defaultText']['accessibility']['accessibilityData'],
4108 r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
4109 lambda x: x['accessibility'],
4110 lambda x: x['accessibilityData']['accessibilityData'],
4111 ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
4112 label = (try_get(tbr, getter, dict) or {}).get('label')
4113 if label:
4114 mobj = re.match(regex, label)
4115 if mobj:
4116 info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
4117 break
17322130 4118 sbr_tooltip = try_get(
4119 vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
4120 if sbr_tooltip:
4121 like_count, dislike_count = sbr_tooltip.split(' / ')
4122 info.update({
4123 'like_count': str_to_int(like_count),
4124 'dislike_count': str_to_int(dislike_count),
4125 })
867c66ff
M
4126 vcr = traverse_obj(vpir, ('viewCount', 'videoViewCountRenderer'))
4127 if vcr:
4128 vc = self._get_count(vcr, 'viewCount')
4129 # Upcoming premieres with waiting count are treated as live here
4130 if vcr.get('isLive'):
4131 info['concurrent_view_count'] = vc
4132 elif info.get('view_count') is None:
4133 info['view_count'] = vc
4134
17322130 4135 vsir = get_first(contents, 'videoSecondaryInfoRenderer')
4136 if vsir:
4137 vor = traverse_obj(vsir, ('owner', 'videoOwnerRenderer'))
4138 info.update({
4139 'channel': self._get_text(vor, 'title'),
4140 'channel_follower_count': self._get_count(vor, 'subscriberCountText')})
4141
4142 rows = try_get(
4143 vsir,
4144 lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
4145 list) or []
4146 multiple_songs = False
4147 for row in rows:
4148 if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
4149 multiple_songs = True
4150 break
4151 for row in rows:
4152 mrr = row.get('metadataRowRenderer') or {}
4153 mrr_title = mrr.get('title')
4154 if not mrr_title:
4155 continue
4156 mrr_title = self._get_text(mrr, 'title')
4157 mrr_contents_text = self._get_text(mrr, ('contents', 0))
4158 if mrr_title == 'License':
4159 info['license'] = mrr_contents_text
4160 elif not multiple_songs:
4161 if mrr_title == 'Album':
4162 info['album'] = mrr_contents_text
4163 elif mrr_title == 'Artist':
4164 info['artist'] = mrr_contents_text
4165 elif mrr_title == 'Song':
4166 info['track'] = mrr_contents_text
545cc85d 4167
4168 fallbacks = {
4169 'channel': 'uploader',
4170 'channel_id': 'uploader_id',
4171 'channel_url': 'uploader_url',
4172 }
992f9a73 4173
17322130 4174 # The upload date for scheduled, live and past live streams / premieres in microformats
4175 # may be different from the stream date. Although not in UTC, we will prefer it in this case.
992f9a73 4176 # See: https://github.com/yt-dlp/yt-dlp/pull/2223#issuecomment-1008485139
17322130 4177 upload_date = (
4178 unified_strdate(get_first(microformats, 'uploadDate'))
4179 or unified_strdate(search_meta('uploadDate')))
1ff88b7a 4180 if not upload_date or (
4d37720a 4181 live_status in ('not_live', None)
1ff88b7a 4182 and 'no-youtube-prefer-utc-upload-date' not in self.get_param('compat_opts', [])
4183 ):
c26f9b99 4184 upload_date = strftime_or_none(
4185 self._parse_time_text(self._get_text(vpir, 'dateText')), '%Y%m%d') or upload_date
17322130 4186 info['upload_date'] = upload_date
992f9a73 4187
545cc85d 4188 for to, frm in fallbacks.items():
4189 if not info.get(to):
4190 info[to] = info.get(frm)
4191
4192 for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
4193 v = info.get(s_k)
4194 if v:
4195 info[d_k] = v
b84071c0 4196
c26f9b99 4197 badges = self._extract_badges(traverse_obj(contents, (..., 'videoPrimaryInfoRenderer'), get_all=False))
4198
4199 is_private = (self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE)
4200 or get_first(video_details, 'isPrivate', expected_type=bool))
4201
4202 info['availability'] = (
4203 'public' if self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
4204 else self._availability(
4205 is_private=is_private,
4206 needs_premium=(
4207 self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM)
4208 or False if initial_data and is_private is not None else None),
4209 needs_subscription=(
4210 self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION)
4211 or False if initial_data and is_private is not None else None),
4212 needs_auth=info['age_limit'] >= 18,
4213 is_unlisted=None if is_private is None else (
4214 self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED)
4215 or get_first(microformats, 'isUnlisted', expected_type=bool))))
c224251a 4216
a2160aa4 4217 info['__post_extractor'] = self.extract_comments(master_ytcfg, video_id, contents, webpage)
4ea3be0a 4218
11f9be09 4219 self.mark_watched(video_id, player_responses)
d77ab8e2 4220
545cc85d 4221 return info
c5e8d7af 4222
a61fd4cf 4223
a6213a49 4224class YoutubeTabBaseInfoExtractor(YoutubeBaseInfoExtractor):
5f6a1245 4225
182bda88 4226 @staticmethod
4227 def passthrough_smuggled_data(func):
4228 def _smuggle(entries, smuggled_data):
4229 for entry in entries:
4230 # TODO: Convert URL to music.youtube instead.
4231 # Do we need to passthrough any other smuggled_data?
4232 entry['url'] = smuggle_url(entry['url'], smuggled_data)
4233 yield entry
4234
4235 @functools.wraps(func)
4236 def wrapper(self, url):
4237 url, smuggled_data = unsmuggle_url(url, {})
4238 if self.is_music_url(url):
4239 smuggled_data['is_music_url'] = True
4240 info_dict = func(self, url, smuggled_data)
4241 if smuggled_data and info_dict.get('entries'):
4242 info_dict['entries'] = _smuggle(info_dict['entries'], smuggled_data)
4243 return info_dict
4244 return wrapper
4245
a6213a49 4246 def _extract_channel_id(self, webpage):
4247 channel_id = self._html_search_meta(
4248 'channelId', webpage, 'channel id', default=None)
4249 if channel_id:
4250 return channel_id
4251 channel_url = self._html_search_meta(
4252 ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
4253 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
4254 'twitter:app:url:googleplay'), webpage, 'channel url')
4255 return self._search_regex(
4256 r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
4257 channel_url, 'channel id')
15f6397c 4258
8bdd16b4 4259 @staticmethod
cd7c66cf 4260 def _extract_basic_item_renderer(item):
4261 # Modified from _extract_grid_item_renderer
201c1459 4262 known_basic_renderers = (
a17526e4 4263 'playlistRenderer', 'videoRenderer', 'channelRenderer', 'showRenderer', 'reelItemRenderer'
cd7c66cf 4264 )
4265 for key, renderer in item.items():
201c1459 4266 if not isinstance(renderer, dict):
cd7c66cf 4267 continue
201c1459 4268 elif key in known_basic_renderers:
4269 return renderer
4270 elif key.startswith('grid') and key.endswith('Renderer'):
4271 return renderer
8bdd16b4 4272
8bdd16b4 4273 def _grid_entries(self, grid_renderer):
4274 for item in grid_renderer['items']:
4275 if not isinstance(item, dict):
39b62db1 4276 continue
cd7c66cf 4277 renderer = self._extract_basic_item_renderer(item)
8bdd16b4 4278 if not isinstance(renderer, dict):
4279 continue
052e1350 4280 title = self._get_text(renderer, 'title')
fe93e2c4 4281
8bdd16b4 4282 # playlist
4283 playlist_id = renderer.get('playlistId')
4284 if playlist_id:
4285 yield self.url_result(
4286 'https://www.youtube.com/playlist?list=%s' % playlist_id,
4287 ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
4288 video_title=title)
201c1459 4289 continue
8bdd16b4 4290 # video
4291 video_id = renderer.get('videoId')
4292 if video_id:
4293 yield self._extract_video(renderer)
201c1459 4294 continue
8bdd16b4 4295 # channel
4296 channel_id = renderer.get('channelId')
4297 if channel_id:
8bdd16b4 4298 yield self.url_result(
4299 'https://www.youtube.com/channel/%s' % channel_id,
4300 ie=YoutubeTabIE.ie_key(), video_title=title)
201c1459 4301 continue
4302 # generic endpoint URL support
4303 ep_url = urljoin('https://www.youtube.com/', try_get(
4304 renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
14f25df2 4305 str))
201c1459 4306 if ep_url:
4307 for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
4308 if ie.suitable(ep_url):
4309 yield self.url_result(
4310 ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
4311 break
8bdd16b4 4312
16aa9ea4 4313 def _music_reponsive_list_entry(self, renderer):
4314 video_id = traverse_obj(renderer, ('playlistItemData', 'videoId'))
4315 if video_id:
4316 return self.url_result(f'https://music.youtube.com/watch?v={video_id}',
4317 ie=YoutubeIE.ie_key(), video_id=video_id)
4318 playlist_id = traverse_obj(renderer, ('navigationEndpoint', 'watchEndpoint', 'playlistId'))
4319 if playlist_id:
4320 video_id = traverse_obj(renderer, ('navigationEndpoint', 'watchEndpoint', 'videoId'))
4321 if video_id:
4322 return self.url_result(f'https://music.youtube.com/watch?v={video_id}&list={playlist_id}',
4323 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
4324 return self.url_result(f'https://music.youtube.com/playlist?list={playlist_id}',
4325 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
4326 browse_id = traverse_obj(renderer, ('navigationEndpoint', 'browseEndpoint', 'browseId'))
4327 if browse_id:
4328 return self.url_result(f'https://music.youtube.com/browse/{browse_id}',
4329 ie=YoutubeTabIE.ie_key(), video_id=browse_id)
4330
3d3dddc9 4331 def _shelf_entries_from_content(self, shelf_renderer):
4332 content = shelf_renderer.get('content')
4333 if not isinstance(content, dict):
8bdd16b4 4334 return
cd7c66cf 4335 renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
3d3dddc9 4336 if renderer:
4337 # TODO: add support for nested playlists so each shelf is processed
4338 # as separate playlist
4339 # TODO: this includes only first N items
86e5f3ed 4340 yield from self._grid_entries(renderer)
3d3dddc9 4341 renderer = content.get('horizontalListRenderer')
4342 if renderer:
4343 # TODO
4344 pass
8bdd16b4 4345
29f7c58a 4346 def _shelf_entries(self, shelf_renderer, skip_channels=False):
8bdd16b4 4347 ep = try_get(
4348 shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
14f25df2 4349 str)
8bdd16b4 4350 shelf_url = urljoin('https://www.youtube.com', ep)
3d3dddc9 4351 if shelf_url:
29f7c58a 4352 # Skipping links to another channels, note that checking for
4353 # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
4354 # will not work
4355 if skip_channels and '/channels?' in shelf_url:
4356 return
052e1350 4357 title = self._get_text(shelf_renderer, 'title')
3d3dddc9 4358 yield self.url_result(shelf_url, video_title=title)
4359 # Shelf may not contain shelf URL, fallback to extraction from content
86e5f3ed 4360 yield from self._shelf_entries_from_content(shelf_renderer)
c5e8d7af 4361
8bdd16b4 4362 def _playlist_entries(self, video_list_renderer):
4363 for content in video_list_renderer['contents']:
4364 if not isinstance(content, dict):
4365 continue
4366 renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
4367 if not isinstance(renderer, dict):
4368 continue
4369 video_id = renderer.get('videoId')
4370 if not video_id:
4371 continue
4372 yield self._extract_video(renderer)
07aeced6 4373
3462ffa8 4374 def _rich_entries(self, rich_grid_renderer):
80eb0bd9 4375 renderer = traverse_obj(
4376 rich_grid_renderer, ('content', ('videoRenderer', 'reelItemRenderer')), get_all=False) or {}
3462ffa8 4377 video_id = renderer.get('videoId')
4378 if not video_id:
4379 return
4380 yield self._extract_video(renderer)
4381
8bdd16b4 4382 def _video_entry(self, video_renderer):
4383 video_id = video_renderer.get('videoId')
4384 if video_id:
4385 return self._extract_video(video_renderer)
dacb3a86 4386
ad210f4f 4387 def _hashtag_tile_entry(self, hashtag_tile_renderer):
4388 url = urljoin('https://youtube.com', traverse_obj(
4389 hashtag_tile_renderer, ('onTapCommand', 'commandMetadata', 'webCommandMetadata', 'url')))
4390 if url:
4391 return self.url_result(
4392 url, ie=YoutubeTabIE.ie_key(), title=self._get_text(hashtag_tile_renderer, 'hashtag'))
4393
8bdd16b4 4394 def _post_thread_entries(self, post_thread_renderer):
4395 post_renderer = try_get(
4396 post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
4397 if not post_renderer:
4398 return
4399 # video attachment
4400 video_renderer = try_get(
895b0931 4401 post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict) or {}
4402 video_id = video_renderer.get('videoId')
4403 if video_id:
4404 entry = self._extract_video(video_renderer)
8bdd16b4 4405 if entry:
4406 yield entry
895b0931 4407 # playlist attachment
4408 playlist_id = try_get(
14f25df2 4409 post_renderer, lambda x: x['backstageAttachment']['playlistRenderer']['playlistId'], str)
895b0931 4410 if playlist_id:
4411 yield self.url_result(
e28f1c0a 4412 'https://www.youtube.com/playlist?list=%s' % playlist_id,
4413 ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
8bdd16b4 4414 # inline video links
4415 runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
4416 for run in runs:
4417 if not isinstance(run, dict):
4418 continue
4419 ep_url = try_get(
14f25df2 4420 run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], str)
8bdd16b4 4421 if not ep_url:
4422 continue
4423 if not YoutubeIE.suitable(ep_url):
4424 continue
4425 ep_video_id = YoutubeIE._match_id(ep_url)
4426 if video_id == ep_video_id:
4427 continue
895b0931 4428 yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=ep_video_id)
dacb3a86 4429
8bdd16b4 4430 def _post_thread_continuation_entries(self, post_thread_continuation):
4431 contents = post_thread_continuation.get('contents')
4432 if not isinstance(contents, list):
4433 return
4434 for content in contents:
4435 renderer = content.get('backstagePostThreadRenderer')
6b0b0a28 4436 if isinstance(renderer, dict):
4437 yield from self._post_thread_entries(renderer)
8bdd16b4 4438 continue
6b0b0a28 4439 renderer = content.get('videoRenderer')
4440 if isinstance(renderer, dict):
4441 yield self._video_entry(renderer)
07aeced6 4442
39ed931e 4443 r''' # unused
4444 def _rich_grid_entries(self, contents):
4445 for content in contents:
4446 video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
4447 if video_renderer:
4448 entry = self._video_entry(video_renderer)
4449 if entry:
4450 yield entry
4451 '''
52efa4b3 4452
0a5095fe 4453 def _report_history_entries(self, renderer):
4454 for url in traverse_obj(renderer, (
7a32c70d 4455 'rows', ..., 'reportHistoryTableRowRenderer', 'cells', ...,
4456 'reportHistoryTableCellRenderer', 'cell', 'reportHistoryTableTextCellRenderer', 'text', 'runs', ...,
0a5095fe 4457 'navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url')):
4458 yield self.url_result(urljoin('https://www.youtube.com', url), YoutubeIE)
4459
a6213a49 4460 def _extract_entries(self, parent_renderer, continuation_list):
4461 # continuation_list is modified in-place with continuation_list = [continuation_token]
4462 continuation_list[:] = [None]
4463 contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
4464 for content in contents:
4465 if not isinstance(content, dict):
4466 continue
16aa9ea4 4467 is_renderer = traverse_obj(
4468 content, 'itemSectionRenderer', 'musicShelfRenderer', 'musicShelfContinuation',
4469 expected_type=dict)
a6213a49 4470 if not is_renderer:
0a5095fe 4471 if content.get('richItemRenderer'):
4472 for entry in self._rich_entries(content['richItemRenderer']):
a6213a49 4473 yield entry
4474 continuation_list[0] = self._extract_continuation(parent_renderer)
0a5095fe 4475 elif content.get('reportHistorySectionRenderer'): # https://www.youtube.com/reporthistory
4476 table = traverse_obj(content, ('reportHistorySectionRenderer', 'table', 'tableRenderer'))
4477 yield from self._report_history_entries(table)
4478 continuation_list[0] = self._extract_continuation(table)
a6213a49 4479 continue
0a5095fe 4480
a6213a49 4481 isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
4482 for isr_content in isr_contents:
4483 if not isinstance(isr_content, dict):
8bdd16b4 4484 continue
69184e41 4485
a6213a49 4486 known_renderers = {
4487 'playlistVideoListRenderer': self._playlist_entries,
4488 'gridRenderer': self._grid_entries,
a17526e4 4489 'reelShelfRenderer': self._grid_entries,
4490 'shelfRenderer': self._shelf_entries,
16aa9ea4 4491 'musicResponsiveListItemRenderer': lambda x: [self._music_reponsive_list_entry(x)],
a6213a49 4492 'backstagePostThreadRenderer': self._post_thread_entries,
4493 'videoRenderer': lambda x: [self._video_entry(x)],
a61fd4cf 4494 'playlistRenderer': lambda x: self._grid_entries({'items': [{'playlistRenderer': x}]}),
4495 'channelRenderer': lambda x: self._grid_entries({'items': [{'channelRenderer': x}]}),
ad210f4f 4496 'hashtagTileRenderer': lambda x: [self._hashtag_tile_entry(x)]
a6213a49 4497 }
4498 for key, renderer in isr_content.items():
4499 if key not in known_renderers:
4500 continue
4501 for entry in known_renderers[key](renderer):
4502 if entry:
4503 yield entry
4504 continuation_list[0] = self._extract_continuation(renderer)
4505 break
70d5c17b 4506
4507 if not continuation_list[0]:
a6213a49 4508 continuation_list[0] = self._extract_continuation(is_renderer)
3462ffa8 4509
a6213a49 4510 if not continuation_list[0]:
4511 continuation_list[0] = self._extract_continuation(parent_renderer)
4512
4513 def _entries(self, tab, item_id, ytcfg, account_syncid, visitor_data):
4514 continuation_list = [None]
4515 extract_entries = lambda x: self._extract_entries(x, continuation_list)
29f7c58a 4516 tab_content = try_get(tab, lambda x: x['content'], dict)
4517 if not tab_content:
4518 return
3462ffa8 4519 parent_renderer = (
29f7c58a 4520 try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
4521 or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
86e5f3ed 4522 yield from extract_entries(parent_renderer)
3462ffa8 4523 continuation = continuation_list[0]
d069eca7 4524
8bdd16b4 4525 for page_num in itertools.count(1):
4526 if not continuation:
4527 break
99e9e001 4528 headers = self.generate_api_headers(
4529 ytcfg=ytcfg, account_syncid=account_syncid, visitor_data=visitor_data)
79360d99 4530 response = self._extract_response(
86e5f3ed 4531 item_id=f'{item_id} page {page_num}',
fe93e2c4 4532 query=continuation, headers=headers, ytcfg=ytcfg,
79360d99 4533 check_get_keys=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
a5c56234
M
4534
4535 if not response:
8bdd16b4 4536 break
ac56cf38 4537 # Extracting updated visitor data is required to prevent an infinite extraction loop in some cases
4538 # See: https://github.com/ytdl-org/youtube-dl/issues/28702
4539 visitor_data = self._extract_visitor_data(response) or visitor_data
ebf1b291 4540
a1b535bd 4541 known_renderers = {
e4b98809 4542 'videoRenderer': (self._grid_entries, 'items'), # for membership tab
a1b535bd 4543 'gridPlaylistRenderer': (self._grid_entries, 'items'),
4544 'gridVideoRenderer': (self._grid_entries, 'items'),
d61fc646 4545 'gridChannelRenderer': (self._grid_entries, 'items'),
a1b535bd 4546 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
cd7c66cf 4547 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
9ba5705a 4548 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
0a5095fe 4549 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents'),
4550 'reportHistoryTableRowRenderer': (self._report_history_entries, 'rows'),
1fb53b94 4551 'playlistVideoListContinuation': (self._playlist_entries, None),
4552 'gridContinuation': (self._grid_entries, None),
4553 'itemSectionContinuation': (self._post_thread_continuation_entries, None),
4554 'sectionListContinuation': (extract_entries, None), # for feeds
a1b535bd 4555 }
1fb53b94 4556
4557 continuation_items = traverse_obj(response, (
4558 ('onResponseReceivedActions', 'onResponseReceivedEndpoints'), ...,
4559 'appendContinuationItemsAction', 'continuationItems'
4560 ), 'continuationContents', get_all=False)
4561 continuation_item = traverse_obj(continuation_items, 0, None, expected_type=dict, default={})
4562
a1b535bd 4563 video_items_renderer = None
1fb53b94 4564 for key in continuation_item.keys():
a1b535bd 4565 if key not in known_renderers:
8bdd16b4 4566 continue
1fb53b94 4567 func, parent_key = known_renderers[key]
4568 video_items_renderer = {parent_key: continuation_items} if parent_key else continuation_items
9ba5705a 4569 continuation_list = [None]
1fb53b94 4570 yield from func(video_items_renderer)
9ba5705a 4571 continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
1fb53b94 4572
4573 if not video_items_renderer:
a1b535bd 4574 break
9558dcec 4575
8bdd16b4 4576 @staticmethod
7c219ea6 4577 def _extract_selected_tab(tabs, fatal=True):
8bdd16b4 4578 for tab in tabs:
cd684175 4579 renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
4580 if renderer.get('selected') is True:
4581 return renderer
2b3c2546 4582 else:
7c219ea6 4583 if fatal:
4584 raise ExtractorError('Unable to find selected tab')
b82f815f 4585
61d3665d 4586 def _extract_uploader(self, data):
8bdd16b4 4587 uploader = {}
61d3665d 4588 renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarSecondaryInfoRenderer') or {}
47193e02 4589 owner = try_get(
4590 renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
4591 if owner:
61d3665d 4592 owner_text = owner.get('text')
4593 uploader['uploader'] = self._search_regex(
4594 r'^by (.+) and \d+ others?$', owner_text, 'uploader', default=owner_text)
47193e02 4595 uploader['uploader_id'] = try_get(
14f25df2 4596 owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], str)
47193e02 4597 uploader['uploader_url'] = urljoin(
4598 'https://www.youtube.com/',
14f25df2 4599 try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], str))
7a32c70d 4600 return filter_dict(uploader)
8bdd16b4 4601
ac56cf38 4602 def _extract_from_tabs(self, item_id, ytcfg, data, tabs):
b60419c5 4603 playlist_id = title = description = channel_url = channel_name = channel_id = None
ac56cf38 4604 tags = []
b60419c5 4605
8bdd16b4 4606 selected_tab = self._extract_selected_tab(tabs)
f0d785d3 4607 primary_sidebar_renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarPrimaryInfoRenderer')
8bdd16b4 4608 renderer = try_get(
4609 data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
4610 if renderer:
b60419c5 4611 channel_name = renderer.get('title')
4612 channel_url = renderer.get('channelUrl')
4613 channel_id = renderer.get('externalId')
39ed931e 4614 else:
64c0d954 4615 renderer = try_get(
4616 data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
39ed931e 4617
8bdd16b4 4618 if renderer:
4619 title = renderer.get('title')
ecc97af3 4620 description = renderer.get('description', '')
b60419c5 4621 playlist_id = channel_id
4622 tags = renderer.get('keywords', '').split()
b60419c5 4623
301d07fc 4624 # We can get the uncropped banner/avatar by replacing the crop params with '=s0'
4625 # See: https://github.com/yt-dlp/yt-dlp/issues/2237#issuecomment-1013694714
4626 def _get_uncropped(url):
4627 return url_or_none((url or '').split('=')[0] + '=s0')
4628
4629 avatar_thumbnails = self._extract_thumbnails(renderer, 'avatar')
4630 if avatar_thumbnails:
4631 uncropped_avatar = _get_uncropped(avatar_thumbnails[0]['url'])
4632 if uncropped_avatar:
4633 avatar_thumbnails.append({
4634 'url': uncropped_avatar,
4635 'id': 'avatar_uncropped',
4636 'preference': 1
4637 })
4638
4639 channel_banners = self._extract_thumbnails(
4640 data, ('header', ..., ['banner', 'mobileBanner', 'tvBanner']))
4641 for banner in channel_banners:
4642 banner['preference'] = -10
4643
4644 if channel_banners:
4645 uncropped_banner = _get_uncropped(channel_banners[0]['url'])
4646 if uncropped_banner:
4647 channel_banners.append({
4648 'url': uncropped_banner,
4649 'id': 'banner_uncropped',
4650 'preference': -5
4651 })
4652
4653 primary_thumbnails = self._extract_thumbnails(
a17526e4 4654 primary_sidebar_renderer, ('thumbnailRenderer', ('playlistVideoThumbnailRenderer', 'playlistCustomThumbnailRenderer'), 'thumbnail'))
a709d873 4655
3462ffa8 4656 if playlist_id is None:
70d5c17b 4657 playlist_id = item_id
f0d785d3 4658
4659 playlist_stats = traverse_obj(primary_sidebar_renderer, 'stats')
c26f9b99 4660 last_updated_unix = self._parse_time_text(self._get_text(playlist_stats, 2))
70d5c17b 4661 if title is None:
f0d785d3 4662 title = self._get_text(data, ('header', 'hashtagHeaderRenderer', 'hashtag')) or playlist_id
b60419c5 4663 title += format_field(selected_tab, 'title', ' - %s')
cd684175 4664 title += format_field(selected_tab, 'expandedText', ' - %s')
f0d785d3 4665
b60419c5 4666 metadata = {
4667 'playlist_id': playlist_id,
4668 'playlist_title': title,
4669 'playlist_description': description,
4670 'uploader': channel_name,
4671 'uploader_id': channel_id,
4672 'uploader_url': channel_url,
301d07fc 4673 'thumbnails': primary_thumbnails + avatar_thumbnails + channel_banners,
b60419c5 4674 'tags': tags,
f0d785d3 4675 'view_count': self._get_count(playlist_stats, 1),
4676 'availability': self._extract_availability(data),
4677 'modified_date': strftime_or_none(last_updated_unix, '%Y%m%d'),
6c73052c 4678 'playlist_count': self._get_count(playlist_stats, 0),
4679 'channel_follower_count': self._get_count(data, ('header', ..., 'subscriberCountText')),
b60419c5 4680 }
4681 if not channel_id:
4682 metadata.update(self._extract_uploader(data))
4683 metadata.update({
4684 'channel': metadata['uploader'],
4685 'channel_id': metadata['uploader_id'],
4686 'channel_url': metadata['uploader_url']})
4687 return self.playlist_result(
d069eca7 4688 self._entries(
ac56cf38 4689 selected_tab, playlist_id, ytcfg,
4690 self._extract_account_syncid(ytcfg, data),
4691 self._extract_visitor_data(data, ytcfg)),
b60419c5 4692 **metadata)
73c4ac2c 4693
6e634cbe 4694 def _extract_inline_playlist(self, playlist, playlist_id, data, ytcfg):
ac56cf38 4695 first_id = last_id = response = None
2be71994 4696 for page_num in itertools.count(1):
cd7c66cf 4697 videos = list(self._playlist_entries(playlist))
4698 if not videos:
4699 return
2be71994 4700 start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
4701 if start >= len(videos):
4702 return
24146491 4703 yield from videos[start:]
2be71994 4704 first_id = first_id or videos[0]['id']
4705 last_id = videos[-1]['id']
79360d99 4706 watch_endpoint = try_get(
4707 playlist, lambda x: x['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
ac56cf38 4708 headers = self.generate_api_headers(
4709 ytcfg=ytcfg, account_syncid=self._extract_account_syncid(ytcfg, data),
4710 visitor_data=self._extract_visitor_data(response, data, ytcfg))
79360d99 4711 query = {
4712 'playlistId': playlist_id,
4713 'videoId': watch_endpoint.get('videoId') or last_id,
4714 'index': watch_endpoint.get('index') or len(videos),
4715 'params': watch_endpoint.get('params') or 'OAE%3D'
4716 }
4717 response = self._extract_response(
4718 item_id='%s page %d' % (playlist_id, page_num),
fe93e2c4 4719 query=query, ep='next', headers=headers, ytcfg=ytcfg,
79360d99 4720 check_get_keys='contents'
4721 )
cd7c66cf 4722 playlist = try_get(
79360d99 4723 response, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
cd7c66cf 4724
ac56cf38 4725 def _extract_from_playlist(self, item_id, url, data, playlist, ytcfg):
8bdd16b4 4726 title = playlist.get('title') or try_get(
14f25df2 4727 data, lambda x: x['titleText']['simpleText'], str)
8bdd16b4 4728 playlist_id = playlist.get('playlistId') or item_id
cd7c66cf 4729
4730 # Delegating everything except mix playlists to regular tab-based playlist URL
29f7c58a 4731 playlist_url = urljoin(url, try_get(
4732 playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
14f25df2 4733 str))
6e634cbe 4734
4735 # Some playlists are unviewable but YouTube still provides a link to the (broken) playlist page [1]
4736 # [1] MLCT, RLTDwFCb4jeqaKWnciAYM-ZVHg
4737 is_known_unviewable = re.fullmatch(r'MLCT|RLTD[\w-]{22}', playlist_id)
4738
4739 if playlist_url and playlist_url != url and not is_known_unviewable:
29f7c58a 4740 return self.url_result(
4741 playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
4742 video_title=title)
cd7c66cf 4743
8bdd16b4 4744 return self.playlist_result(
6e634cbe 4745 self._extract_inline_playlist(playlist, playlist_id, data, ytcfg),
cd7c66cf 4746 playlist_id=playlist_id, playlist_title=title)
c5e8d7af 4747
47193e02 4748 def _extract_availability(self, data):
4749 """
4750 Gets the availability of a given playlist/tab.
4751 Note: Unless YouTube tells us explicitly, we do not assume it is public
4752 @param data: response
4753 """
47193e02 4754 renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarPrimaryInfoRenderer') or {}
c26f9b99 4755
4756 player_header_privacy = traverse_obj(
4757 data, ('header', 'playlistHeaderRenderer', 'privacy'), expected_type=str)
4758
4759 badges = self._extract_badges(renderer)
47193e02 4760
4761 # Personal playlists, when authenticated, have a dropdown visibility selector instead of a badge
c26f9b99 4762 privacy_setting_icon = traverse_obj(
4763 renderer, (
4764 'privacyForm', 'dropdownFormFieldRenderer', 'dropdown', 'dropdownRenderer', 'entries',
4765 lambda _, v: v['privacyDropdownItemRenderer']['isSelected'], 'privacyDropdownItemRenderer', 'icon', 'iconType'),
4766 get_all=False, expected_type=str)
47193e02 4767
c26f9b99 4768 return (
4769 'public' if (
4770 self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
4771 or player_header_privacy == 'PUBLIC'
4772 or privacy_setting_icon == 'PRIVACY_PUBLIC')
4773 else self._availability(
4774 is_private=(
4775 self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE)
4776 or player_header_privacy == 'PRIVATE' if player_header_privacy is not None
4777 else privacy_setting_icon == 'PRIVACY_PRIVATE' if privacy_setting_icon is not None else None),
4778 is_unlisted=(
4779 self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED)
4780 or player_header_privacy == 'UNLISTED' if player_header_privacy is not None
4781 else privacy_setting_icon == 'PRIVACY_UNLISTED' if privacy_setting_icon is not None else None),
4782 needs_subscription=self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION) or None,
4783 needs_premium=self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or None,
4784 needs_auth=False))
47193e02 4785
4786 @staticmethod
4787 def _extract_sidebar_info_renderer(data, info_renderer, expected_type=dict):
4788 sidebar_renderer = try_get(
4789 data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list) or []
4790 for item in sidebar_renderer:
4791 renderer = try_get(item, lambda x: x[info_renderer], expected_type)
4792 if renderer:
4793 return renderer
4794
ac56cf38 4795 def _reload_with_unavailable_videos(self, item_id, data, ytcfg):
358de58c 4796 """
4797 Get playlist with unavailable videos if the 'show unavailable videos' button exists.
4798 """
5d342002 4799 browse_id = params = None
47193e02 4800 renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarPrimaryInfoRenderer')
4801 if not renderer:
4802 return
4803 menu_renderer = try_get(
4804 renderer, lambda x: x['menu']['menuRenderer']['items'], list) or []
4805 for menu_item in menu_renderer:
4806 if not isinstance(menu_item, dict):
358de58c 4807 continue
47193e02 4808 nav_item_renderer = menu_item.get('menuNavigationItemRenderer')
4809 text = try_get(
14f25df2 4810 nav_item_renderer, lambda x: x['text']['simpleText'], str)
47193e02 4811 if not text or text.lower() != 'show unavailable videos':
4812 continue
4813 browse_endpoint = try_get(
4814 nav_item_renderer, lambda x: x['navigationEndpoint']['browseEndpoint'], dict) or {}
4815 browse_id = browse_endpoint.get('browseId')
4816 params = browse_endpoint.get('params')
4817 break
5d342002 4818
11f9be09 4819 headers = self.generate_api_headers(
99e9e001 4820 ytcfg=ytcfg, account_syncid=self._extract_account_syncid(ytcfg, data),
ac56cf38 4821 visitor_data=self._extract_visitor_data(data, ytcfg))
47193e02 4822 query = {
4823 'params': params or 'wgYCCAA=',
4824 'browseId': browse_id or 'VL%s' % item_id
4825 }
4826 return self._extract_response(
4827 item_id=item_id, headers=headers, query=query,
fe93e2c4 4828 check_get_keys='contents', fatal=False, ytcfg=ytcfg,
47193e02 4829 note='Downloading API JSON with unavailable videos')
358de58c 4830
2762dbb1 4831 @functools.cached_property
a25bca9f 4832 def skip_webpage(self):
4833 return 'webpage' in self._configuration_arg('skip', ie_key=YoutubeTabIE.ie_key())
4834
ac56cf38 4835 def _extract_webpage(self, url, item_id, fatal=True):
be5c1ae8 4836 webpage, data = None, None
4837 for retry in self.RetryManager(fatal=fatal):
ac56cf38 4838 try:
be5c1ae8 4839 webpage = self._download_webpage(url, item_id, note='Downloading webpage')
ac56cf38 4840 data = self.extract_yt_initial_data(item_id, webpage or '', fatal=fatal) or {}
4841 except ExtractorError as e:
4842 if isinstance(e.cause, network_exceptions):
14f25df2 4843 if not isinstance(e.cause, urllib.error.HTTPError) or e.cause.code not in (403, 429):
be5c1ae8 4844 retry.error = e
4845 continue
4846 self._error_or_warning(e, fatal=fatal)
14fdfea9 4847 break
ac56cf38 4848
be5c1ae8 4849 try:
4850 self._extract_and_report_alerts(data)
4851 except ExtractorError as e:
4852 self._error_or_warning(e, fatal=fatal)
4853 break
ac56cf38 4854
be5c1ae8 4855 # Sometimes youtube returns a webpage with incomplete ytInitialData
4856 # See: https://github.com/yt-dlp/yt-dlp/issues/116
4857 if not traverse_obj(data, 'contents', 'currentVideoEndpoint', 'onResponseReceivedActions'):
4858 retry.error = ExtractorError('Incomplete yt initial data received')
4859 continue
ac56cf38 4860
cd7c66cf 4861 return webpage, data
4862
a25bca9f 4863 def _report_playlist_authcheck(self, ytcfg, fatal=True):
4864 """Use if failed to extract ytcfg (and data) from initial webpage"""
4865 if not ytcfg and self.is_authenticated:
4866 msg = 'Playlists that require authentication may not extract correctly without a successful webpage download'
4867 if 'authcheck' not in self._configuration_arg('skip', ie_key=YoutubeTabIE.ie_key()) and fatal:
4868 raise ExtractorError(
4869 f'{msg}. If you are not downloading private content, or '
4870 'your cookies are only for the first account and channel,'
4871 ' pass "--extractor-args youtubetab:skip=authcheck" to skip this check',
4872 expected=True)
4873 self.report_warning(msg, only_once=True)
4874
ac56cf38 4875 def _extract_data(self, url, item_id, ytcfg=None, fatal=True, webpage_fatal=False, default_client='web'):
4876 data = None
a25bca9f 4877 if not self.skip_webpage:
ac56cf38 4878 webpage, data = self._extract_webpage(url, item_id, fatal=webpage_fatal)
4879 ytcfg = ytcfg or self.extract_ytcfg(item_id, webpage)
1108613f 4880 # Reject webpage data if redirected to home page without explicitly requesting
4881 selected_tab = self._extract_selected_tab(traverse_obj(
7c219ea6 4882 data, ('contents', 'twoColumnBrowseResultsRenderer', 'tabs'), expected_type=list, default=[]), fatal=False) or {}
1108613f 4883 if (url != 'https://www.youtube.com/feed/recommended'
4884 and selected_tab.get('tabIdentifier') == 'FEwhat_to_watch' # Home page
4885 and 'no-youtube-channel-redirect' not in self.get_param('compat_opts', [])):
4886 msg = 'The channel/playlist does not exist and the URL redirected to youtube.com home page'
4887 if fatal:
4888 raise ExtractorError(msg, expected=True)
4889 self.report_warning(msg, only_once=True)
ac56cf38 4890 if not data:
a25bca9f 4891 self._report_playlist_authcheck(ytcfg, fatal=fatal)
ac56cf38 4892 data = self._extract_tab_endpoint(url, item_id, ytcfg, fatal=fatal, default_client=default_client)
4893 return data, ytcfg
4894
4895 def _extract_tab_endpoint(self, url, item_id, ytcfg=None, fatal=True, default_client='web'):
4896 headers = self.generate_api_headers(ytcfg=ytcfg, default_client=default_client)
4897 resolve_response = self._extract_response(
4898 item_id=item_id, query={'url': url}, check_get_keys='endpoint', headers=headers, ytcfg=ytcfg, fatal=fatal,
4899 ep='navigation/resolve_url', note='Downloading API parameters API JSON', default_client=default_client)
4900 endpoints = {'browseEndpoint': 'browse', 'watchEndpoint': 'next'}
4901 for ep_key, ep in endpoints.items():
4902 params = try_get(resolve_response, lambda x: x['endpoint'][ep_key], dict)
4903 if params:
4904 return self._extract_response(
4905 item_id=item_id, query=params, ep=ep, headers=headers,
4906 ytcfg=ytcfg, fatal=fatal, default_client=default_client,
7c219ea6 4907 check_get_keys=('contents', 'currentVideoEndpoint', 'onResponseReceivedActions'))
ac56cf38 4908 err_note = 'Failed to resolve url (does the playlist exist?)'
4909 if fatal:
4910 raise ExtractorError(err_note, expected=True)
4911 self.report_warning(err_note, item_id)
4912
a6213a49 4913 _SEARCH_PARAMS = None
4914
af5c1c55 4915 def _search_results(self, query, params=NO_DEFAULT, default_client='web'):
a6213a49 4916 data = {'query': query}
4917 if params is NO_DEFAULT:
4918 params = self._SEARCH_PARAMS
4919 if params:
4920 data['params'] = params
16aa9ea4 4921
4922 content_keys = (
4923 ('contents', 'twoColumnSearchResultsRenderer', 'primaryContents', 'sectionListRenderer', 'contents'),
4924 ('onResponseReceivedCommands', 0, 'appendContinuationItemsAction', 'continuationItems'),
4925 # ytmusic search
4926 ('contents', 'tabbedSearchResultsRenderer', 'tabs', 0, 'tabRenderer', 'content', 'sectionListRenderer', 'contents'),
4927 ('continuationContents', ),
4928 )
a25bca9f 4929 display_id = f'query "{query}"'
86e5f3ed 4930 check_get_keys = tuple({keys[0] for keys in content_keys})
a25bca9f 4931 ytcfg = self._download_ytcfg(default_client, display_id) if not self.skip_webpage else {}
4932 self._report_playlist_authcheck(ytcfg, fatal=False)
16aa9ea4 4933
a61fd4cf 4934 continuation_list = [None]
a25bca9f 4935 search = None
a6213a49 4936 for page_num in itertools.count(1):
a61fd4cf 4937 data.update(continuation_list[0] or {})
a25bca9f 4938 headers = self.generate_api_headers(
4939 ytcfg=ytcfg, visitor_data=self._extract_visitor_data(search), default_client=default_client)
a6213a49 4940 search = self._extract_response(
a25bca9f 4941 item_id=f'{display_id} page {page_num}', ep='search', query=data,
4942 default_client=default_client, check_get_keys=check_get_keys, ytcfg=ytcfg, headers=headers)
16aa9ea4 4943 slr_contents = traverse_obj(search, *content_keys)
4944 yield from self._extract_entries({'contents': list(variadic(slr_contents))}, continuation_list)
a61fd4cf 4945 if not continuation_list[0]:
a6213a49 4946 break
4947
4948
4949class YoutubeTabIE(YoutubeTabBaseInfoExtractor):
4950 IE_DESC = 'YouTube Tabs'
4951 _VALID_URL = r'''(?x:
4952 https?://
4953 (?:\w+\.)?
4954 (?:
4955 youtube(?:kids)?\.com|
4956 %(invidious)s
4957 )/
4958 (?:
4959 (?P<channel_type>channel|c|user|browse)/|
4960 (?P<not_channel>
4961 feed/|hashtag/|
4962 (?:playlist|watch)\?.*?\blist=
4963 )|
4964 (?!(?:%(reserved_names)s)\b) # Direct URLs
4965 )
4966 (?P<id>[^/?\#&]+)
4967 )''' % {
4968 'reserved_names': YoutubeBaseInfoExtractor._RESERVED_NAMES,
4969 'invidious': '|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
4970 }
4971 IE_NAME = 'youtube:tab'
4972
4973 _TESTS = [{
4974 'note': 'playlists, multipage',
4975 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
4976 'playlist_mincount': 94,
4977 'info_dict': {
4978 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
976ae3ea 4979 'title': 'Igor Kleiner - Playlists',
a6213a49 4980 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
976ae3ea 4981 'uploader': 'Igor Kleiner',
a6213a49 4982 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
976ae3ea 4983 'channel': 'Igor Kleiner',
4984 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
4985 'tags': ['"критическое', 'мышление"', '"наука', 'просто"', 'математика', '"анализ', 'данных"'],
4986 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
4987 'uploader_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
6c73052c 4988 'channel_follower_count': int
a6213a49 4989 },
4990 }, {
4991 'note': 'playlists, multipage, different order',
4992 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
4993 'playlist_mincount': 94,
4994 'info_dict': {
4995 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
976ae3ea 4996 'title': 'Igor Kleiner - Playlists',
a6213a49 4997 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
4998 'uploader_id': 'UCqj7Cz7revf5maW9g5pgNcg',
976ae3ea 4999 'uploader': 'Igor Kleiner',
5000 'uploader_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
5001 'tags': ['"критическое', 'мышление"', '"наука', 'просто"', 'математика', '"анализ', 'данных"'],
5002 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
5003 'channel': 'Igor Kleiner',
5004 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
6c73052c 5005 'channel_follower_count': int
a6213a49 5006 },
5007 }, {
5008 'note': 'playlists, series',
5009 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
5010 'playlist_mincount': 5,
5011 'info_dict': {
5012 'id': 'UCYO_jab_esuFRV4b17AJtAw',
5013 'title': '3Blue1Brown - Playlists',
5014 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
5015 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
5016 'uploader': '3Blue1Brown',
976ae3ea 5017 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
5018 'uploader_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
5019 'channel': '3Blue1Brown',
5020 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
5021 'tags': ['Mathematics'],
6c73052c 5022 'channel_follower_count': int
a6213a49 5023 },
5024 }, {
5025 'note': 'playlists, singlepage',
5026 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
5027 'playlist_mincount': 4,
5028 'info_dict': {
5029 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
5030 'title': 'ThirstForScience - Playlists',
5031 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
5032 'uploader': 'ThirstForScience',
5033 'uploader_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
976ae3ea 5034 'uploader_url': 'https://www.youtube.com/channel/UCAEtajcuhQ6an9WEzY9LEMQ',
5035 'channel_url': 'https://www.youtube.com/channel/UCAEtajcuhQ6an9WEzY9LEMQ',
5036 'channel_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
5037 'tags': 'count:13',
5038 'channel': 'ThirstForScience',
6c73052c 5039 'channel_follower_count': int
a6213a49 5040 }
5041 }, {
5042 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
5043 'only_matching': True,
5044 }, {
5045 'note': 'basic, single video playlist',
5046 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
5047 'info_dict': {
5048 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5049 'uploader': 'Sergey M.',
5050 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
5051 'title': 'youtube-dl public playlist',
976ae3ea 5052 'description': '',
5053 'tags': [],
5054 'view_count': int,
5055 'modified_date': '20201130',
5056 'channel': 'Sergey M.',
5057 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5058 'uploader_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5059 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
c26f9b99 5060 'availability': 'public',
a6213a49 5061 },
5062 'playlist_count': 1,
5063 }, {
5064 'note': 'empty playlist',
5065 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
5066 'info_dict': {
5067 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5068 'uploader': 'Sergey M.',
5069 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
5070 'title': 'youtube-dl empty playlist',
976ae3ea 5071 'tags': [],
5072 'channel': 'Sergey M.',
5073 'description': '',
5074 'modified_date': '20160902',
5075 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
5076 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5077 'uploader_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
c26f9b99 5078 'availability': 'public',
a6213a49 5079 },
5080 'playlist_count': 0,
5081 }, {
5082 'note': 'Home tab',
5083 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
5084 'info_dict': {
5085 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5086 'title': 'lex will - Home',
5087 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5088 'uploader': 'lex will',
5089 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5090 'channel': 'lex will',
5091 'tags': ['bible', 'history', 'prophesy'],
5092 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5093 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5094 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
6c73052c 5095 'channel_follower_count': int
a6213a49 5096 },
5097 'playlist_mincount': 2,
5098 }, {
5099 'note': 'Videos tab',
5100 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
5101 'info_dict': {
5102 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5103 'title': 'lex will - Videos',
5104 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5105 'uploader': 'lex will',
5106 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5107 'tags': ['bible', 'history', 'prophesy'],
5108 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5109 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5110 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5111 'channel': 'lex will',
6c73052c 5112 'channel_follower_count': int
a6213a49 5113 },
5114 'playlist_mincount': 975,
5115 }, {
5116 'note': 'Videos tab, sorted by popular',
5117 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
5118 'info_dict': {
5119 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5120 'title': 'lex will - Videos',
5121 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5122 'uploader': 'lex will',
5123 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5124 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5125 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5126 'channel': 'lex will',
5127 'tags': ['bible', 'history', 'prophesy'],
5128 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
6c73052c 5129 'channel_follower_count': int
a6213a49 5130 },
5131 'playlist_mincount': 199,
5132 }, {
5133 'note': 'Playlists tab',
5134 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
5135 'info_dict': {
5136 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5137 'title': 'lex will - Playlists',
5138 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5139 'uploader': 'lex will',
5140 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5141 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5142 'channel': 'lex will',
5143 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5144 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5145 'tags': ['bible', 'history', 'prophesy'],
6c73052c 5146 'channel_follower_count': int
a6213a49 5147 },
5148 'playlist_mincount': 17,
5149 }, {
5150 'note': 'Community tab',
5151 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
5152 'info_dict': {
5153 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5154 'title': 'lex will - Community',
5155 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5156 'uploader': 'lex will',
5157 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5158 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5159 'channel': 'lex will',
5160 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5161 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5162 'tags': ['bible', 'history', 'prophesy'],
6c73052c 5163 'channel_follower_count': int
a6213a49 5164 },
5165 'playlist_mincount': 18,
5166 }, {
5167 'note': 'Channels tab',
5168 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
5169 'info_dict': {
5170 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5171 'title': 'lex will - Channels',
5172 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
5173 'uploader': 'lex will',
5174 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
976ae3ea 5175 'uploader_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5176 'channel': 'lex will',
5177 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
5178 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
5179 'tags': ['bible', 'history', 'prophesy'],
6c73052c 5180 'channel_follower_count': int
a6213a49 5181 },
5182 'playlist_mincount': 12,
5183 }, {
5184 'note': 'Search tab',
5185 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
5186 'playlist_mincount': 40,
5187 'info_dict': {
5188 'id': 'UCYO_jab_esuFRV4b17AJtAw',
5189 'title': '3Blue1Brown - Search - linear algebra',
5190 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
5191 'uploader': '3Blue1Brown',
5192 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
976ae3ea 5193 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
5194 'uploader_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
5195 'tags': ['Mathematics'],
5196 'channel': '3Blue1Brown',
5197 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
6c73052c 5198 'channel_follower_count': int
a6213a49 5199 },
5200 }, {
5201 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5202 'only_matching': True,
5203 }, {
5204 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5205 'only_matching': True,
5206 }, {
5207 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
5208 'only_matching': True,
5209 }, {
5210 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
5211 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
5212 'info_dict': {
5213 'title': '29C3: Not my department',
5214 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
5215 'uploader': 'Christiaan008',
5216 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
5217 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
976ae3ea 5218 'tags': [],
5219 'uploader_url': 'https://www.youtube.com/c/ChRiStIaAn008',
5220 'view_count': int,
5221 'modified_date': '20150605',
5222 'channel_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
5223 'channel_url': 'https://www.youtube.com/c/ChRiStIaAn008',
5224 'channel': 'Christiaan008',
c26f9b99 5225 'availability': 'public',
a6213a49 5226 },
5227 'playlist_count': 96,
5228 }, {
5229 'note': 'Large playlist',
5230 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
5231 'info_dict': {
5232 'title': 'Uploads from Cauchemar',
5233 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
5234 'uploader': 'Cauchemar',
5235 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
976ae3ea 5236 'channel_url': 'https://www.youtube.com/c/Cauchemar89',
5237 'tags': [],
5238 'modified_date': r're:\d{8}',
5239 'channel': 'Cauchemar',
5240 'uploader_url': 'https://www.youtube.com/c/Cauchemar89',
5241 'view_count': int,
5242 'description': '',
5243 'channel_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
c26f9b99 5244 'availability': 'public',
a6213a49 5245 },
5246 'playlist_mincount': 1123,
976ae3ea 5247 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
a6213a49 5248 }, {
5249 'note': 'even larger playlist, 8832 videos',
5250 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
5251 'only_matching': True,
5252 }, {
5253 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
5254 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
5255 'info_dict': {
5256 'title': 'Uploads from Interstellar Movie',
5257 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
5258 'uploader': 'Interstellar Movie',
5259 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
976ae3ea 5260 'uploader_url': 'https://www.youtube.com/c/InterstellarMovie',
5261 'tags': [],
5262 'view_count': int,
5263 'channel_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
5264 'channel_url': 'https://www.youtube.com/c/InterstellarMovie',
5265 'channel': 'Interstellar Movie',
5266 'description': '',
5267 'modified_date': r're:\d{8}',
c26f9b99 5268 'availability': 'public',
a6213a49 5269 },
5270 'playlist_mincount': 21,
5271 }, {
5272 'note': 'Playlist with "show unavailable videos" button',
5273 'url': 'https://www.youtube.com/playlist?list=UUTYLiWFZy8xtPwxFwX9rV7Q',
5274 'info_dict': {
5275 'title': 'Uploads from Phim Siêu Nhân Nhật Bản',
5276 'id': 'UUTYLiWFZy8xtPwxFwX9rV7Q',
5277 'uploader': 'Phim Siêu Nhân Nhật Bản',
5278 'uploader_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
976ae3ea 5279 'view_count': int,
5280 'channel': 'Phim Siêu Nhân Nhật Bản',
5281 'tags': [],
5282 'uploader_url': 'https://www.youtube.com/channel/UCTYLiWFZy8xtPwxFwX9rV7Q',
5283 'description': '',
5284 'channel_url': 'https://www.youtube.com/channel/UCTYLiWFZy8xtPwxFwX9rV7Q',
5285 'channel_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
5286 'modified_date': r're:\d{8}',
c26f9b99 5287 'availability': 'public',
a6213a49 5288 },
5289 'playlist_mincount': 200,
976ae3ea 5290 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
a6213a49 5291 }, {
5292 'note': 'Playlist with unavailable videos in page 7',
5293 'url': 'https://www.youtube.com/playlist?list=UU8l9frL61Yl5KFOl87nIm2w',
5294 'info_dict': {
5295 'title': 'Uploads from BlankTV',
5296 'id': 'UU8l9frL61Yl5KFOl87nIm2w',
5297 'uploader': 'BlankTV',
5298 'uploader_id': 'UC8l9frL61Yl5KFOl87nIm2w',
976ae3ea 5299 'channel': 'BlankTV',
5300 'channel_url': 'https://www.youtube.com/c/blanktv',
5301 'channel_id': 'UC8l9frL61Yl5KFOl87nIm2w',
5302 'view_count': int,
5303 'tags': [],
5304 'uploader_url': 'https://www.youtube.com/c/blanktv',
5305 'modified_date': r're:\d{8}',
5306 'description': '',
c26f9b99 5307 'availability': 'public',
a6213a49 5308 },
5309 'playlist_mincount': 1000,
976ae3ea 5310 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
a6213a49 5311 }, {
5312 'note': 'https://github.com/ytdl-org/youtube-dl/issues/21844',
5313 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
5314 'info_dict': {
5315 'title': 'Data Analysis with Dr Mike Pound',
5316 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
5317 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
5318 'uploader': 'Computerphile',
5319 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
976ae3ea 5320 'uploader_url': 'https://www.youtube.com/user/Computerphile',
5321 'tags': [],
5322 'view_count': int,
5323 'channel_id': 'UC9-y-6csu5WGm29I7JiwpnA',
5324 'channel_url': 'https://www.youtube.com/user/Computerphile',
5325 'channel': 'Computerphile',
c26f9b99 5326 'availability': 'public',
a6213a49 5327 },
5328 'playlist_mincount': 11,
5329 }, {
5330 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
5331 'only_matching': True,
5332 }, {
5333 'note': 'Playlist URL that does not actually serve a playlist',
5334 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
5335 'info_dict': {
5336 'id': 'FqZTN594JQw',
5337 'ext': 'webm',
5338 'title': "Smiley's People 01 detective, Adventure Series, Action",
5339 'uploader': 'STREEM',
5340 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
5341 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
5342 'upload_date': '20150526',
5343 'license': 'Standard YouTube License',
5344 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
5345 'categories': ['People & Blogs'],
5346 'tags': list,
5347 'view_count': int,
5348 'like_count': int,
a6213a49 5349 },
5350 'params': {
5351 'skip_download': True,
5352 },
5353 'skip': 'This video is not available.',
5354 'add_ie': [YoutubeIE.ie_key()],
5355 }, {
5356 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
5357 'only_matching': True,
5358 }, {
5359 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
5360 'only_matching': True,
5361 }, {
5362 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
5363 'info_dict': {
12a1b225 5364 'id': 'Wq15eF5vCbI', # This will keep changing
a6213a49 5365 'ext': 'mp4',
976ae3ea 5366 'title': str,
a6213a49 5367 'uploader': 'Sky News',
5368 'uploader_id': 'skynews',
5369 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
5370 'upload_date': r're:\d{8}',
976ae3ea 5371 'description': str,
a6213a49 5372 'categories': ['News & Politics'],
5373 'tags': list,
5374 'like_count': int,
6c73052c 5375 'release_timestamp': 1642502819,
976ae3ea 5376 'channel': 'Sky News',
5377 'channel_id': 'UCoMdktPbSTixAyNGwb-UYkQ',
5378 'age_limit': 0,
5379 'view_count': int,
6c73052c 5380 'thumbnail': 'https://i.ytimg.com/vi/GgL890LIznQ/maxresdefault_live.jpg',
976ae3ea 5381 'playable_in_embed': True,
6c73052c 5382 'release_date': '20220118',
976ae3ea 5383 'availability': 'public',
5384 'live_status': 'is_live',
5385 'channel_url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ',
6c73052c 5386 'channel_follower_count': int
a6213a49 5387 },
5388 'params': {
5389 'skip_download': True,
5390 },
976ae3ea 5391 'expected_warnings': ['Ignoring subtitle tracks found in '],
a6213a49 5392 }, {
5393 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
5394 'info_dict': {
5395 'id': 'a48o2S1cPoo',
5396 'ext': 'mp4',
5397 'title': 'The Young Turks - Live Main Show',
5398 'uploader': 'The Young Turks',
5399 'uploader_id': 'TheYoungTurks',
5400 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
5401 'upload_date': '20150715',
5402 'license': 'Standard YouTube License',
5403 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
5404 'categories': ['News & Politics'],
5405 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
5406 'like_count': int,
a6213a49 5407 },
5408 'params': {
5409 'skip_download': True,
5410 },
5411 'only_matching': True,
5412 }, {
5413 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
5414 'only_matching': True,
5415 }, {
5416 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
5417 'only_matching': True,
5418 }, {
5419 'note': 'A channel that is not live. Should raise error',
5420 'url': 'https://www.youtube.com/user/numberphile/live',
5421 'only_matching': True,
5422 }, {
5423 'url': 'https://www.youtube.com/feed/trending',
5424 'only_matching': True,
5425 }, {
5426 'url': 'https://www.youtube.com/feed/library',
5427 'only_matching': True,
5428 }, {
5429 'url': 'https://www.youtube.com/feed/history',
5430 'only_matching': True,
5431 }, {
5432 'url': 'https://www.youtube.com/feed/subscriptions',
5433 'only_matching': True,
5434 }, {
5435 'url': 'https://www.youtube.com/feed/watch_later',
5436 'only_matching': True,
5437 }, {
5438 'note': 'Recommended - redirects to home page.',
5439 'url': 'https://www.youtube.com/feed/recommended',
5440 'only_matching': True,
5441 }, {
5442 'note': 'inline playlist with not always working continuations',
5443 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
5444 'only_matching': True,
5445 }, {
5446 'url': 'https://www.youtube.com/course',
5447 'only_matching': True,
5448 }, {
5449 'url': 'https://www.youtube.com/zsecurity',
5450 'only_matching': True,
5451 }, {
5452 'url': 'http://www.youtube.com/NASAgovVideo/videos',
5453 'only_matching': True,
5454 }, {
5455 'url': 'https://www.youtube.com/TheYoungTurks/live',
5456 'only_matching': True,
5457 }, {
5458 'url': 'https://www.youtube.com/hashtag/cctv9',
5459 'info_dict': {
5460 'id': 'cctv9',
5461 'title': '#cctv9',
976ae3ea 5462 'tags': [],
a6213a49 5463 },
5464 'playlist_mincount': 350,
5465 }, {
5466 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
5467 'only_matching': True,
5468 }, {
5469 'note': 'Requires Premium: should request additional YTM-info webpage (and have format 141) for videos in playlist',
5470 'url': 'https://music.youtube.com/playlist?list=PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
5471 'only_matching': True
5472 }, {
5473 'note': '/browse/ should redirect to /channel/',
5474 'url': 'https://music.youtube.com/browse/UC1a8OFewdjuLq6KlF8M_8Ng',
5475 'only_matching': True
5476 }, {
5477 'note': 'VLPL, should redirect to playlist?list=PL...',
5478 'url': 'https://music.youtube.com/browse/VLPLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
5479 'info_dict': {
5480 'id': 'PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
5481 'uploader': 'NoCopyrightSounds',
5482 'description': 'Providing you with copyright free / safe music for gaming, live streaming, studying and more!',
5483 'uploader_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg',
12a1b225 5484 'title': 'NCS : All Releases 💿',
976ae3ea 5485 'uploader_url': 'https://www.youtube.com/c/NoCopyrightSounds',
5486 'channel_url': 'https://www.youtube.com/c/NoCopyrightSounds',
5487 'modified_date': r're:\d{8}',
5488 'view_count': int,
5489 'channel_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg',
5490 'tags': [],
5491 'channel': 'NoCopyrightSounds',
c26f9b99 5492 'availability': 'public',
a6213a49 5493 },
5494 'playlist_mincount': 166,
976ae3ea 5495 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
a6213a49 5496 }, {
5497 'note': 'Topic, should redirect to playlist?list=UU...',
5498 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
5499 'info_dict': {
5500 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
5501 'uploader_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
5502 'title': 'Uploads from Royalty Free Music - Topic',
5503 'uploader': 'Royalty Free Music - Topic',
976ae3ea 5504 'tags': [],
5505 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
5506 'channel': 'Royalty Free Music - Topic',
5507 'view_count': int,
5508 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
5509 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
5510 'modified_date': r're:\d{8}',
5511 'uploader_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
5512 'description': '',
c26f9b99 5513 'availability': 'public',
a6213a49 5514 },
5515 'expected_warnings': [
a6213a49 5516 'The URL does not have a videos tab',
976ae3ea 5517 r'[Uu]navailable videos (are|will be) hidden',
a6213a49 5518 ],
5519 'playlist_mincount': 101,
5520 }, {
5521 'note': 'Topic without a UU playlist',
5522 'url': 'https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg',
5523 'info_dict': {
5524 'id': 'UCtFRv9O2AHqOZjjynzrv-xg',
5525 'title': 'UCtFRv9O2AHqOZjjynzrv-xg',
976ae3ea 5526 'tags': [],
a6213a49 5527 },
5528 'expected_warnings': [
976ae3ea 5529 'the playlist redirect gave error',
a6213a49 5530 ],
5531 'playlist_mincount': 9,
5532 }, {
5533 'note': 'Youtube music Album',
5534 'url': 'https://music.youtube.com/browse/MPREb_gTAcphH99wE',
5535 'info_dict': {
5536 'id': 'OLAK5uy_l1m0thk3g31NmIIz_vMIbWtyv7eZixlH0',
5537 'title': 'Album - Royalty Free Music Library V2 (50 Songs)',
976ae3ea 5538 'tags': [],
5539 'view_count': int,
5540 'description': '',
5541 'availability': 'unlisted',
5542 'modified_date': r're:\d{8}',
a6213a49 5543 },
5544 'playlist_count': 50,
5545 }, {
5546 'note': 'unlisted single video playlist',
5547 'url': 'https://www.youtube.com/playlist?list=PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
5548 'info_dict': {
5549 'uploader_id': 'UC9zHu_mHU96r19o-wV5Qs1Q',
5550 'uploader': 'colethedj',
5551 'id': 'PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
5552 'title': 'yt-dlp unlisted playlist test',
976ae3ea 5553 'availability': 'unlisted',
5554 'tags': [],
12a1b225 5555 'modified_date': '20220418',
976ae3ea 5556 'channel': 'colethedj',
5557 'view_count': int,
5558 'description': '',
5559 'uploader_url': 'https://www.youtube.com/channel/UC9zHu_mHU96r19o-wV5Qs1Q',
5560 'channel_id': 'UC9zHu_mHU96r19o-wV5Qs1Q',
5561 'channel_url': 'https://www.youtube.com/channel/UC9zHu_mHU96r19o-wV5Qs1Q',
a6213a49 5562 },
5563 'playlist_count': 1,
5564 }, {
5565 'note': 'API Fallback: Recommended - redirects to home page. Requires visitorData',
5566 'url': 'https://www.youtube.com/feed/recommended',
5567 'info_dict': {
5568 'id': 'recommended',
5569 'title': 'recommended',
6c73052c 5570 'tags': [],
a6213a49 5571 },
5572 'playlist_mincount': 50,
5573 'params': {
5574 'skip_download': True,
5575 'extractor_args': {'youtubetab': {'skip': ['webpage']}}
5576 },
5577 }, {
5578 'note': 'API Fallback: /videos tab, sorted by oldest first',
5579 'url': 'https://www.youtube.com/user/theCodyReeder/videos?view=0&sort=da&flow=grid',
5580 'info_dict': {
5581 'id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
5582 'title': 'Cody\'sLab - Videos',
5583 'description': 'md5:d083b7c2f0c67ee7a6c74c3e9b4243fa',
5584 'uploader': 'Cody\'sLab',
5585 'uploader_id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
976ae3ea 5586 'channel': 'Cody\'sLab',
5587 'channel_id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
5588 'tags': [],
5589 'channel_url': 'https://www.youtube.com/channel/UCu6mSoMNzHQiBIOCkHUa2Aw',
5590 'uploader_url': 'https://www.youtube.com/channel/UCu6mSoMNzHQiBIOCkHUa2Aw',
6c73052c 5591 'channel_follower_count': int
a6213a49 5592 },
5593 'playlist_mincount': 650,
5594 'params': {
5595 'skip_download': True,
5596 'extractor_args': {'youtubetab': {'skip': ['webpage']}}
5597 },
5598 }, {
5599 'note': 'API Fallback: Topic, should redirect to playlist?list=UU...',
5600 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
5601 'info_dict': {
5602 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
5603 'uploader_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
5604 'title': 'Uploads from Royalty Free Music - Topic',
5605 'uploader': 'Royalty Free Music - Topic',
976ae3ea 5606 'modified_date': r're:\d{8}',
5607 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
5608 'description': '',
5609 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
5610 'tags': [],
5611 'channel': 'Royalty Free Music - Topic',
5612 'view_count': int,
5613 'uploader_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
c26f9b99 5614 'availability': 'public',
a6213a49 5615 },
5616 'expected_warnings': [
976ae3ea 5617 'does not have a videos tab',
5618 r'[Uu]navailable videos (are|will be) hidden',
a6213a49 5619 ],
5620 'playlist_mincount': 101,
5621 'params': {
5622 'skip_download': True,
5623 'extractor_args': {'youtubetab': {'skip': ['webpage']}}
5624 },
7c219ea6 5625 }, {
5626 'note': 'non-standard redirect to regional channel',
5627 'url': 'https://www.youtube.com/channel/UCwVVpHQ2Cs9iGJfpdFngePQ',
5628 'only_matching': True
61d3665d 5629 }, {
5630 'note': 'collaborative playlist (uploader name in the form "by <uploader> and x other(s)")',
5631 'url': 'https://www.youtube.com/playlist?list=PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
5632 'info_dict': {
5633 'id': 'PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
5634 'modified_date': '20220407',
5635 'channel_url': 'https://www.youtube.com/channel/UCKcqXmCcyqnhgpA5P0oHH_Q',
5636 'tags': [],
5637 'uploader_id': 'UCKcqXmCcyqnhgpA5P0oHH_Q',
5638 'uploader': 'pukkandan',
5639 'availability': 'unlisted',
5640 'channel_id': 'UCKcqXmCcyqnhgpA5P0oHH_Q',
5641 'channel': 'pukkandan',
5642 'description': 'Test for collaborative playlist',
5643 'title': 'yt-dlp test - collaborative playlist',
12a1b225 5644 'view_count': int,
61d3665d 5645 'uploader_url': 'https://www.youtube.com/channel/UCKcqXmCcyqnhgpA5P0oHH_Q',
5646 },
5647 'playlist_mincount': 2
c26f9b99 5648 }, {
5649 'note': 'translated tab name',
5650 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/playlists',
5651 'info_dict': {
5652 'id': 'UCiu-3thuViMebBjw_5nWYrA',
5653 'tags': [],
5654 'uploader_id': 'UCiu-3thuViMebBjw_5nWYrA',
5655 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
5656 'description': '',
5657 'title': 'cole-dlp-test-acc - 再生リスト',
5658 'uploader_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
5659 'uploader': 'cole-dlp-test-acc',
5660 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
5661 'channel': 'cole-dlp-test-acc',
5662 },
5663 'playlist_mincount': 1,
5664 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
5665 'expected_warnings': ['Preferring "ja"'],
5666 }, {
5667 # XXX: this should really check flat playlist entries, but the test suite doesn't support that
5668 'note': 'preferred lang set with playlist with translated video titles',
5669 'url': 'https://www.youtube.com/playlist?list=PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
5670 'info_dict': {
5671 'id': 'PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
5672 'tags': [],
5673 'view_count': int,
5674 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
5675 'uploader': 'cole-dlp-test-acc',
5676 'uploader_id': 'UCiu-3thuViMebBjw_5nWYrA',
5677 'channel': 'cole-dlp-test-acc',
5678 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
5679 'description': 'test',
5680 'uploader_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
5681 'title': 'dlp test playlist',
5682 'availability': 'public',
5683 },
5684 'playlist_mincount': 1,
5685 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
5686 'expected_warnings': ['Preferring "ja"'],
80eb0bd9 5687 }, {
5688 # shorts audio pivot for 2GtVksBMYFM.
5689 'url': 'https://www.youtube.com/feed/sfv_audio_pivot?bp=8gUrCikSJwoLMkd0VmtzQk1ZRk0SCzJHdFZrc0JNWUZNGgsyR3RWa3NCTVlGTQ==',
5690 'info_dict': {
5691 'id': 'sfv_audio_pivot',
5692 'title': 'sfv_audio_pivot',
5693 'tags': [],
5694 },
5695 'playlist_mincount': 50,
5696
a6213a49 5697 }]
5698
5699 @classmethod
5700 def suitable(cls, url):
86e5f3ed 5701 return False if YoutubeIE.suitable(url) else super().suitable(url)
9297939e 5702
64f36541 5703 _URL_RE = re.compile(rf'(?P<pre>{_VALID_URL})(?(not_channel)|(?P<tab>/\w+))?(?P<post>.*)$')
fe03a6cd 5704
182bda88 5705 @YoutubeTabBaseInfoExtractor.passthrough_smuggled_data
5706 def _real_extract(self, url, smuggled_data):
cd7c66cf 5707 item_id = self._match_id(url)
14f25df2 5708 url = urllib.parse.urlunparse(
5709 urllib.parse.urlparse(url)._replace(netloc='www.youtube.com'))
a06916d9 5710 compat_opts = self.get_param('compat_opts', [])
cd7c66cf 5711
fe03a6cd 5712 def get_mobj(url):
37e57a9f 5713 mobj = self._URL_RE.match(url).groupdict()
07cce701 5714 mobj.update((k, '') for k, v in mobj.items() if v is None)
fe03a6cd 5715 return mobj
5716
37e57a9f 5717 mobj, redirect_warning = get_mobj(url), None
fe03a6cd 5718 # Youtube returns incomplete data if tabname is not lower case
5719 pre, tab, post, is_channel = mobj['pre'], mobj['tab'].lower(), mobj['post'], not mobj['not_channel']
fe03a6cd 5720 if is_channel:
5721 if smuggled_data.get('is_music_url'):
37e57a9f 5722 if item_id[:2] == 'VL': # Youtube music VL channels have an equivalent playlist
fe03a6cd 5723 item_id = item_id[2:]
37e57a9f 5724 pre, tab, post, is_channel = f'https://www.youtube.com/playlist?list={item_id}', '', '', False
5725 elif item_id[:2] == 'MP': # Resolve albums (/[channel/browse]/MP...) to their equivalent playlist
ac56cf38 5726 mdata = self._extract_tab_endpoint(
37e57a9f 5727 f'https://music.youtube.com/channel/{item_id}', item_id, default_client='web_music')
5728 murl = traverse_obj(mdata, ('microformat', 'microformatDataRenderer', 'urlCanonical'),
14f25df2 5729 get_all=False, expected_type=str)
ac56cf38 5730 if not murl:
37e57a9f 5731 raise ExtractorError('Failed to resolve album to playlist')
ac56cf38 5732 return self.url_result(murl, ie=YoutubeTabIE.ie_key())
37e57a9f 5733 elif mobj['channel_type'] == 'browse': # Youtube music /browse/ should be changed to /channel/
5734 pre = f'https://www.youtube.com/channel/{item_id}'
5735
64f36541 5736 original_tab_name = tab
fe03a6cd 5737 if is_channel and not tab and 'no-youtube-channel-redirect' not in compat_opts:
5738 # Home URLs should redirect to /videos/
37e57a9f 5739 redirect_warning = ('A channel/user page was given. All the channel\'s videos will be downloaded. '
5740 'To download only the videos in the home page, add a "/featured" to the URL')
fe03a6cd 5741 tab = '/videos'
5742
5743 url = ''.join((pre, tab, post))
5744 mobj = get_mobj(url)
cd7c66cf 5745
5746 # Handle both video/playlist URLs
201c1459 5747 qs = parse_qs(url)
86e5f3ed 5748 video_id, playlist_id = (qs.get(key, [None])[0] for key in ('v', 'list'))
cd7c66cf 5749
fe03a6cd 5750 if not video_id and mobj['not_channel'].startswith('watch'):
cd7c66cf 5751 if not playlist_id:
fe03a6cd 5752 # If there is neither video or playlist ids, youtube redirects to home page, which is undesirable
cd7c66cf 5753 raise ExtractorError('Unable to recognize tab page')
fe03a6cd 5754 # Common mistake: https://www.youtube.com/watch?list=playlist_id
37e57a9f 5755 self.report_warning(f'A video URL was given without video ID. Trying to download playlist {playlist_id}')
5756 url = f'https://www.youtube.com/playlist?list={playlist_id}'
18db7548 5757 mobj = get_mobj(url)
cd7c66cf 5758
5759 if video_id and playlist_id:
a06916d9 5760 if self.get_param('noplaylist'):
37e57a9f 5761 self.to_screen(f'Downloading just video {video_id} because of --no-playlist')
5762 return self.url_result(f'https://www.youtube.com/watch?v={video_id}',
5763 ie=YoutubeIE.ie_key(), video_id=video_id)
5764 self.to_screen(f'Downloading playlist {playlist_id}; add --no-playlist to just download video {video_id}')
cd7c66cf 5765
ac56cf38 5766 data, ytcfg = self._extract_data(url, item_id)
14fdfea9 5767
7c219ea6 5768 # YouTube may provide a non-standard redirect to the regional channel
5769 # See: https://github.com/yt-dlp/yt-dlp/issues/2694
5770 redirect_url = traverse_obj(
5771 data, ('onResponseReceivedActions', ..., 'navigateAction', 'endpoint', 'commandMetadata', 'webCommandMetadata', 'url'), get_all=False)
5772 if redirect_url and 'no-youtube-channel-redirect' not in compat_opts:
5773 redirect_url = ''.join((
5774 urljoin('https://www.youtube.com', redirect_url), mobj['tab'], mobj['post']))
5775 self.to_screen(f'This playlist is likely not available in your region. Following redirect to regional playlist {redirect_url}')
5776 return self.url_result(redirect_url, ie=YoutubeTabIE.ie_key())
5777
37e57a9f 5778 tabs = traverse_obj(data, ('contents', 'twoColumnBrowseResultsRenderer', 'tabs'), expected_type=list)
18db7548 5779 if tabs:
5780 selected_tab = self._extract_selected_tab(tabs)
c26f9b99 5781 selected_tab_url = urljoin(
5782 url, traverse_obj(selected_tab, ('endpoint', 'commandMetadata', 'webCommandMetadata', 'url')))
5783 translated_tab_name = selected_tab.get('title', '').lower()
5784
5785 # Prefer tab name from tab url as it is always in en,
5786 # but only when preferred lang is set as it may not extract reliably in all cases.
5787 selected_tab_name = (self._preferred_lang in (None, 'en') and translated_tab_name
5788 or selected_tab_url and get_mobj(selected_tab_url)['tab'][1:] # primary
5789 or translated_tab_name)
5790
64f36541 5791 if selected_tab_name == 'home':
5792 selected_tab_name = 'featured'
5793 requested_tab_name = mobj['tab'][1:]
c26f9b99 5794
09f1580e 5795 if 'no-youtube-channel-redirect' not in compat_opts:
693f0600 5796 if requested_tab_name == 'live': # Live tab should have redirected to the video
5797 raise UserNotLive(video_id=mobj['id'])
64f36541 5798 if requested_tab_name not in ('', selected_tab_name):
5799 redirect_warning = f'The channel does not have a {requested_tab_name} tab'
5800 if not original_tab_name:
5801 if item_id[:2] == 'UC':
5802 # Topic channels don't have /videos. Use the equivalent playlist instead
5803 pl_id = f'UU{item_id[2:]}'
5804 pl_url = f'https://www.youtube.com/playlist?list={pl_id}'
5805 try:
5806 data, ytcfg = self._extract_data(pl_url, pl_id, ytcfg=ytcfg, fatal=True, webpage_fatal=True)
5807 except ExtractorError:
5808 redirect_warning += ' and the playlist redirect gave error'
5809 else:
5810 item_id, url, selected_tab_name = pl_id, pl_url, requested_tab_name
5811 redirect_warning += f'. Redirecting to playlist {pl_id} instead'
5812 if selected_tab_name and selected_tab_name != requested_tab_name:
5813 redirect_warning += f'. {selected_tab_name} tab is being downloaded instead'
5814 else:
5815 raise ExtractorError(redirect_warning, expected=True)
18db7548 5816
37e57a9f 5817 if redirect_warning:
64f36541 5818 self.to_screen(redirect_warning)
37e57a9f 5819 self.write_debug(f'Final URL: {url}')
18db7548 5820
358de58c 5821 # YouTube sometimes provides a button to reload playlist with unavailable videos.
53ed7066 5822 if 'no-youtube-unavailable-videos' not in compat_opts:
ac56cf38 5823 data = self._reload_with_unavailable_videos(item_id, data, ytcfg) or data
c0ac49bc 5824 self._extract_and_report_alerts(data, only_once=True)
37e57a9f 5825 tabs = traverse_obj(data, ('contents', 'twoColumnBrowseResultsRenderer', 'tabs'), expected_type=list)
8bdd16b4 5826 if tabs:
ac56cf38 5827 return self._extract_from_tabs(item_id, ytcfg, data, tabs)
cd7c66cf 5828
37e57a9f 5829 playlist = traverse_obj(
5830 data, ('contents', 'twoColumnWatchNextResults', 'playlist', 'playlist'), expected_type=dict)
8bdd16b4 5831 if playlist:
ac56cf38 5832 return self._extract_from_playlist(item_id, url, data, playlist, ytcfg)
cd7c66cf 5833
37e57a9f 5834 video_id = traverse_obj(
5835 data, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'), expected_type=str) or video_id
8bdd16b4 5836 if video_id:
09f1580e 5837 if mobj['tab'] != '/live': # live tab is expected to redirect to video
37e57a9f 5838 self.report_warning(f'Unable to recognize playlist. Downloading just video {video_id}')
5839 return self.url_result(f'https://www.youtube.com/watch?v={video_id}',
5840 ie=YoutubeIE.ie_key(), video_id=video_id)
cd7c66cf 5841
8bdd16b4 5842 raise ExtractorError('Unable to recognize tab page')
c5e8d7af 5843
c5e8d7af 5844
8bdd16b4 5845class YoutubePlaylistIE(InfoExtractor):
96565c7e 5846 IE_DESC = 'YouTube playlists'
8bdd16b4 5847 _VALID_URL = r'''(?x)(?:
5848 (?:https?://)?
5849 (?:\w+\.)?
5850 (?:
5851 (?:
5852 youtube(?:kids)?\.com|
d9190e44 5853 %(invidious)s
8bdd16b4 5854 )
5855 /.*?\?.*?\blist=
5856 )?
5857 (?P<id>%(playlist_id)s)
d9190e44
RH
5858 )''' % {
5859 'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE,
5860 'invidious': '|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
5861 }
8bdd16b4 5862 IE_NAME = 'youtube:playlist'
cdc628a4 5863 _TESTS = [{
8bdd16b4 5864 'note': 'issue #673',
5865 'url': 'PLBB231211A4F62143',
cdc628a4 5866 'info_dict': {
8bdd16b4 5867 'title': '[OLD]Team Fortress 2 (Class-based LP)',
5868 'id': 'PLBB231211A4F62143',
976ae3ea 5869 'uploader': 'Wickman',
8bdd16b4 5870 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
11f9be09 5871 'description': 'md5:8fa6f52abb47a9552002fa3ddfc57fc2',
976ae3ea 5872 'view_count': int,
5873 'uploader_url': 'https://www.youtube.com/user/Wickydoo',
5874 'modified_date': r're:\d{8}',
5875 'channel_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
5876 'channel': 'Wickman',
5877 'tags': [],
5878 'channel_url': 'https://www.youtube.com/user/Wickydoo',
8bdd16b4 5879 },
5880 'playlist_mincount': 29,
5881 }, {
5882 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
5883 'info_dict': {
5884 'title': 'YDL_safe_search',
5885 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
5886 },
5887 'playlist_count': 2,
5888 'skip': 'This playlist is private',
9558dcec 5889 }, {
8bdd16b4 5890 'note': 'embedded',
5891 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
5892 'playlist_count': 4,
9558dcec 5893 'info_dict': {
8bdd16b4 5894 'title': 'JODA15',
5895 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
5896 'uploader': 'milan',
5897 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
976ae3ea 5898 'description': '',
5899 'channel_url': 'https://www.youtube.com/channel/UCEI1-PVPcYXjB73Hfelbmaw',
5900 'tags': [],
5901 'modified_date': '20140919',
5902 'view_count': int,
5903 'channel': 'milan',
5904 'channel_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
5905 'uploader_url': 'https://www.youtube.com/channel/UCEI1-PVPcYXjB73Hfelbmaw',
c26f9b99 5906 'availability': 'public',
976ae3ea 5907 },
5908 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
cdc628a4 5909 }, {
8bdd16b4 5910 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
12a1b225 5911 'playlist_mincount': 455,
8bdd16b4 5912 'info_dict': {
5913 'title': '2018 Chinese New Singles (11/6 updated)',
5914 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
5915 'uploader': 'LBK',
5916 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
11f9be09 5917 'description': 'md5:da521864744d60a198e3a88af4db0d9d',
976ae3ea 5918 'channel': 'LBK',
5919 'view_count': int,
5920 'channel_url': 'https://www.youtube.com/c/愛低音的國王',
5921 'tags': [],
5922 'uploader_url': 'https://www.youtube.com/c/愛低音的國王',
5923 'channel_id': 'UC21nz3_MesPLqtDqwdvnoxA',
5924 'modified_date': r're:\d{8}',
c26f9b99 5925 'availability': 'public',
976ae3ea 5926 },
5927 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
daa0df9e 5928 }, {
29f7c58a 5929 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
5930 'only_matching': True,
5931 }, {
5932 # music album playlist
5933 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
5934 'only_matching': True,
5935 }]
5936
5937 @classmethod
5938 def suitable(cls, url):
201c1459 5939 if YoutubeTabIE.suitable(url):
5940 return False
49a57e70 5941 from ..utils import parse_qs
201c1459 5942 qs = parse_qs(url)
5943 if qs.get('v', [None])[0]:
5944 return False
86e5f3ed 5945 return super().suitable(url)
29f7c58a 5946
5947 def _real_extract(self, url):
5948 playlist_id = self._match_id(url)
46953e7e 5949 is_music_url = YoutubeBaseInfoExtractor.is_music_url(url)
9297939e 5950 url = update_url_query(
5951 'https://www.youtube.com/playlist',
5952 parse_qs(url) or {'list': playlist_id})
5953 if is_music_url:
5954 url = smuggle_url(url, {'is_music_url': True})
5955 return self.url_result(url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
29f7c58a 5956
5957
5958class YoutubeYtBeIE(InfoExtractor):
c76eb41b 5959 IE_DESC = 'youtu.be'
29f7c58a 5960 _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}
5961 _TESTS = [{
8bdd16b4 5962 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
5963 'info_dict': {
5964 'id': 'yeWKywCrFtk',
5965 'ext': 'mp4',
5966 'title': 'Small Scale Baler and Braiding Rugs',
5967 'uploader': 'Backus-Page House Museum',
5968 'uploader_id': 'backuspagemuseum',
5969 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
5970 'upload_date': '20161008',
5971 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
5972 'categories': ['Nonprofits & Activism'],
5973 'tags': list,
5974 'like_count': int,
976ae3ea 5975 'age_limit': 0,
5976 'playable_in_embed': True,
5977 'thumbnail': 'https://i.ytimg.com/vi_webp/yeWKywCrFtk/maxresdefault.webp',
5978 'channel': 'Backus-Page House Museum',
5979 'channel_id': 'UCEfMCQ9bs3tjvjy1s451zaw',
5980 'live_status': 'not_live',
5981 'view_count': int,
5982 'channel_url': 'https://www.youtube.com/channel/UCEfMCQ9bs3tjvjy1s451zaw',
5983 'availability': 'public',
5984 'duration': 59,
12a1b225
A
5985 'comment_count': int,
5986 'channel_follower_count': int
8bdd16b4 5987 },
5988 'params': {
5989 'noplaylist': True,
5990 'skip_download': True,
5991 },
39e7107d 5992 }, {
8bdd16b4 5993 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
39e7107d 5994 'only_matching': True,
cdc628a4
PH
5995 }]
5996
8bdd16b4 5997 def _real_extract(self, url):
5ad28e7f 5998 mobj = self._match_valid_url(url)
29f7c58a 5999 video_id = mobj.group('id')
6000 playlist_id = mobj.group('playlist_id')
8bdd16b4 6001 return self.url_result(
29f7c58a 6002 update_url_query('https://www.youtube.com/watch', {
6003 'v': video_id,
6004 'list': playlist_id,
6005 'feature': 'youtu.be',
6006 }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
8bdd16b4 6007
6008
b6ce9bb0 6009class YoutubeLivestreamEmbedIE(InfoExtractor):
6010 IE_DESC = 'YouTube livestream embeds'
6011 _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/embed/live_stream/?\?(?:[^#]+&)?channel=(?P<id>[^&#]+)'
6012 _TESTS = [{
6013 'url': 'https://www.youtube.com/embed/live_stream?channel=UC2_KI6RB__jGdlnK6dvFEZA',
6014 'only_matching': True,
6015 }]
6016
6017 def _real_extract(self, url):
6018 channel_id = self._match_id(url)
6019 return self.url_result(
6020 f'https://www.youtube.com/channel/{channel_id}/live',
6021 ie=YoutubeTabIE.ie_key(), video_id=channel_id)
6022
6023
8bdd16b4 6024class YoutubeYtUserIE(InfoExtractor):
96565c7e 6025 IE_DESC = 'YouTube user videos; "ytuser:" prefix'
b6ce9bb0 6026 IE_NAME = 'youtube:user'
8bdd16b4 6027 _VALID_URL = r'ytuser:(?P<id>.+)'
6028 _TESTS = [{
6029 'url': 'ytuser:phihag',
6030 'only_matching': True,
6031 }]
6032
6033 def _real_extract(self, url):
6034 user_id = self._match_id(url)
6035 return self.url_result(
c586f9e8 6036 'https://www.youtube.com/user/%s/videos' % user_id,
8bdd16b4 6037 ie=YoutubeTabIE.ie_key(), video_id=user_id)
9558dcec 6038
b05654f0 6039
3d3dddc9 6040class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
70d5c17b 6041 IE_NAME = 'youtube:favorites'
96565c7e 6042 IE_DESC = 'YouTube liked videos; ":ytfav" keyword (requires cookies)'
70d5c17b 6043 _VALID_URL = r':ytfav(?:ou?rite)?s?'
6044 _LOGIN_REQUIRED = True
6045 _TESTS = [{
6046 'url': ':ytfav',
6047 'only_matching': True,
6048 }, {
6049 'url': ':ytfavorites',
6050 'only_matching': True,
6051 }]
6052
6053 def _real_extract(self, url):
6054 return self.url_result(
6055 'https://www.youtube.com/playlist?list=LL',
6056 ie=YoutubeTabIE.ie_key())
6057
6058
ca5300c7 6059class YoutubeNotificationsIE(YoutubeTabBaseInfoExtractor):
6060 IE_NAME = 'youtube:notif'
6061 IE_DESC = 'YouTube notifications; ":ytnotif" keyword (requires cookies)'
6062 _VALID_URL = r':ytnotif(?:ication)?s?'
6063 _LOGIN_REQUIRED = True
6064 _TESTS = [{
6065 'url': ':ytnotif',
6066 'only_matching': True,
6067 }, {
6068 'url': ':ytnotifications',
6069 'only_matching': True,
6070 }]
6071
6072 def _extract_notification_menu(self, response, continuation_list):
6073 notification_list = traverse_obj(
6074 response,
6075 ('actions', 0, 'openPopupAction', 'popup', 'multiPageMenuRenderer', 'sections', 0, 'multiPageMenuNotificationSectionRenderer', 'items'),
6076 ('actions', 0, 'appendContinuationItemsAction', 'continuationItems'),
6077 expected_type=list) or []
6078 continuation_list[0] = None
6079 for item in notification_list:
6080 entry = self._extract_notification_renderer(item.get('notificationRenderer'))
6081 if entry:
6082 yield entry
6083 continuation = item.get('continuationItemRenderer')
6084 if continuation:
6085 continuation_list[0] = continuation
6086
6087 def _extract_notification_renderer(self, notification):
6088 video_id = traverse_obj(
6089 notification, ('navigationEndpoint', 'watchEndpoint', 'videoId'), expected_type=str)
6090 url = f'https://www.youtube.com/watch?v={video_id}'
6091 channel_id = None
6092 if not video_id:
6093 browse_ep = traverse_obj(
6094 notification, ('navigationEndpoint', 'browseEndpoint'), expected_type=dict)
6095 channel_id = traverse_obj(browse_ep, 'browseId', expected_type=str)
6096 post_id = self._search_regex(
6097 r'/post/(.+)', traverse_obj(browse_ep, 'canonicalBaseUrl', expected_type=str),
6098 'post id', default=None)
6099 if not channel_id or not post_id:
6100 return
6101 # The direct /post url redirects to this in the browser
6102 url = f'https://www.youtube.com/channel/{channel_id}/community?lb={post_id}'
6103
6104 channel = traverse_obj(
6105 notification, ('contextualMenu', 'menuRenderer', 'items', 1, 'menuServiceItemRenderer', 'text', 'runs', 1, 'text'),
6106 expected_type=str)
c7a7baaa 6107 notification_title = self._get_text(notification, 'shortMessage')
6108 if notification_title:
6109 notification_title = notification_title.replace('\xad', '') # remove soft hyphens
6110 # TODO: handle recommended videos
ca5300c7 6111 title = self._search_regex(
c7a7baaa 6112 rf'{re.escape(channel or "")}[^:]+: (.+)', notification_title,
ca5300c7 6113 'video title', default=None)
5225df50 6114 timestamp = (self._parse_time_text(self._get_text(notification, 'sentTimeText'))
6115 if self._configuration_arg('approximate_date', ie_key=YoutubeTabIE)
6116 else None)
ca5300c7 6117 return {
6118 '_type': 'url',
6119 'url': url,
6120 'ie_key': (YoutubeIE if video_id else YoutubeTabIE).ie_key(),
6121 'video_id': video_id,
6122 'title': title,
6123 'channel_id': channel_id,
6124 'channel': channel,
6125 'thumbnails': self._extract_thumbnails(notification, 'videoThumbnail'),
5225df50 6126 'timestamp': timestamp,
ca5300c7 6127 }
6128
6129 def _notification_menu_entries(self, ytcfg):
6130 continuation_list = [None]
6131 response = None
6132 for page in itertools.count(1):
6133 ctoken = traverse_obj(
6134 continuation_list, (0, 'continuationEndpoint', 'getNotificationMenuEndpoint', 'ctoken'), expected_type=str)
6135 response = self._extract_response(
6136 item_id=f'page {page}', query={'ctoken': ctoken} if ctoken else {}, ytcfg=ytcfg,
6137 ep='notification/get_notification_menu', check_get_keys='actions',
6138 headers=self.generate_api_headers(ytcfg=ytcfg, visitor_data=self._extract_visitor_data(response)))
6139 yield from self._extract_notification_menu(response, continuation_list)
6140 if not continuation_list[0]:
6141 break
6142
6143 def _real_extract(self, url):
6144 display_id = 'notifications'
6145 ytcfg = self._download_ytcfg('web', display_id) if not self.skip_webpage else {}
6146 self._report_playlist_authcheck(ytcfg)
6147 return self.playlist_result(self._notification_menu_entries(ytcfg), display_id, display_id)
6148
6149
a6213a49 6150class YoutubeSearchIE(YoutubeTabBaseInfoExtractor, SearchInfoExtractor):
6151 IE_DESC = 'YouTube search'
78caa52a 6152 IE_NAME = 'youtube:search'
b05654f0 6153 _SEARCH_KEY = 'ytsearch'
a61fd4cf 6154 _SEARCH_PARAMS = 'EgIQAQ%3D%3D' # Videos only
84bbc545 6155 _TESTS = [{
6156 'url': 'ytsearch5:youtube-dl test video',
6157 'playlist_count': 5,
6158 'info_dict': {
6159 'id': 'youtube-dl test video',
6160 'title': 'youtube-dl test video',
6161 }
6162 }]
b05654f0 6163
a61fd4cf 6164
5f7cb91a 6165class YoutubeSearchDateIE(YoutubeTabBaseInfoExtractor, SearchInfoExtractor):
cb7fb546 6166 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
a3dd9248 6167 _SEARCH_KEY = 'ytsearchdate'
a6213a49 6168 IE_DESC = 'YouTube search, newest videos first'
a61fd4cf 6169 _SEARCH_PARAMS = 'CAISAhAB' # Videos only, sorted by date
84bbc545 6170 _TESTS = [{
6171 'url': 'ytsearchdate5:youtube-dl test video',
6172 'playlist_count': 5,
6173 'info_dict': {
6174 'id': 'youtube-dl test video',
6175 'title': 'youtube-dl test video',
6176 }
6177 }]
75dff0ee 6178
c9ae7b95 6179
a6213a49 6180class YoutubeSearchURLIE(YoutubeTabBaseInfoExtractor):
96565c7e 6181 IE_DESC = 'YouTube search URLs with sorting and filter support'
386e1dd9 6182 IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
182bda88 6183 _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:results|search)\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
3462ffa8 6184 _TESTS = [{
6185 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
6186 'playlist_mincount': 5,
6187 'info_dict': {
11f9be09 6188 'id': 'youtube-dl test video',
3462ffa8 6189 'title': 'youtube-dl test video',
6190 }
a61fd4cf 6191 }, {
6192 'url': 'https://www.youtube.com/results?search_query=python&sp=EgIQAg%253D%253D',
6193 'playlist_mincount': 5,
6194 'info_dict': {
6195 'id': 'python',
6196 'title': 'python',
6197 }
ad210f4f 6198 }, {
6199 'url': 'https://www.youtube.com/results?search_query=%23cats',
6200 'playlist_mincount': 1,
6201 'info_dict': {
6202 'id': '#cats',
6203 'title': '#cats',
12a1b225
A
6204 # The test suite does not have support for nested playlists
6205 # 'entries': [{
6206 # 'url': r're:https://(www\.)?youtube\.com/hashtag/cats',
6207 # 'title': '#cats',
6208 # }],
ad210f4f 6209 },
3462ffa8 6210 }, {
6211 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
6212 'only_matching': True,
6213 }]
6214
6215 def _real_extract(self, url):
4dfbf869 6216 qs = parse_qs(url)
386e1dd9 6217 query = (qs.get('search_query') or qs.get('q'))[0]
a6213a49 6218 return self.playlist_result(self._search_results(query, qs.get('sp', (None,))[0]), query, query)
3462ffa8 6219
6220
16aa9ea4 6221class YoutubeMusicSearchURLIE(YoutubeTabBaseInfoExtractor):
62b58c09 6222 IE_DESC = 'YouTube music search URLs with selectable sections, e.g. #songs'
16aa9ea4 6223 IE_NAME = 'youtube:music:search_url'
6224 _VALID_URL = r'https?://music\.youtube\.com/search\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
6225 _TESTS = [{
6226 'url': 'https://music.youtube.com/search?q=royalty+free+music',
6227 'playlist_count': 16,
6228 'info_dict': {
6229 'id': 'royalty free music',
6230 'title': 'royalty free music',
6231 }
6232 }, {
6233 'url': 'https://music.youtube.com/search?q=royalty+free+music&sp=EgWKAQIIAWoKEAoQAxAEEAkQBQ%3D%3D',
6234 'playlist_mincount': 30,
6235 'info_dict': {
6236 'id': 'royalty free music - songs',
6237 'title': 'royalty free music - songs',
6238 },
6239 'params': {'extract_flat': 'in_playlist'}
6240 }, {
6241 'url': 'https://music.youtube.com/search?q=royalty+free+music#community+playlists',
6242 'playlist_mincount': 30,
6243 'info_dict': {
6244 'id': 'royalty free music - community playlists',
6245 'title': 'royalty free music - community playlists',
6246 },
6247 'params': {'extract_flat': 'in_playlist'}
6248 }]
6249
6250 _SECTIONS = {
6251 'albums': 'EgWKAQIYAWoKEAoQAxAEEAkQBQ==',
6252 'artists': 'EgWKAQIgAWoKEAoQAxAEEAkQBQ==',
6253 'community playlists': 'EgeKAQQoAEABagoQChADEAQQCRAF',
6254 'featured playlists': 'EgeKAQQoADgBagwQAxAJEAQQDhAKEAU==',
6255 'songs': 'EgWKAQIIAWoKEAoQAxAEEAkQBQ==',
6256 'videos': 'EgWKAQIQAWoKEAoQAxAEEAkQBQ==',
6257 }
6258
6259 def _real_extract(self, url):
6260 qs = parse_qs(url)
6261 query = (qs.get('search_query') or qs.get('q'))[0]
6262 params = qs.get('sp', (None,))[0]
6263 if params:
6264 section = next((k for k, v in self._SECTIONS.items() if v == params), params)
6265 else:
ac668111 6266 section = urllib.parse.unquote_plus((url.split('#') + [''])[1]).lower()
16aa9ea4 6267 params = self._SECTIONS.get(section)
6268 if not params:
6269 section = None
6270 title = join_nonempty(query, section, delim=' - ')
af5c1c55 6271 return self.playlist_result(self._search_results(query, params, default_client='web_music'), title, title)
16aa9ea4 6272
6273
182bda88 6274class YoutubeFeedsInfoExtractor(InfoExtractor):
d7ae0639 6275 """
25f14e9f 6276 Base class for feed extractors
82d02080 6277 Subclasses must re-define the _FEED_NAME property.
d7ae0639 6278 """
b2e8bc1b 6279 _LOGIN_REQUIRED = True
82d02080 6280 _FEED_NAME = 'feeds'
a25bca9f 6281
6282 def _real_initialize(self):
6283 YoutubeBaseInfoExtractor._check_login_required(self)
d7ae0639 6284
82d02080 6285 @classproperty
d7ae0639 6286 def IE_NAME(self):
82d02080 6287 return f'youtube:{self._FEED_NAME}'
04cc9617 6288
3853309f 6289 def _real_extract(self, url):
3d3dddc9 6290 return self.url_result(
182bda88 6291 f'https://www.youtube.com/feed/{self._FEED_NAME}', ie=YoutubeTabIE.ie_key())
25f14e9f
S
6292
6293
ef2f3c7f 6294class YoutubeWatchLaterIE(InfoExtractor):
6295 IE_NAME = 'youtube:watchlater'
96565c7e 6296 IE_DESC = 'Youtube watch later list; ":ytwatchlater" keyword (requires cookies)'
3d3dddc9 6297 _VALID_URL = r':ytwatchlater'
bc7a9cd8 6298 _TESTS = [{
8bdd16b4 6299 'url': ':ytwatchlater',
bc7a9cd8
S
6300 'only_matching': True,
6301 }]
25f14e9f
S
6302
6303 def _real_extract(self, url):
ef2f3c7f 6304 return self.url_result(
6305 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
3462ffa8 6306
6307
25f14e9f 6308class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
96565c7e 6309 IE_DESC = 'YouTube recommended videos; ":ytrec" keyword'
3d3dddc9 6310 _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
25f14e9f 6311 _FEED_NAME = 'recommended'
45db527f 6312 _LOGIN_REQUIRED = False
3d3dddc9 6313 _TESTS = [{
6314 'url': ':ytrec',
6315 'only_matching': True,
6316 }, {
6317 'url': ':ytrecommended',
6318 'only_matching': True,
6319 }, {
6320 'url': 'https://youtube.com',
6321 'only_matching': True,
6322 }]
1ed5b5c9 6323
1ed5b5c9 6324
25f14e9f 6325class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
96565c7e 6326 IE_DESC = 'YouTube subscriptions feed; ":ytsubs" keyword (requires cookies)'
3d3dddc9 6327 _VALID_URL = r':ytsub(?:scription)?s?'
25f14e9f 6328 _FEED_NAME = 'subscriptions'
3d3dddc9 6329 _TESTS = [{
6330 'url': ':ytsubs',
6331 'only_matching': True,
6332 }, {
6333 'url': ':ytsubscriptions',
6334 'only_matching': True,
6335 }]
1ed5b5c9 6336
1ed5b5c9 6337
25f14e9f 6338class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
96565c7e 6339 IE_DESC = 'Youtube watch history; ":ythis" keyword (requires cookies)'
a5c56234 6340 _VALID_URL = r':ythis(?:tory)?'
25f14e9f 6341 _FEED_NAME = 'history'
3d3dddc9 6342 _TESTS = [{
6343 'url': ':ythistory',
6344 'only_matching': True,
6345 }]
1ed5b5c9
JMF
6346
6347
6e634cbe 6348class YoutubeStoriesIE(InfoExtractor):
6349 IE_DESC = 'YouTube channel stories; "ytstories:" prefix'
6350 IE_NAME = 'youtube:stories'
6351 _VALID_URL = r'ytstories:UC(?P<id>[A-Za-z0-9_-]{21}[AQgw])$'
6352 _TESTS = [{
6353 'url': 'ytstories:UCwFCb4jeqaKWnciAYM-ZVHg',
6354 'only_matching': True,
6355 }]
6356
6357 def _real_extract(self, url):
6358 playlist_id = f'RLTD{self._match_id(url)}'
6359 return self.url_result(
50ac0e54 6360 smuggle_url(f'https://www.youtube.com/playlist?list={playlist_id}&playnext=1', {'is_story': True}),
6e634cbe 6361 ie=YoutubeTabIE, video_id=playlist_id)
6362
6363
80eb0bd9 6364class YoutubeShortsAudioPivotIE(InfoExtractor):
1dd18a88 6365 IE_DESC = 'YouTube Shorts audio pivot (Shorts using audio of a given video)'
80eb0bd9 6366 IE_NAME = 'youtube:shorts:pivot:audio'
1dd18a88 6367 _VALID_URL = r'https?://(?:www\.)?youtube\.com/source/(?P<id>[\w-]{11})/shorts'
80eb0bd9 6368 _TESTS = [{
1dd18a88 6369 'url': 'https://www.youtube.com/source/Lyj-MZSAA9o/shorts',
80eb0bd9 6370 'only_matching': True,
6371 }]
6372
6373 @staticmethod
6374 def _generate_audio_pivot_params(video_id):
6375 """
6376 Generates sfv_audio_pivot browse params for this video id
6377 """
6378 pb_params = b'\xf2\x05+\n)\x12\'\n\x0b%b\x12\x0b%b\x1a\x0b%b' % ((video_id.encode(),) * 3)
6379 return urllib.parse.quote(base64.b64encode(pb_params).decode())
6380
6381 def _real_extract(self, url):
6382 video_id = self._match_id(url)
6383 return self.url_result(
6384 f'https://www.youtube.com/feed/sfv_audio_pivot?bp={self._generate_audio_pivot_params(video_id)}',
6385 ie=YoutubeTabIE)
6386
6387
15870e90
PH
6388class YoutubeTruncatedURLIE(InfoExtractor):
6389 IE_NAME = 'youtube:truncated_url'
6390 IE_DESC = False # Do not list
975d35db 6391 _VALID_URL = r'''(?x)
b95aab84
PH
6392 (?:https?://)?
6393 (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
6394 (?:watch\?(?:
c4808c60 6395 feature=[a-z_]+|
b95aab84
PH
6396 annotation_id=annotation_[^&]+|
6397 x-yt-cl=[0-9]+|
c1708b89 6398 hl=[^&]*|
287be8c6 6399 t=[0-9]+
b95aab84
PH
6400 )?
6401 |
6402 attribution_link\?a=[^&]+
6403 )
6404 $
975d35db 6405 '''
15870e90 6406
c4808c60 6407 _TESTS = [{
2d3d2997 6408 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
c4808c60 6409 'only_matching': True,
dc2fc736 6410 }, {
2d3d2997 6411 'url': 'https://www.youtube.com/watch?',
dc2fc736 6412 'only_matching': True,
b95aab84
PH
6413 }, {
6414 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
6415 'only_matching': True,
6416 }, {
6417 'url': 'https://www.youtube.com/watch?feature=foo',
6418 'only_matching': True,
c1708b89
PH
6419 }, {
6420 'url': 'https://www.youtube.com/watch?hl=en-GB',
6421 'only_matching': True,
287be8c6
PH
6422 }, {
6423 'url': 'https://www.youtube.com/watch?t=2372',
6424 'only_matching': True,
c4808c60
PH
6425 }]
6426
15870e90
PH
6427 def _real_extract(self, url):
6428 raise ExtractorError(
78caa52a
PH
6429 'Did you forget to quote the URL? Remember that & is a meta '
6430 'character in most shells, so you want to put the URL in quotes, '
3867038a 6431 'like youtube-dl '
2d3d2997 6432 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
3867038a 6433 ' or simply youtube-dl BaW_jenozKc .',
15870e90 6434 expected=True)
772fd5cc
PH
6435
6436
471d0367 6437class YoutubeClipIE(YoutubeTabBaseInfoExtractor):
3cd786db 6438 IE_NAME = 'youtube:clip'
471d0367 6439 _VALID_URL = r'https?://(?:www\.)?youtube\.com/clip/(?P<id>[^/?#]+)'
6440 _TESTS = [{
6441 # FIXME: Other metadata should be extracted from the clip, not from the base video
6442 'url': 'https://www.youtube.com/clip/UgytZKpehg-hEMBSn3F4AaABCQ',
6443 'info_dict': {
6444 'id': 'UgytZKpehg-hEMBSn3F4AaABCQ',
6445 'ext': 'mp4',
6446 'section_start': 29.0,
6447 'section_end': 39.7,
6448 'duration': 10.7,
12a1b225
A
6449 'age_limit': 0,
6450 'availability': 'public',
6451 'categories': ['Gaming'],
6452 'channel': 'Scott The Woz',
6453 'channel_id': 'UC4rqhyiTs7XyuODcECvuiiQ',
6454 'channel_url': 'https://www.youtube.com/channel/UC4rqhyiTs7XyuODcECvuiiQ',
6455 'description': 'md5:7a4517a17ea9b4bd98996399d8bb36e7',
6456 'like_count': int,
6457 'playable_in_embed': True,
6458 'tags': 'count:17',
6459 'thumbnail': 'https://i.ytimg.com/vi_webp/ScPX26pdQik/maxresdefault.webp',
6460 'title': 'Mobile Games on Console - Scott The Woz',
6461 'upload_date': '20210920',
6462 'uploader': 'Scott The Woz',
6463 'uploader_id': 'scottthewoz',
6464 'uploader_url': 'http://www.youtube.com/user/scottthewoz',
6465 'view_count': int,
6466 'live_status': 'not_live',
6467 'channel_follower_count': int
471d0367 6468 }
6469 }]
3cd786db 6470
6471 def _real_extract(self, url):
471d0367 6472 clip_id = self._match_id(url)
6473 _, data = self._extract_webpage(url, clip_id)
6474
6475 video_id = traverse_obj(data, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'))
6476 if not video_id:
6477 raise ExtractorError('Unable to find video ID')
6478
6479 clip_data = traverse_obj(data, (
6480 'engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'clipSectionRenderer',
6481 'contents', ..., 'clipAttributionRenderer', 'onScrubExit', 'commandExecutorCommand', 'commands', ...,
6482 'openPopupAction', 'popup', 'notificationActionRenderer', 'actionButton', 'buttonRenderer', 'command',
6483 'commandExecutorCommand', 'commands', ..., 'loopCommand'), get_all=False)
6484
6485 return {
6486 '_type': 'url_transparent',
6487 'url': f'https://www.youtube.com/watch?v={video_id}',
6488 'ie_key': YoutubeIE.ie_key(),
6489 'id': clip_id,
6490 'section_start': int(clip_data['startTimeMs']) / 1000,
6491 'section_end': int(clip_data['endTimeMs']) / 1000,
6492 }
3cd786db 6493
6494
772fd5cc
PH
6495class YoutubeTruncatedIDIE(InfoExtractor):
6496 IE_NAME = 'youtube:truncated_id'
6497 IE_DESC = False # Do not list
b95aab84 6498 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
772fd5cc
PH
6499
6500 _TESTS = [{
6501 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
6502 'only_matching': True,
6503 }]
6504
6505 def _real_extract(self, url):
6506 video_id = self._match_id(url)
6507 raise ExtractorError(
86e5f3ed 6508 f'Incomplete YouTube ID {video_id}. URL {url} looks truncated.',
772fd5cc 6509 expected=True)