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