youtube.py 190 KB

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