youtube.py 165 KB

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