youtube.py 144 KB

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