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