youtube.py 196 KB

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