youtube.py 170 KB

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