youtube.py 191 KB

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