youtube.py 345 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494
  1. import base64
  2. import calendar
  3. import collections
  4. import copy
  5. import datetime as dt
  6. import enum
  7. import functools
  8. import hashlib
  9. import itertools
  10. import json
  11. import math
  12. import os.path
  13. import random
  14. import re
  15. import shlex
  16. import sys
  17. import threading
  18. import time
  19. import traceback
  20. import urllib.parse
  21. from .common import InfoExtractor, SearchInfoExtractor
  22. from .openload import PhantomJSwrapper
  23. from ..jsinterp import JSInterpreter
  24. from ..networking.exceptions import HTTPError, network_exceptions
  25. from ..utils import (
  26. NO_DEFAULT,
  27. ExtractorError,
  28. LazyList,
  29. UserNotLive,
  30. bug_reports_message,
  31. classproperty,
  32. clean_html,
  33. datetime_from_str,
  34. dict_get,
  35. filesize_from_tbr,
  36. filter_dict,
  37. float_or_none,
  38. format_field,
  39. get_first,
  40. int_or_none,
  41. is_html,
  42. join_nonempty,
  43. js_to_json,
  44. mimetype2ext,
  45. orderedSet,
  46. parse_codecs,
  47. parse_count,
  48. parse_duration,
  49. parse_iso8601,
  50. parse_qs,
  51. qualities,
  52. remove_start,
  53. smuggle_url,
  54. str_or_none,
  55. str_to_int,
  56. strftime_or_none,
  57. traverse_obj,
  58. try_call,
  59. try_get,
  60. unescapeHTML,
  61. unified_strdate,
  62. unified_timestamp,
  63. unsmuggle_url,
  64. update_url_query,
  65. url_or_none,
  66. urljoin,
  67. variadic,
  68. )
  69. STREAMING_DATA_CLIENT_NAME = '__yt_dlp_client'
  70. # any clients starting with _ cannot be explicitly requested by the user
  71. INNERTUBE_CLIENTS = {
  72. 'web': {
  73. 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  74. 'INNERTUBE_CONTEXT': {
  75. 'client': {
  76. 'clientName': 'WEB',
  77. 'clientVersion': '2.20220801.00.00',
  78. },
  79. },
  80. 'INNERTUBE_CONTEXT_CLIENT_NAME': 1,
  81. },
  82. 'web_embedded': {
  83. 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  84. 'INNERTUBE_CONTEXT': {
  85. 'client': {
  86. 'clientName': 'WEB_EMBEDDED_PLAYER',
  87. 'clientVersion': '1.20220731.00.00',
  88. },
  89. },
  90. 'INNERTUBE_CONTEXT_CLIENT_NAME': 56,
  91. },
  92. 'web_music': {
  93. 'INNERTUBE_API_KEY': 'AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30',
  94. 'INNERTUBE_HOST': 'music.youtube.com',
  95. 'INNERTUBE_CONTEXT': {
  96. 'client': {
  97. 'clientName': 'WEB_REMIX',
  98. 'clientVersion': '1.20220727.01.00',
  99. },
  100. },
  101. 'INNERTUBE_CONTEXT_CLIENT_NAME': 67,
  102. },
  103. 'web_creator': {
  104. 'INNERTUBE_API_KEY': 'AIzaSyBUPetSUmoZL-OhlxA7wSac5XinrygCqMo',
  105. 'INNERTUBE_CONTEXT': {
  106. 'client': {
  107. 'clientName': 'WEB_CREATOR',
  108. 'clientVersion': '1.20220726.00.00',
  109. },
  110. },
  111. 'INNERTUBE_CONTEXT_CLIENT_NAME': 62,
  112. },
  113. 'android': {
  114. 'INNERTUBE_API_KEY': 'AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w',
  115. 'INNERTUBE_CONTEXT': {
  116. 'client': {
  117. 'clientName': 'ANDROID',
  118. 'clientVersion': '19.09.37',
  119. 'androidSdkVersion': 30,
  120. 'userAgent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  121. },
  122. },
  123. 'INNERTUBE_CONTEXT_CLIENT_NAME': 3,
  124. 'REQUIRE_JS_PLAYER': False,
  125. },
  126. 'android_embedded': {
  127. 'INNERTUBE_API_KEY': 'AIzaSyCjc_pVEDi4qsv5MtC2dMXzpIaDoRFLsxw',
  128. 'INNERTUBE_CONTEXT': {
  129. 'client': {
  130. 'clientName': 'ANDROID_EMBEDDED_PLAYER',
  131. 'clientVersion': '19.09.37',
  132. 'androidSdkVersion': 30,
  133. 'userAgent': 'com.google.android.youtube/19.09.37 (Linux; U; Android 11) gzip',
  134. },
  135. },
  136. 'INNERTUBE_CONTEXT_CLIENT_NAME': 55,
  137. 'REQUIRE_JS_PLAYER': False,
  138. },
  139. 'android_music': {
  140. 'INNERTUBE_API_KEY': 'AIzaSyAOghZGza2MQSZkY_zfZ370N-PUdXEo8AI',
  141. 'INNERTUBE_CONTEXT': {
  142. 'client': {
  143. 'clientName': 'ANDROID_MUSIC',
  144. 'clientVersion': '6.42.52',
  145. 'androidSdkVersion': 30,
  146. 'userAgent': 'com.google.android.apps.youtube.music/6.42.52 (Linux; U; Android 11) gzip',
  147. },
  148. },
  149. 'INNERTUBE_CONTEXT_CLIENT_NAME': 21,
  150. 'REQUIRE_JS_PLAYER': False,
  151. },
  152. 'android_creator': {
  153. 'INNERTUBE_API_KEY': 'AIzaSyD_qjV8zaaUMehtLkrKFgVeSX_Iqbtyws8',
  154. 'INNERTUBE_CONTEXT': {
  155. 'client': {
  156. 'clientName': 'ANDROID_CREATOR',
  157. 'clientVersion': '22.30.100',
  158. 'androidSdkVersion': 30,
  159. 'userAgent': 'com.google.android.apps.youtube.creator/22.30.100 (Linux; U; Android 11) gzip',
  160. },
  161. },
  162. 'INNERTUBE_CONTEXT_CLIENT_NAME': 14,
  163. 'REQUIRE_JS_PLAYER': False,
  164. },
  165. # iOS clients have HLS live streams. Setting device model to get 60fps formats.
  166. # See: https://github.com/TeamNewPipe/NewPipeExtractor/issues/680#issuecomment-1002724558
  167. 'ios': {
  168. 'INNERTUBE_API_KEY': 'AIzaSyB-63vPrdThhKuerbB2N_l7Kwwcxj6yUAc',
  169. 'INNERTUBE_CONTEXT': {
  170. 'client': {
  171. 'clientName': 'IOS',
  172. 'clientVersion': '19.09.3',
  173. 'deviceModel': 'iPhone14,3',
  174. 'userAgent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  175. },
  176. },
  177. 'INNERTUBE_CONTEXT_CLIENT_NAME': 5,
  178. 'REQUIRE_JS_PLAYER': False,
  179. },
  180. 'ios_embedded': {
  181. 'INNERTUBE_CONTEXT': {
  182. 'client': {
  183. 'clientName': 'IOS_MESSAGES_EXTENSION',
  184. 'clientVersion': '19.09.3',
  185. 'deviceModel': 'iPhone14,3',
  186. 'userAgent': 'com.google.ios.youtube/19.09.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  187. },
  188. },
  189. 'INNERTUBE_CONTEXT_CLIENT_NAME': 66,
  190. 'REQUIRE_JS_PLAYER': False,
  191. },
  192. 'ios_music': {
  193. 'INNERTUBE_API_KEY': 'AIzaSyBAETezhkwP0ZWA02RsqT1zu78Fpt0bC_s',
  194. 'INNERTUBE_CONTEXT': {
  195. 'client': {
  196. 'clientName': 'IOS_MUSIC',
  197. 'clientVersion': '6.33.3',
  198. 'deviceModel': 'iPhone14,3',
  199. 'userAgent': 'com.google.ios.youtubemusic/6.33.3 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  200. },
  201. },
  202. 'INNERTUBE_CONTEXT_CLIENT_NAME': 26,
  203. 'REQUIRE_JS_PLAYER': False,
  204. },
  205. 'ios_creator': {
  206. 'INNERTUBE_CONTEXT': {
  207. 'client': {
  208. 'clientName': 'IOS_CREATOR',
  209. 'clientVersion': '22.33.101',
  210. 'deviceModel': 'iPhone14,3',
  211. 'userAgent': 'com.google.ios.ytcreator/22.33.101 (iPhone14,3; U; CPU iOS 15_6 like Mac OS X)',
  212. },
  213. },
  214. 'INNERTUBE_CONTEXT_CLIENT_NAME': 15,
  215. 'REQUIRE_JS_PLAYER': False,
  216. },
  217. # mweb has 'ultralow' formats
  218. # See: https://github.com/yt-dlp/yt-dlp/pull/557
  219. 'mweb': {
  220. 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  221. 'INNERTUBE_CONTEXT': {
  222. 'client': {
  223. 'clientName': 'MWEB',
  224. 'clientVersion': '2.20220801.00.00',
  225. },
  226. },
  227. 'INNERTUBE_CONTEXT_CLIENT_NAME': 2,
  228. },
  229. # This client can access age restricted videos (unless the uploader has disabled the 'allow embedding' option)
  230. # See: https://github.com/zerodytrash/YouTube-Internal-Clients
  231. 'tv_embedded': {
  232. 'INNERTUBE_API_KEY': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  233. 'INNERTUBE_CONTEXT': {
  234. 'client': {
  235. 'clientName': 'TVHTML5_SIMPLY_EMBEDDED_PLAYER',
  236. 'clientVersion': '2.0',
  237. },
  238. },
  239. 'INNERTUBE_CONTEXT_CLIENT_NAME': 85,
  240. },
  241. # This client has pre-merged video+audio 720p/1080p streams
  242. 'mediaconnect': {
  243. 'INNERTUBE_CONTEXT': {
  244. 'client': {
  245. 'clientName': 'MEDIA_CONNECT_FRONTEND',
  246. 'clientVersion': '0.1',
  247. },
  248. },
  249. 'INNERTUBE_CONTEXT_CLIENT_NAME': 95,
  250. },
  251. }
  252. def _split_innertube_client(client_name):
  253. variant, *base = client_name.rsplit('.', 1)
  254. if base:
  255. return variant, base[0], variant
  256. base, *variant = client_name.split('_', 1)
  257. return client_name, base, variant[0] if variant else None
  258. def short_client_name(client_name):
  259. main, *parts = _split_innertube_client(client_name)[0].replace('embedscreen', 'e_s').split('_')
  260. return join_nonempty(main[:4], ''.join(x[0] for x in parts)).upper()
  261. def build_innertube_clients():
  262. THIRD_PARTY = {
  263. 'embedUrl': 'https://www.youtube.com/', # Can be any valid URL
  264. }
  265. BASE_CLIENTS = ('ios', 'android', 'web', 'tv', 'mweb')
  266. priority = qualities(BASE_CLIENTS[::-1])
  267. for client, ytcfg in tuple(INNERTUBE_CLIENTS.items()):
  268. ytcfg.setdefault('INNERTUBE_API_KEY', 'AIzaSyDCU8hByM-4DrUqRUYnGn-3llEO78bcxq8')
  269. ytcfg.setdefault('INNERTUBE_HOST', 'www.youtube.com')
  270. ytcfg.setdefault('REQUIRE_JS_PLAYER', True)
  271. ytcfg['INNERTUBE_CONTEXT']['client'].setdefault('hl', 'en')
  272. _, base_client, variant = _split_innertube_client(client)
  273. ytcfg['priority'] = 10 * priority(base_client)
  274. if not variant:
  275. INNERTUBE_CLIENTS[f'{client}_embedscreen'] = embedscreen = copy.deepcopy(ytcfg)
  276. embedscreen['INNERTUBE_CONTEXT']['client']['clientScreen'] = 'EMBED'
  277. embedscreen['INNERTUBE_CONTEXT']['thirdParty'] = THIRD_PARTY
  278. embedscreen['priority'] -= 3
  279. elif variant == 'embedded':
  280. ytcfg['INNERTUBE_CONTEXT']['thirdParty'] = THIRD_PARTY
  281. ytcfg['priority'] -= 2
  282. else:
  283. ytcfg['priority'] -= 3
  284. build_innertube_clients()
  285. class BadgeType(enum.Enum):
  286. AVAILABILITY_UNLISTED = enum.auto()
  287. AVAILABILITY_PRIVATE = enum.auto()
  288. AVAILABILITY_PUBLIC = enum.auto()
  289. AVAILABILITY_PREMIUM = enum.auto()
  290. AVAILABILITY_SUBSCRIPTION = enum.auto()
  291. LIVE_NOW = enum.auto()
  292. VERIFIED = enum.auto()
  293. class YoutubeBaseInfoExtractor(InfoExtractor):
  294. """Provide base functions for Youtube extractors"""
  295. _RESERVED_NAMES = (
  296. r'channel|c|user|playlist|watch|w|v|embed|e|live|watch_popup|clip|'
  297. r'shorts|movies|results|search|shared|hashtag|trending|explore|feed|feeds|'
  298. r'browse|oembed|get_video_info|iframe_api|s/player|source|'
  299. r'storefront|oops|index|account|t/terms|about|upload|signin|logout')
  300. _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM|WL|LL|LM)'
  301. # _NETRC_MACHINE = 'youtube'
  302. # If True it will raise an error if no login info is provided
  303. _LOGIN_REQUIRED = False
  304. _INVIDIOUS_SITES = (
  305. # invidious-redirect websites
  306. r'(?:www\.)?redirect\.invidious\.io',
  307. r'(?:(?:www|dev)\.)?invidio\.us',
  308. # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/docs/instances.md
  309. r'(?:www\.)?invidious\.pussthecat\.org',
  310. r'(?:www\.)?invidious\.zee\.li',
  311. r'(?:www\.)?invidious\.ethibox\.fr',
  312. r'(?:www\.)?iv\.ggtyler\.dev',
  313. r'(?:www\.)?inv\.vern\.i2p',
  314. r'(?:www\.)?am74vkcrjp2d5v36lcdqgsj2m6x36tbrkhsruoegwfcizzabnfgf5zyd\.onion',
  315. r'(?:www\.)?inv\.riverside\.rocks',
  316. r'(?:www\.)?invidious\.silur\.me',
  317. r'(?:www\.)?inv\.bp\.projectsegfau\.lt',
  318. r'(?:www\.)?invidious\.g4c3eya4clenolymqbpgwz3q3tawoxw56yhzk4vugqrl6dtu3ejvhjid\.onion',
  319. r'(?:www\.)?invidious\.slipfox\.xyz',
  320. r'(?:www\.)?invidious\.esmail5pdn24shtvieloeedh7ehz3nrwcdivnfhfcedl7gf4kwddhkqd\.onion',
  321. r'(?:www\.)?inv\.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad\.onion',
  322. r'(?:www\.)?invidious\.tiekoetter\.com',
  323. r'(?:www\.)?iv\.odysfvr23q5wgt7i456o5t3trw2cw5dgn56vbjfbq2m7xsc5vqbqpcyd\.onion',
  324. r'(?:www\.)?invidious\.nerdvpn\.de',
  325. r'(?:www\.)?invidious\.weblibre\.org',
  326. r'(?:www\.)?inv\.odyssey346\.dev',
  327. r'(?:www\.)?invidious\.dhusch\.de',
  328. r'(?:www\.)?iv\.melmac\.space',
  329. r'(?:www\.)?watch\.thekitty\.zone',
  330. r'(?:www\.)?invidious\.privacydev\.net',
  331. r'(?:www\.)?ng27owmagn5amdm7l5s3rsqxwscl5ynppnis5dqcasogkyxcfqn7psid\.onion',
  332. r'(?:www\.)?invidious\.drivet\.xyz',
  333. r'(?:www\.)?vid\.priv\.au',
  334. r'(?:www\.)?euxxcnhsynwmfidvhjf6uzptsmh4dipkmgdmcmxxuo7tunp3ad2jrwyd\.onion',
  335. r'(?:www\.)?inv\.vern\.cc',
  336. r'(?:www\.)?invidious\.esmailelbob\.xyz',
  337. r'(?:www\.)?invidious\.sethforprivacy\.com',
  338. r'(?:www\.)?yt\.oelrichsgarcia\.de',
  339. r'(?:www\.)?yt\.artemislena\.eu',
  340. r'(?:www\.)?invidious\.flokinet\.to',
  341. r'(?:www\.)?invidious\.baczek\.me',
  342. r'(?:www\.)?y\.com\.sb',
  343. r'(?:www\.)?invidious\.epicsite\.xyz',
  344. r'(?:www\.)?invidious\.lidarshield\.cloud',
  345. r'(?:www\.)?yt\.funami\.tech',
  346. r'(?:www\.)?invidious\.3o7z6yfxhbw7n3za4rss6l434kmv55cgw2vuziwuigpwegswvwzqipyd\.onion',
  347. r'(?:www\.)?osbivz6guyeahrwp2lnwyjk2xos342h4ocsxyqrlaopqjuhwn2djiiyd\.onion',
  348. r'(?:www\.)?u2cvlit75owumwpy4dj2hsmvkq7nvrclkpht7xgyye2pyoxhpmclkrad\.onion',
  349. # youtube-dl invidious instances list
  350. r'(?:(?:www|no)\.)?invidiou\.sh',
  351. r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
  352. r'(?:www\.)?invidious\.kabi\.tk',
  353. r'(?:www\.)?invidious\.mastodon\.host',
  354. r'(?:www\.)?invidious\.zapashcanon\.fr',
  355. r'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
  356. r'(?:www\.)?invidious\.tinfoil-hat\.net',
  357. r'(?:www\.)?invidious\.himiko\.cloud',
  358. r'(?:www\.)?invidious\.reallyancient\.tech',
  359. r'(?:www\.)?invidious\.tube',
  360. r'(?:www\.)?invidiou\.site',
  361. r'(?:www\.)?invidious\.site',
  362. r'(?:www\.)?invidious\.xyz',
  363. r'(?:www\.)?invidious\.nixnet\.xyz',
  364. r'(?:www\.)?invidious\.048596\.xyz',
  365. r'(?:www\.)?invidious\.drycat\.fr',
  366. r'(?:www\.)?inv\.skyn3t\.in',
  367. r'(?:www\.)?tube\.poal\.co',
  368. r'(?:www\.)?tube\.connect\.cafe',
  369. r'(?:www\.)?vid\.wxzm\.sx',
  370. r'(?:www\.)?vid\.mint\.lgbt',
  371. r'(?:www\.)?vid\.puffyan\.us',
  372. r'(?:www\.)?yewtu\.be',
  373. r'(?:www\.)?yt\.elukerio\.org',
  374. r'(?:www\.)?yt\.lelux\.fi',
  375. r'(?:www\.)?invidious\.ggc-project\.de',
  376. r'(?:www\.)?yt\.maisputain\.ovh',
  377. r'(?:www\.)?ytprivate\.com',
  378. r'(?:www\.)?invidious\.13ad\.de',
  379. r'(?:www\.)?invidious\.toot\.koeln',
  380. r'(?:www\.)?invidious\.fdn\.fr',
  381. r'(?:www\.)?watch\.nettohikari\.com',
  382. r'(?:www\.)?invidious\.namazso\.eu',
  383. r'(?:www\.)?invidious\.silkky\.cloud',
  384. r'(?:www\.)?invidious\.exonip\.de',
  385. r'(?:www\.)?invidious\.riverside\.rocks',
  386. r'(?:www\.)?invidious\.blamefran\.net',
  387. r'(?:www\.)?invidious\.moomoo\.de',
  388. r'(?:www\.)?ytb\.trom\.tf',
  389. r'(?:www\.)?yt\.cyberhost\.uk',
  390. r'(?:www\.)?kgg2m7yk5aybusll\.onion',
  391. r'(?:www\.)?qklhadlycap4cnod\.onion',
  392. r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
  393. r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
  394. r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
  395. r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
  396. r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
  397. r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
  398. r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
  399. r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
  400. r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
  401. r'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
  402. # piped instances from https://github.com/TeamPiped/Piped/wiki/Instances
  403. r'(?:www\.)?piped\.kavin\.rocks',
  404. r'(?:www\.)?piped\.tokhmi\.xyz',
  405. r'(?:www\.)?piped\.syncpundit\.io',
  406. r'(?:www\.)?piped\.mha\.fi',
  407. r'(?:www\.)?watch\.whatever\.social',
  408. r'(?:www\.)?piped\.garudalinux\.org',
  409. r'(?:www\.)?piped\.rivo\.lol',
  410. r'(?:www\.)?piped-libre\.kavin\.rocks',
  411. r'(?:www\.)?yt\.jae\.fi',
  412. r'(?:www\.)?piped\.mint\.lgbt',
  413. r'(?:www\.)?il\.ax',
  414. r'(?:www\.)?piped\.esmailelbob\.xyz',
  415. r'(?:www\.)?piped\.projectsegfau\.lt',
  416. r'(?:www\.)?piped\.privacydev\.net',
  417. r'(?:www\.)?piped\.palveluntarjoaja\.eu',
  418. r'(?:www\.)?piped\.smnz\.de',
  419. r'(?:www\.)?piped\.adminforge\.de',
  420. r'(?:www\.)?watch\.whatevertinfoil\.de',
  421. r'(?:www\.)?piped\.qdi\.fi',
  422. r'(?:(?:www|cf)\.)?piped\.video',
  423. r'(?:www\.)?piped\.aeong\.one',
  424. r'(?:www\.)?piped\.moomoo\.me',
  425. r'(?:www\.)?piped\.chauvet\.pro',
  426. r'(?:www\.)?watch\.leptons\.xyz',
  427. r'(?:www\.)?pd\.vern\.cc',
  428. r'(?:www\.)?piped\.hostux\.net',
  429. r'(?:www\.)?piped\.lunar\.icu',
  430. # Hyperpipe instances from https://hyperpipe.codeberg.page/
  431. r'(?:www\.)?hyperpipe\.surge\.sh',
  432. r'(?:www\.)?hyperpipe\.esmailelbob\.xyz',
  433. r'(?:www\.)?listen\.whatever\.social',
  434. r'(?:www\.)?music\.adminforge\.de',
  435. )
  436. # extracted from account/account_menu ep
  437. # XXX: These are the supported YouTube UI and API languages,
  438. # which is slightly different from languages supported for translation in YouTube studio
  439. _SUPPORTED_LANG_CODES = [
  440. 'af', 'az', 'id', 'ms', 'bs', 'ca', 'cs', 'da', 'de', 'et', 'en-IN', 'en-GB', 'en', 'es',
  441. 'es-419', 'es-US', 'eu', 'fil', 'fr', 'fr-CA', 'gl', 'hr', 'zu', 'is', 'it', 'sw', 'lv',
  442. 'lt', 'hu', 'nl', 'no', 'uz', 'pl', 'pt-PT', 'pt', 'ro', 'sq', 'sk', 'sl', 'sr-Latn', 'fi',
  443. 'sv', 'vi', 'tr', 'be', 'bg', 'ky', 'kk', 'mk', 'mn', 'ru', 'sr', 'uk', 'el', 'hy', 'iw',
  444. 'ur', 'ar', 'fa', 'ne', 'mr', 'hi', 'as', 'bn', 'pa', 'gu', 'or', 'ta', 'te', 'kn', 'ml',
  445. 'si', 'th', 'lo', 'my', 'ka', 'am', 'km', 'zh-CN', 'zh-TW', 'zh-HK', 'ja', 'ko',
  446. ]
  447. _IGNORED_WARNINGS = {
  448. 'Unavailable videos will be hidden during playback',
  449. 'Unavailable videos are hidden',
  450. }
  451. _YT_HANDLE_RE = r'@[\w.-]{3,30}' # https://support.google.com/youtube/answer/11585688?hl=en
  452. _YT_CHANNEL_UCID_RE = r'UC[\w-]{22}'
  453. def ucid_or_none(self, ucid):
  454. return self._search_regex(rf'^({self._YT_CHANNEL_UCID_RE})$', ucid, 'UC-id', default=None)
  455. def handle_or_none(self, handle):
  456. return self._search_regex(rf'^({self._YT_HANDLE_RE})$', handle, '@-handle', default=None)
  457. def handle_from_url(self, url):
  458. return self._search_regex(rf'^(?:https?://(?:www\.)?youtube\.com)?/({self._YT_HANDLE_RE})',
  459. url, 'channel handle', default=None)
  460. def ucid_from_url(self, url):
  461. return self._search_regex(rf'^(?:https?://(?:www\.)?youtube\.com)?/({self._YT_CHANNEL_UCID_RE})',
  462. url, 'channel id', default=None)
  463. @functools.cached_property
  464. def _preferred_lang(self):
  465. """
  466. Returns a language code supported by YouTube for the user preferred language.
  467. Returns None if no preferred language set.
  468. """
  469. preferred_lang = self._configuration_arg('lang', ie_key='Youtube', casesense=True, default=[''])[0]
  470. if not preferred_lang:
  471. return
  472. if preferred_lang not in self._SUPPORTED_LANG_CODES:
  473. raise ExtractorError(
  474. f'Unsupported language code: {preferred_lang}. Supported language codes (case-sensitive): {join_nonempty(*self._SUPPORTED_LANG_CODES, delim=", ")}.',
  475. expected=True)
  476. elif preferred_lang != 'en':
  477. self.report_warning(
  478. f'Preferring "{preferred_lang}" translated fields. Note that some metadata extraction may fail or be incorrect.')
  479. return preferred_lang
  480. def _initialize_consent(self):
  481. cookies = self._get_cookies('https://www.youtube.com/')
  482. if cookies.get('__Secure-3PSID'):
  483. return
  484. socs = cookies.get('SOCS')
  485. if socs and not socs.value.startswith('CAA'): # not consented
  486. return
  487. self._set_cookie('.youtube.com', 'SOCS', 'CAI', secure=True) # accept all (required for mixes)
  488. def _initialize_pref(self):
  489. cookies = self._get_cookies('https://www.youtube.com/')
  490. pref_cookie = cookies.get('PREF')
  491. pref = {}
  492. if pref_cookie:
  493. try:
  494. pref = dict(urllib.parse.parse_qsl(pref_cookie.value))
  495. except ValueError:
  496. self.report_warning('Failed to parse user PREF cookie' + bug_reports_message())
  497. pref.update({'hl': self._preferred_lang or 'en', 'tz': 'UTC'})
  498. self._set_cookie('.youtube.com', name='PREF', value=urllib.parse.urlencode(pref))
  499. def _real_initialize(self):
  500. self._initialize_pref()
  501. self._initialize_consent()
  502. self._check_login_required()
  503. def _check_login_required(self):
  504. if self._LOGIN_REQUIRED and not self._cookies_passed:
  505. self.raise_login_required('Login details are needed to download this content', method='cookies')
  506. _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*='
  507. _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*='
  508. def _get_default_ytcfg(self, client='web'):
  509. return copy.deepcopy(INNERTUBE_CLIENTS[client])
  510. def _get_innertube_host(self, client='web'):
  511. return INNERTUBE_CLIENTS[client]['INNERTUBE_HOST']
  512. def _ytcfg_get_safe(self, ytcfg, getter, expected_type=None, default_client='web'):
  513. # try_get but with fallback to default ytcfg client values when present
  514. _func = lambda y: try_get(y, getter, expected_type)
  515. return _func(ytcfg) or _func(self._get_default_ytcfg(default_client))
  516. def _extract_client_name(self, ytcfg, default_client='web'):
  517. return self._ytcfg_get_safe(
  518. ytcfg, (lambda x: x['INNERTUBE_CLIENT_NAME'],
  519. lambda x: x['INNERTUBE_CONTEXT']['client']['clientName']), str, default_client)
  520. def _extract_client_version(self, ytcfg, default_client='web'):
  521. return self._ytcfg_get_safe(
  522. ytcfg, (lambda x: x['INNERTUBE_CLIENT_VERSION'],
  523. lambda x: x['INNERTUBE_CONTEXT']['client']['clientVersion']), str, default_client)
  524. def _select_api_hostname(self, req_api_hostname, default_client=None):
  525. return (self._configuration_arg('innertube_host', [''], ie_key=YoutubeIE.ie_key())[0]
  526. or req_api_hostname or self._get_innertube_host(default_client or 'web'))
  527. def _extract_api_key(self, ytcfg=None, default_client='web'):
  528. return self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_API_KEY'], str, default_client)
  529. def _extract_context(self, ytcfg=None, default_client='web'):
  530. context = get_first(
  531. (ytcfg, self._get_default_ytcfg(default_client)), 'INNERTUBE_CONTEXT', expected_type=dict)
  532. # Enforce language and tz for extraction
  533. client_context = traverse_obj(context, 'client', expected_type=dict, default={})
  534. client_context.update({'hl': self._preferred_lang or 'en', 'timeZone': 'UTC', 'utcOffsetMinutes': 0})
  535. return context
  536. _SAPISID = None
  537. def _generate_sapisidhash_header(self, origin='https://www.youtube.com'):
  538. time_now = round(time.time())
  539. if self._SAPISID is None:
  540. yt_cookies = self._get_cookies('https://www.youtube.com')
  541. # Sometimes SAPISID cookie isn't present but __Secure-3PAPISID is.
  542. # See: https://github.com/yt-dlp/yt-dlp/issues/393
  543. sapisid_cookie = dict_get(
  544. yt_cookies, ('__Secure-3PAPISID', 'SAPISID'))
  545. if sapisid_cookie and sapisid_cookie.value:
  546. self._SAPISID = sapisid_cookie.value
  547. self.write_debug('Extracted SAPISID cookie')
  548. # SAPISID cookie is required if not already present
  549. if not yt_cookies.get('SAPISID'):
  550. self.write_debug('Copying __Secure-3PAPISID cookie to SAPISID cookie')
  551. self._set_cookie(
  552. '.youtube.com', 'SAPISID', self._SAPISID, secure=True, expire_time=time_now + 3600)
  553. else:
  554. self._SAPISID = False
  555. if not self._SAPISID:
  556. return None
  557. # SAPISIDHASH algorithm from https://stackoverflow.com/a/32065323
  558. sapisidhash = hashlib.sha1(
  559. f'{time_now} {self._SAPISID} {origin}'.encode()).hexdigest()
  560. return f'SAPISIDHASH {time_now}_{sapisidhash}'
  561. def _call_api(self, ep, query, video_id, fatal=True, headers=None,
  562. note='Downloading API JSON', errnote='Unable to download API page',
  563. context=None, api_key=None, api_hostname=None, default_client='web'):
  564. data = {'context': context} if context else {'context': self._extract_context(default_client=default_client)}
  565. data.update(query)
  566. real_headers = self.generate_api_headers(default_client=default_client)
  567. real_headers.update({'content-type': 'application/json'})
  568. if headers:
  569. real_headers.update(headers)
  570. api_key = (self._configuration_arg('innertube_key', [''], ie_key=YoutubeIE.ie_key(), casesense=True)[0]
  571. or api_key or self._extract_api_key(default_client=default_client))
  572. return self._download_json(
  573. f'https://{self._select_api_hostname(api_hostname, default_client)}/youtubei/v1/{ep}',
  574. video_id=video_id, fatal=fatal, note=note, errnote=errnote,
  575. data=json.dumps(data).encode('utf8'), headers=real_headers,
  576. query={'key': api_key, 'prettyPrint': 'false'})
  577. def extract_yt_initial_data(self, item_id, webpage, fatal=True):
  578. return self._search_json(self._YT_INITIAL_DATA_RE, webpage, 'yt initial data', item_id, fatal=fatal)
  579. @staticmethod
  580. def _extract_session_index(*data):
  581. """
  582. Index of current account in account list.
  583. See: https://github.com/yt-dlp/yt-dlp/pull/519
  584. """
  585. for ytcfg in data:
  586. session_index = int_or_none(try_get(ytcfg, lambda x: x['SESSION_INDEX']))
  587. if session_index is not None:
  588. return session_index
  589. # Deprecated?
  590. def _extract_identity_token(self, ytcfg=None, webpage=None):
  591. if ytcfg:
  592. token = try_get(ytcfg, lambda x: x['ID_TOKEN'], str)
  593. if token:
  594. return token
  595. if webpage:
  596. return self._search_regex(
  597. r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
  598. 'identity token', default=None, fatal=False)
  599. @staticmethod
  600. def _extract_account_syncid(*args):
  601. """
  602. Extract syncId required to download private playlists of secondary channels
  603. @params response and/or ytcfg
  604. """
  605. for data in args:
  606. # ytcfg includes channel_syncid if on secondary channel
  607. delegated_sid = try_get(data, lambda x: x['DELEGATED_SESSION_ID'], str)
  608. if delegated_sid:
  609. return delegated_sid
  610. sync_ids = (try_get(
  611. data, (lambda x: x['responseContext']['mainAppWebResponseContext']['datasyncId'],
  612. lambda x: x['DATASYNC_ID']), str) or '').split('||')
  613. if len(sync_ids) >= 2 and sync_ids[1]:
  614. # datasyncid is of the form "channel_syncid||user_syncid" for secondary channel
  615. # and just "user_syncid||" for primary channel. We only want the channel_syncid
  616. return sync_ids[0]
  617. @staticmethod
  618. def _extract_visitor_data(*args):
  619. """
  620. Extracts visitorData from an API response or ytcfg
  621. Appears to be used to track session state
  622. """
  623. return get_first(
  624. args, [('VISITOR_DATA', ('INNERTUBE_CONTEXT', 'client', 'visitorData'), ('responseContext', 'visitorData'))],
  625. expected_type=str)
  626. @functools.cached_property
  627. def is_authenticated(self):
  628. return bool(self._generate_sapisidhash_header())
  629. def extract_ytcfg(self, video_id, webpage):
  630. if not webpage:
  631. return {}
  632. return self._parse_json(
  633. self._search_regex(
  634. r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
  635. default='{}'), video_id, fatal=False) or {}
  636. def generate_api_headers(
  637. self, *, ytcfg=None, account_syncid=None, session_index=None,
  638. visitor_data=None, identity_token=None, api_hostname=None, default_client='web'):
  639. origin = 'https://' + (self._select_api_hostname(api_hostname, default_client))
  640. headers = {
  641. 'X-YouTube-Client-Name': str(
  642. self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT_CLIENT_NAME'], default_client=default_client)),
  643. 'X-YouTube-Client-Version': self._extract_client_version(ytcfg, default_client),
  644. 'Origin': origin,
  645. 'X-Youtube-Identity-Token': identity_token or self._extract_identity_token(ytcfg),
  646. 'X-Goog-PageId': account_syncid or self._extract_account_syncid(ytcfg),
  647. 'X-Goog-Visitor-Id': visitor_data or self._extract_visitor_data(ytcfg),
  648. 'User-Agent': self._ytcfg_get_safe(ytcfg, lambda x: x['INNERTUBE_CONTEXT']['client']['userAgent'], default_client=default_client),
  649. }
  650. if session_index is None:
  651. session_index = self._extract_session_index(ytcfg)
  652. if account_syncid or session_index is not None:
  653. headers['X-Goog-AuthUser'] = session_index if session_index is not None else 0
  654. auth = self._generate_sapisidhash_header(origin)
  655. if auth is not None:
  656. headers['Authorization'] = auth
  657. headers['X-Origin'] = origin
  658. return filter_dict(headers)
  659. def _download_ytcfg(self, client, video_id):
  660. url = {
  661. 'web': 'https://www.youtube.com',
  662. 'web_music': 'https://music.youtube.com',
  663. 'web_embedded': f'https://www.youtube.com/embed/{video_id}?html5=1',
  664. }.get(client)
  665. if not url:
  666. return {}
  667. webpage = self._download_webpage(
  668. url, video_id, fatal=False, note=f'Downloading {client.replace("_", " ").strip()} client config')
  669. return self.extract_ytcfg(video_id, webpage) or {}
  670. @staticmethod
  671. def _build_api_continuation_query(continuation, ctp=None):
  672. query = {
  673. 'continuation': continuation,
  674. }
  675. # TODO: Inconsistency with clickTrackingParams.
  676. # Currently we have a fixed ctp contained within context (from ytcfg)
  677. # and a ctp in root query for continuation.
  678. if ctp:
  679. query['clickTracking'] = {'clickTrackingParams': ctp}
  680. return query
  681. @classmethod
  682. def _extract_next_continuation_data(cls, renderer):
  683. next_continuation = try_get(
  684. renderer, (lambda x: x['continuations'][0]['nextContinuationData'],
  685. lambda x: x['continuation']['reloadContinuationData']), dict)
  686. if not next_continuation:
  687. return
  688. continuation = next_continuation.get('continuation')
  689. if not continuation:
  690. return
  691. ctp = next_continuation.get('clickTrackingParams')
  692. return cls._build_api_continuation_query(continuation, ctp)
  693. @classmethod
  694. def _extract_continuation_ep_data(cls, continuation_ep: dict):
  695. if isinstance(continuation_ep, dict):
  696. continuation = try_get(
  697. continuation_ep, lambda x: x['continuationCommand']['token'], str)
  698. if not continuation:
  699. return
  700. ctp = continuation_ep.get('clickTrackingParams')
  701. return cls._build_api_continuation_query(continuation, ctp)
  702. @classmethod
  703. def _extract_continuation(cls, renderer):
  704. next_continuation = cls._extract_next_continuation_data(renderer)
  705. if next_continuation:
  706. return next_continuation
  707. return traverse_obj(renderer, (
  708. ('contents', 'items', 'rows'), ..., 'continuationItemRenderer',
  709. ('continuationEndpoint', ('button', 'buttonRenderer', 'command')),
  710. ), get_all=False, expected_type=cls._extract_continuation_ep_data)
  711. @classmethod
  712. def _extract_alerts(cls, data):
  713. for alert_dict in try_get(data, lambda x: x['alerts'], list) or []:
  714. if not isinstance(alert_dict, dict):
  715. continue
  716. for alert in alert_dict.values():
  717. alert_type = alert.get('type')
  718. if not alert_type:
  719. continue
  720. message = cls._get_text(alert, 'text')
  721. if message:
  722. yield alert_type, message
  723. def _report_alerts(self, alerts, expected=True, fatal=True, only_once=False):
  724. errors, warnings = [], []
  725. for alert_type, alert_message in alerts:
  726. if alert_type.lower() == 'error' and fatal:
  727. errors.append([alert_type, alert_message])
  728. elif alert_message not in self._IGNORED_WARNINGS:
  729. warnings.append([alert_type, alert_message])
  730. for alert_type, alert_message in (warnings + errors[:-1]):
  731. self.report_warning(f'YouTube said: {alert_type} - {alert_message}', only_once=only_once)
  732. if errors:
  733. raise ExtractorError(f'YouTube said: {errors[-1][1]}', expected=expected)
  734. def _extract_and_report_alerts(self, data, *args, **kwargs):
  735. return self._report_alerts(self._extract_alerts(data), *args, **kwargs)
  736. def _extract_badges(self, badge_list: list):
  737. """
  738. Extract known BadgeType's from a list of badge renderers.
  739. @returns [{'type': BadgeType}]
  740. """
  741. icon_type_map = {
  742. 'PRIVACY_UNLISTED': BadgeType.AVAILABILITY_UNLISTED,
  743. 'PRIVACY_PRIVATE': BadgeType.AVAILABILITY_PRIVATE,
  744. 'PRIVACY_PUBLIC': BadgeType.AVAILABILITY_PUBLIC,
  745. 'CHECK_CIRCLE_THICK': BadgeType.VERIFIED,
  746. 'OFFICIAL_ARTIST_BADGE': BadgeType.VERIFIED,
  747. 'CHECK': BadgeType.VERIFIED,
  748. }
  749. badge_style_map = {
  750. 'BADGE_STYLE_TYPE_MEMBERS_ONLY': BadgeType.AVAILABILITY_SUBSCRIPTION,
  751. 'BADGE_STYLE_TYPE_PREMIUM': BadgeType.AVAILABILITY_PREMIUM,
  752. 'BADGE_STYLE_TYPE_LIVE_NOW': BadgeType.LIVE_NOW,
  753. 'BADGE_STYLE_TYPE_VERIFIED': BadgeType.VERIFIED,
  754. 'BADGE_STYLE_TYPE_VERIFIED_ARTIST': BadgeType.VERIFIED,
  755. }
  756. label_map = {
  757. 'unlisted': BadgeType.AVAILABILITY_UNLISTED,
  758. 'private': BadgeType.AVAILABILITY_PRIVATE,
  759. 'members only': BadgeType.AVAILABILITY_SUBSCRIPTION,
  760. 'live': BadgeType.LIVE_NOW,
  761. 'premium': BadgeType.AVAILABILITY_PREMIUM,
  762. 'verified': BadgeType.VERIFIED,
  763. 'official artist channel': BadgeType.VERIFIED,
  764. }
  765. badges = []
  766. for badge in traverse_obj(badge_list, (..., lambda key, _: re.search(r'[bB]adgeRenderer$', key))):
  767. badge_type = (
  768. icon_type_map.get(traverse_obj(badge, ('icon', 'iconType'), expected_type=str))
  769. or badge_style_map.get(traverse_obj(badge, 'style'))
  770. )
  771. if badge_type:
  772. badges.append({'type': badge_type})
  773. continue
  774. # fallback, won't work in some languages
  775. label = traverse_obj(
  776. badge, 'label', ('accessibilityData', 'label'), 'tooltip', 'iconTooltip', get_all=False, expected_type=str, default='')
  777. for match, label_badge_type in label_map.items():
  778. if match in label.lower():
  779. badges.append({'type': label_badge_type})
  780. break
  781. return badges
  782. @staticmethod
  783. def _has_badge(badges, badge_type):
  784. return bool(traverse_obj(badges, lambda _, v: v['type'] == badge_type))
  785. @staticmethod
  786. def _get_text(data, *path_list, max_runs=None):
  787. for path in path_list or [None]:
  788. if path is None:
  789. obj = [data]
  790. else:
  791. obj = traverse_obj(data, path, default=[])
  792. if not any(key is ... or isinstance(key, (list, tuple)) for key in variadic(path)):
  793. obj = [obj]
  794. for item in obj:
  795. text = try_get(item, lambda x: x['simpleText'], str)
  796. if text:
  797. return text
  798. runs = try_get(item, lambda x: x['runs'], list) or []
  799. if not runs and isinstance(item, list):
  800. runs = item
  801. runs = runs[:min(len(runs), max_runs or len(runs))]
  802. text = ''.join(traverse_obj(runs, (..., 'text'), expected_type=str))
  803. if text:
  804. return text
  805. def _get_count(self, data, *path_list):
  806. count_text = self._get_text(data, *path_list) or ''
  807. count = parse_count(count_text)
  808. if count is None:
  809. count = str_to_int(
  810. self._search_regex(r'^([\d,]+)', re.sub(r'\s', '', count_text), 'count', default=None))
  811. return count
  812. @staticmethod
  813. def _extract_thumbnails(data, *path_list, final_key='thumbnails'):
  814. """
  815. Extract thumbnails from thumbnails dict
  816. @param path_list: path list to level that contains 'thumbnails' key
  817. """
  818. thumbnails = []
  819. for path in path_list or [()]:
  820. for thumbnail in traverse_obj(data, (*variadic(path), final_key, ...)):
  821. thumbnail_url = url_or_none(thumbnail.get('url'))
  822. if not thumbnail_url:
  823. continue
  824. # Sometimes youtube gives a wrong thumbnail URL. See:
  825. # https://github.com/yt-dlp/yt-dlp/issues/233
  826. # https://github.com/ytdl-org/youtube-dl/issues/28023
  827. if 'maxresdefault' in thumbnail_url:
  828. thumbnail_url = thumbnail_url.split('?')[0]
  829. thumbnails.append({
  830. 'url': thumbnail_url,
  831. 'height': int_or_none(thumbnail.get('height')),
  832. 'width': int_or_none(thumbnail.get('width')),
  833. })
  834. return thumbnails
  835. @staticmethod
  836. def extract_relative_time(relative_time_text):
  837. """
  838. Extracts a relative time from string and converts to dt object
  839. e.g. 'streamed 6 days ago', '5 seconds ago (edited)', 'updated today', '8 yr ago'
  840. """
  841. # XXX: this could be moved to a general function in utils/_utils.py
  842. # The relative time text strings are roughly the same as what
  843. # Javascript's Intl.RelativeTimeFormat function generates.
  844. # See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
  845. mobj = re.search(
  846. r'(?P<start>today|yesterday|now)|(?P<time>\d+)\s*(?P<unit>sec(?:ond)?|s|min(?:ute)?|h(?:our|r)?|d(?:ay)?|w(?:eek|k)?|mo(?:nth)?|y(?:ear|r)?)s?\s*ago',
  847. relative_time_text)
  848. if mobj:
  849. start = mobj.group('start')
  850. if start:
  851. return datetime_from_str(start)
  852. try:
  853. return datetime_from_str('now-{}{}'.format(mobj.group('time'), mobj.group('unit')))
  854. except ValueError:
  855. return None
  856. def _parse_time_text(self, text):
  857. if not text:
  858. return
  859. dt_ = self.extract_relative_time(text)
  860. timestamp = None
  861. if isinstance(dt_, dt.datetime):
  862. timestamp = calendar.timegm(dt_.timetuple())
  863. if timestamp is None:
  864. timestamp = (
  865. unified_timestamp(text) or unified_timestamp(
  866. self._search_regex(
  867. (r'([a-z]+\s*\d{1,2},?\s*20\d{2})', r'(?:.+|^)(?:live|premieres|ed|ing)(?:\s*(?:on|for))?\s*(.+\d)'),
  868. text.lower(), 'time text', default=None)))
  869. if text and timestamp is None and self._preferred_lang in (None, 'en'):
  870. self.report_warning(
  871. f'Cannot parse localized time text "{text}"', only_once=True)
  872. return timestamp
  873. def _extract_response(self, item_id, query, note='Downloading API JSON', headers=None,
  874. ytcfg=None, check_get_keys=None, ep='browse', fatal=True, api_hostname=None,
  875. default_client='web'):
  876. raise_for_incomplete = bool(self._configuration_arg('raise_incomplete_data', ie_key=YoutubeIE))
  877. # Incomplete Data should be a warning by default when retries are exhausted, while other errors should be fatal.
  878. icd_retries = iter(self.RetryManager(fatal=raise_for_incomplete))
  879. icd_rm = next(icd_retries)
  880. main_retries = iter(self.RetryManager())
  881. main_rm = next(main_retries)
  882. # Manual retry loop for multiple RetryManagers
  883. # The proper RetryManager MUST be advanced after an error
  884. # and its result MUST be checked if the manager is non fatal
  885. while True:
  886. try:
  887. response = self._call_api(
  888. ep=ep, fatal=True, headers=headers,
  889. video_id=item_id, query=query, note=note,
  890. context=self._extract_context(ytcfg, default_client),
  891. api_key=self._extract_api_key(ytcfg, default_client),
  892. api_hostname=api_hostname, default_client=default_client)
  893. except ExtractorError as e:
  894. if not isinstance(e.cause, network_exceptions):
  895. return self._error_or_warning(e, fatal=fatal)
  896. elif not isinstance(e.cause, HTTPError):
  897. main_rm.error = e
  898. next(main_retries)
  899. continue
  900. first_bytes = e.cause.response.read(512)
  901. if not is_html(first_bytes):
  902. yt_error = try_get(
  903. self._parse_json(
  904. self._webpage_read_content(e.cause.response, None, item_id, prefix=first_bytes) or '{}', item_id, fatal=False),
  905. lambda x: x['error']['message'], str)
  906. if yt_error:
  907. self._report_alerts([('ERROR', yt_error)], fatal=False)
  908. # Downloading page may result in intermittent 5xx HTTP error
  909. # Sometimes a 404 is also received. See: https://github.com/ytdl-org/youtube-dl/issues/28289
  910. # We also want to catch all other network exceptions since errors in later pages can be troublesome
  911. # See https://github.com/yt-dlp/yt-dlp/issues/507#issuecomment-880188210
  912. if e.cause.status not in (403, 429):
  913. main_rm.error = e
  914. next(main_retries)
  915. continue
  916. return self._error_or_warning(e, fatal=fatal)
  917. try:
  918. self._extract_and_report_alerts(response, only_once=True)
  919. except ExtractorError as e:
  920. # YouTube's servers may return errors we want to retry on in a 200 OK response
  921. # See: https://github.com/yt-dlp/yt-dlp/issues/839
  922. if 'unknown error' in e.msg.lower():
  923. main_rm.error = e
  924. next(main_retries)
  925. continue
  926. return self._error_or_warning(e, fatal=fatal)
  927. # Youtube sometimes sends incomplete data
  928. # See: https://github.com/ytdl-org/youtube-dl/issues/28194
  929. if not traverse_obj(response, *variadic(check_get_keys)):
  930. icd_rm.error = ExtractorError('Incomplete data received', expected=True)
  931. should_retry = next(icd_retries, None)
  932. if not should_retry:
  933. return None
  934. continue
  935. return response
  936. @staticmethod
  937. def is_music_url(url):
  938. return re.match(r'(https?://)?music\.youtube\.com/', url) is not None
  939. def _extract_video(self, renderer):
  940. video_id = renderer.get('videoId')
  941. reel_header_renderer = traverse_obj(renderer, (
  942. 'navigationEndpoint', 'reelWatchEndpoint', 'overlay', 'reelPlayerOverlayRenderer',
  943. 'reelPlayerHeaderSupportedRenderers', 'reelPlayerHeaderRenderer'))
  944. title = self._get_text(renderer, 'title', 'headline') or self._get_text(reel_header_renderer, 'reelTitleText')
  945. description = self._get_text(renderer, 'descriptionSnippet')
  946. duration = int_or_none(renderer.get('lengthSeconds'))
  947. if duration is None:
  948. duration = parse_duration(self._get_text(
  949. renderer, 'lengthText', ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'text')))
  950. if duration is None:
  951. # XXX: should write a parser to be more general to support more cases (e.g. shorts in shorts tab)
  952. duration = parse_duration(self._search_regex(
  953. r'(?i)(ago)(?!.*\1)\s+(?P<duration>[a-z0-9 ,]+?)(?:\s+[\d,]+\s+views)?(?:\s+-\s+play\s+short)?$',
  954. traverse_obj(renderer, ('title', 'accessibility', 'accessibilityData', 'label'), default='', expected_type=str),
  955. video_id, default=None, group='duration'))
  956. channel_id = traverse_obj(
  957. renderer, ('shortBylineText', 'runs', ..., 'navigationEndpoint', 'browseEndpoint', 'browseId'),
  958. expected_type=str, get_all=False)
  959. if not channel_id:
  960. channel_id = traverse_obj(reel_header_renderer, ('channelNavigationEndpoint', 'browseEndpoint', 'browseId'))
  961. channel_id = self.ucid_or_none(channel_id)
  962. overlay_style = traverse_obj(
  963. renderer, ('thumbnailOverlays', ..., 'thumbnailOverlayTimeStatusRenderer', 'style'),
  964. get_all=False, expected_type=str)
  965. badges = self._extract_badges(traverse_obj(renderer, 'badges'))
  966. owner_badges = self._extract_badges(traverse_obj(renderer, 'ownerBadges'))
  967. navigation_url = urljoin('https://www.youtube.com/', traverse_obj(
  968. renderer, ('navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url'),
  969. expected_type=str)) or ''
  970. url = f'https://www.youtube.com/watch?v={video_id}'
  971. if overlay_style == 'SHORTS' or '/shorts/' in navigation_url:
  972. url = f'https://www.youtube.com/shorts/{video_id}'
  973. time_text = (self._get_text(renderer, 'publishedTimeText', 'videoInfo')
  974. or self._get_text(reel_header_renderer, 'timestampText') or '')
  975. scheduled_timestamp = str_to_int(traverse_obj(renderer, ('upcomingEventData', 'startTime'), get_all=False))
  976. live_status = (
  977. 'is_upcoming' if scheduled_timestamp is not None
  978. else 'was_live' if 'streamed' in time_text.lower()
  979. else 'is_live' if overlay_style == 'LIVE' or self._has_badge(badges, BadgeType.LIVE_NOW)
  980. else None)
  981. # videoInfo is a string like '50K views • 10 years ago'.
  982. view_count_text = self._get_text(renderer, 'viewCountText', 'shortViewCountText', 'videoInfo') or ''
  983. view_count = (0 if 'no views' in view_count_text.lower()
  984. else self._get_count({'simpleText': view_count_text}))
  985. view_count_field = 'concurrent_view_count' if live_status in ('is_live', 'is_upcoming') else 'view_count'
  986. channel = (self._get_text(renderer, 'ownerText', 'shortBylineText')
  987. or self._get_text(reel_header_renderer, 'channelTitleText'))
  988. channel_handle = traverse_obj(renderer, (
  989. 'shortBylineText', 'runs', ..., 'navigationEndpoint',
  990. (('commandMetadata', 'webCommandMetadata', 'url'), ('browseEndpoint', 'canonicalBaseUrl'))),
  991. expected_type=self.handle_from_url, get_all=False)
  992. return {
  993. '_type': 'url',
  994. 'ie_key': YoutubeIE.ie_key(),
  995. 'id': video_id,
  996. 'url': url,
  997. 'title': title,
  998. 'description': description,
  999. 'duration': duration,
  1000. 'channel_id': channel_id,
  1001. 'channel': channel,
  1002. 'channel_url': f'https://www.youtube.com/channel/{channel_id}' if channel_id else None,
  1003. 'uploader': channel,
  1004. 'uploader_id': channel_handle,
  1005. 'uploader_url': format_field(channel_handle, None, 'https://www.youtube.com/%s', default=None),
  1006. 'thumbnails': self._extract_thumbnails(renderer, 'thumbnail'),
  1007. 'timestamp': (self._parse_time_text(time_text)
  1008. if self._configuration_arg('approximate_date', ie_key=YoutubeTabIE)
  1009. else None),
  1010. 'release_timestamp': scheduled_timestamp,
  1011. 'availability':
  1012. 'public' if self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
  1013. else self._availability(
  1014. is_private=self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE) or None,
  1015. needs_premium=self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or None,
  1016. needs_subscription=self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION) or None,
  1017. is_unlisted=self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED) or None),
  1018. view_count_field: view_count,
  1019. 'live_status': live_status,
  1020. 'channel_is_verified': True if self._has_badge(owner_badges, BadgeType.VERIFIED) else None,
  1021. }
  1022. class YoutubeIE(YoutubeBaseInfoExtractor):
  1023. IE_DESC = 'YouTube'
  1024. _VALID_URL = r'''(?x)^
  1025. (
  1026. (?:https?://|//) # http(s):// or protocol-independent URL
  1027. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
  1028. (?:www\.)?deturl\.com/www\.youtube\.com|
  1029. (?:www\.)?pwnyoutube\.com|
  1030. (?:www\.)?hooktube\.com|
  1031. (?:www\.)?yourepeat\.com|
  1032. tube\.majestyc\.net|
  1033. {invidious}|
  1034. youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
  1035. (?:.*?\#/)? # handle anchor (#/) redirect urls
  1036. (?: # the various things that can precede the ID:
  1037. (?:(?:v|embed|e|shorts|live)/(?!videoseries|live_stream)) # v/ or embed/ or e/ or shorts/
  1038. |(?: # or the v= param in all its forms
  1039. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  1040. (?:\?|\#!?) # the params delimiter ? or # or #!
  1041. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  1042. v=
  1043. )
  1044. ))
  1045. |(?:
  1046. youtu\.be| # just youtu.be/xxxx
  1047. vid\.plus| # or vid.plus/xxxx
  1048. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  1049. {invidious}
  1050. )/
  1051. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  1052. )
  1053. )? # all until now is optional -> you can pass the naked ID
  1054. (?P<id>[0-9A-Za-z_-]{{11}}) # here is it! the YouTube video ID
  1055. (?(1).+)? # if we found the ID, everything can follow
  1056. (?:\#|$)'''.format(
  1057. invidious='|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
  1058. )
  1059. _EMBED_REGEX = [
  1060. r'''(?x)
  1061. (?:
  1062. <(?:[0-9A-Za-z-]+?)?iframe[^>]+?src=|
  1063. data-video-url=|
  1064. <embed[^>]+?src=|
  1065. embedSWF\(?:\s*|
  1066. <object[^>]+data=|
  1067. new\s+SWFObject\(
  1068. )
  1069. (["\'])
  1070. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1071. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1072. \1''',
  1073. # https://wordpress.org/plugins/lazy-load-for-videos/
  1074. r'''(?xs)
  1075. <a\s[^>]*\bhref="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"
  1076. \s[^>]*\bclass="[^"]*\blazy-load-youtube''',
  1077. ]
  1078. _RETURN_TYPE = 'video' # XXX: How to handle multifeed?
  1079. _PLAYER_INFO_RE = (
  1080. r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
  1081. r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
  1082. r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
  1083. )
  1084. _formats = { # NB: Used in YoutubeWebArchiveIE and GoogleDriveIE
  1085. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1086. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1087. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  1088. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  1089. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  1090. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1091. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1092. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1093. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  1094. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  1095. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1096. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1097. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1098. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1099. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1100. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1101. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1102. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1103. # 3D videos
  1104. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1105. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1106. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1107. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1108. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  1109. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1110. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1111. # Apple HTTP Live Streaming
  1112. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1113. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1114. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1115. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1116. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1117. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1118. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1119. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  1120. # DASH mp4 video
  1121. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1122. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1123. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1124. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1125. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1126. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  1127. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1128. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1129. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1130. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1131. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1132. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1133. # Dash mp4 audio
  1134. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  1135. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  1136. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  1137. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1138. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1139. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  1140. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  1141. # Dash webm
  1142. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1143. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1144. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1145. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1146. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1147. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1148. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  1149. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1150. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1151. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1152. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1153. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1154. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1155. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1156. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1157. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  1158. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1159. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1160. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1161. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1162. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1163. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1164. # Dash webm audio
  1165. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  1166. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  1167. # Dash webm audio with opus inside
  1168. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  1169. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  1170. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  1171. # RTMP (unnamed)
  1172. '_rtmp': {'protocol': 'rtmp'},
  1173. # av01 video only formats sometimes served with "unknown" codecs
  1174. '394': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
  1175. '395': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'av01.0.00M.08'},
  1176. '396': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'av01.0.01M.08'},
  1177. '397': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'av01.0.04M.08'},
  1178. '398': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'av01.0.05M.08'},
  1179. '399': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'av01.0.08M.08'},
  1180. '400': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
  1181. '401': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'av01.0.12M.08'},
  1182. }
  1183. _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  1184. _GEO_BYPASS = False
  1185. IE_NAME = 'youtube'
  1186. _TESTS = [
  1187. {
  1188. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  1189. 'info_dict': {
  1190. 'id': 'BaW_jenozKc',
  1191. 'ext': 'mp4',
  1192. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  1193. 'channel': 'Philipp Hagemeister',
  1194. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  1195. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  1196. 'upload_date': '20121002',
  1197. 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
  1198. 'categories': ['Science & Technology'],
  1199. 'tags': ['youtube-dl'],
  1200. 'duration': 10,
  1201. 'view_count': int,
  1202. 'like_count': int,
  1203. 'availability': 'public',
  1204. 'playable_in_embed': True,
  1205. 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
  1206. 'live_status': 'not_live',
  1207. 'age_limit': 0,
  1208. 'start_time': 1,
  1209. 'end_time': 9,
  1210. 'comment_count': int,
  1211. 'channel_follower_count': int,
  1212. 'uploader': 'Philipp Hagemeister',
  1213. 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
  1214. 'uploader_id': '@PhilippHagemeister',
  1215. 'heatmap': 'count:100',
  1216. 'timestamp': 1349198244,
  1217. },
  1218. },
  1219. {
  1220. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  1221. 'note': 'Embed-only video (#1746)',
  1222. 'info_dict': {
  1223. 'id': 'yZIXLfi8CZQ',
  1224. 'ext': 'mp4',
  1225. 'upload_date': '20120608',
  1226. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  1227. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  1228. 'age_limit': 18,
  1229. },
  1230. 'skip': 'Private video',
  1231. },
  1232. {
  1233. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
  1234. 'note': 'Use the first video ID in the URL',
  1235. 'info_dict': {
  1236. 'id': 'BaW_jenozKc',
  1237. 'ext': 'mp4',
  1238. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  1239. 'channel': 'Philipp Hagemeister',
  1240. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  1241. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  1242. 'upload_date': '20121002',
  1243. 'description': 'md5:8fb536f4877b8a7455c2ec23794dbc22',
  1244. 'categories': ['Science & Technology'],
  1245. 'tags': ['youtube-dl'],
  1246. 'duration': 10,
  1247. 'view_count': int,
  1248. 'like_count': int,
  1249. 'availability': 'public',
  1250. 'playable_in_embed': True,
  1251. 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
  1252. 'live_status': 'not_live',
  1253. 'age_limit': 0,
  1254. 'comment_count': int,
  1255. 'channel_follower_count': int,
  1256. 'uploader': 'Philipp Hagemeister',
  1257. 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
  1258. 'uploader_id': '@PhilippHagemeister',
  1259. 'heatmap': 'count:100',
  1260. 'timestamp': 1349198244,
  1261. },
  1262. 'params': {
  1263. 'skip_download': True,
  1264. },
  1265. },
  1266. {
  1267. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  1268. 'note': '256k DASH audio (format 141) via DASH manifest',
  1269. 'info_dict': {
  1270. 'id': 'a9LDPn-MO4I',
  1271. 'ext': 'm4a',
  1272. 'upload_date': '20121002',
  1273. 'description': '',
  1274. 'title': 'UHDTV TEST 8K VIDEO.mp4',
  1275. },
  1276. 'params': {
  1277. 'youtube_include_dash_manifest': True,
  1278. 'format': '141',
  1279. },
  1280. 'skip': 'format 141 not served anymore',
  1281. },
  1282. # DASH manifest with encrypted signature
  1283. {
  1284. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  1285. 'info_dict': {
  1286. 'id': 'IB3lcPjvWLA',
  1287. 'ext': 'm4a',
  1288. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  1289. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  1290. 'duration': 244,
  1291. 'upload_date': '20131011',
  1292. 'abr': 129.495,
  1293. 'like_count': int,
  1294. 'channel_id': 'UChuZAo1RKL85gev3Eal9_zg',
  1295. 'playable_in_embed': True,
  1296. 'channel_url': 'https://www.youtube.com/channel/UChuZAo1RKL85gev3Eal9_zg',
  1297. 'view_count': int,
  1298. 'track': 'The Spark',
  1299. 'live_status': 'not_live',
  1300. 'thumbnail': 'https://i.ytimg.com/vi_webp/IB3lcPjvWLA/maxresdefault.webp',
  1301. 'channel': 'Afrojack',
  1302. 'tags': 'count:19',
  1303. 'availability': 'public',
  1304. 'categories': ['Music'],
  1305. 'age_limit': 0,
  1306. 'alt_title': 'The Spark',
  1307. 'channel_follower_count': int,
  1308. 'uploader': 'Afrojack',
  1309. 'uploader_url': 'https://www.youtube.com/@Afrojack',
  1310. 'uploader_id': '@Afrojack',
  1311. },
  1312. 'params': {
  1313. 'youtube_include_dash_manifest': True,
  1314. 'format': '141/bestaudio[ext=m4a]',
  1315. },
  1316. },
  1317. # Age-gate videos. See https://github.com/yt-dlp/yt-dlp/pull/575#issuecomment-888837000
  1318. {
  1319. 'note': 'Embed allowed age-gate video',
  1320. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  1321. 'info_dict': {
  1322. 'id': 'HtVdAasjOgU',
  1323. 'ext': 'mp4',
  1324. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  1325. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  1326. 'duration': 142,
  1327. 'upload_date': '20140605',
  1328. 'age_limit': 18,
  1329. 'categories': ['Gaming'],
  1330. 'thumbnail': 'https://i.ytimg.com/vi_webp/HtVdAasjOgU/maxresdefault.webp',
  1331. 'availability': 'needs_auth',
  1332. 'channel_url': 'https://www.youtube.com/channel/UCzybXLxv08IApdjdN0mJhEg',
  1333. 'like_count': int,
  1334. 'channel': 'The Witcher',
  1335. 'live_status': 'not_live',
  1336. 'tags': 'count:17',
  1337. 'channel_id': 'UCzybXLxv08IApdjdN0mJhEg',
  1338. 'playable_in_embed': True,
  1339. 'view_count': int,
  1340. 'channel_follower_count': int,
  1341. 'uploader': 'The Witcher',
  1342. 'uploader_url': 'https://www.youtube.com/@thewitcher',
  1343. 'uploader_id': '@thewitcher',
  1344. 'comment_count': int,
  1345. 'channel_is_verified': True,
  1346. 'heatmap': 'count:100',
  1347. 'timestamp': 1401991663,
  1348. },
  1349. },
  1350. {
  1351. 'note': 'Age-gate video with embed allowed in public site',
  1352. 'url': 'https://youtube.com/watch?v=HsUATh_Nc2U',
  1353. 'info_dict': {
  1354. 'id': 'HsUATh_Nc2U',
  1355. 'ext': 'mp4',
  1356. 'title': 'Godzilla 2 (Official Video)',
  1357. 'description': 'md5:bf77e03fcae5529475e500129b05668a',
  1358. 'upload_date': '20200408',
  1359. 'age_limit': 18,
  1360. 'availability': 'needs_auth',
  1361. 'channel_id': 'UCYQT13AtrJC0gsM1far_zJg',
  1362. 'channel': 'FlyingKitty',
  1363. 'channel_url': 'https://www.youtube.com/channel/UCYQT13AtrJC0gsM1far_zJg',
  1364. 'view_count': int,
  1365. 'categories': ['Entertainment'],
  1366. 'live_status': 'not_live',
  1367. 'tags': ['Flyingkitty', 'godzilla 2'],
  1368. 'thumbnail': 'https://i.ytimg.com/vi/HsUATh_Nc2U/maxresdefault.jpg',
  1369. 'like_count': int,
  1370. 'duration': 177,
  1371. 'playable_in_embed': True,
  1372. 'channel_follower_count': int,
  1373. 'uploader': 'FlyingKitty',
  1374. 'uploader_url': 'https://www.youtube.com/@FlyingKitty900',
  1375. 'uploader_id': '@FlyingKitty900',
  1376. 'comment_count': int,
  1377. 'channel_is_verified': True,
  1378. },
  1379. },
  1380. {
  1381. 'note': 'Age-gate video embedable only with clientScreen=EMBED',
  1382. 'url': 'https://youtube.com/watch?v=Tq92D6wQ1mg',
  1383. 'info_dict': {
  1384. 'id': 'Tq92D6wQ1mg',
  1385. 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
  1386. 'ext': 'mp4',
  1387. 'upload_date': '20191228',
  1388. 'description': 'md5:17eccca93a786d51bc67646756894066',
  1389. 'age_limit': 18,
  1390. 'like_count': int,
  1391. 'availability': 'needs_auth',
  1392. 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
  1393. 'view_count': int,
  1394. 'thumbnail': 'https://i.ytimg.com/vi_webp/Tq92D6wQ1mg/sddefault.webp',
  1395. 'channel': 'Projekt Melody',
  1396. 'live_status': 'not_live',
  1397. 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
  1398. 'playable_in_embed': True,
  1399. 'categories': ['Entertainment'],
  1400. 'duration': 106,
  1401. 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
  1402. 'comment_count': int,
  1403. 'channel_follower_count': int,
  1404. 'uploader': 'Projekt Melody',
  1405. 'uploader_url': 'https://www.youtube.com/@ProjektMelody',
  1406. 'uploader_id': '@ProjektMelody',
  1407. 'timestamp': 1577508724,
  1408. },
  1409. },
  1410. {
  1411. 'note': 'Non-Agegated non-embeddable video',
  1412. 'url': 'https://youtube.com/watch?v=MeJVWBSsPAY',
  1413. 'info_dict': {
  1414. 'id': 'MeJVWBSsPAY',
  1415. 'ext': 'mp4',
  1416. 'title': 'OOMPH! - Such Mich Find Mich (Lyrics)',
  1417. 'description': 'Fan Video. Music & Lyrics by OOMPH!.',
  1418. 'upload_date': '20130730',
  1419. 'track': 'Such mich find mich',
  1420. 'age_limit': 0,
  1421. 'tags': ['oomph', 'such mich find mich', 'lyrics', 'german industrial', 'musica industrial'],
  1422. 'like_count': int,
  1423. 'playable_in_embed': False,
  1424. 'creator': 'OOMPH!',
  1425. 'thumbnail': 'https://i.ytimg.com/vi/MeJVWBSsPAY/sddefault.jpg',
  1426. 'view_count': int,
  1427. 'alt_title': 'Such mich find mich',
  1428. 'duration': 210,
  1429. 'channel': 'Herr Lurik',
  1430. 'channel_id': 'UCdR3RSDPqub28LjZx0v9-aA',
  1431. 'categories': ['Music'],
  1432. 'availability': 'public',
  1433. 'channel_url': 'https://www.youtube.com/channel/UCdR3RSDPqub28LjZx0v9-aA',
  1434. 'live_status': 'not_live',
  1435. 'artist': 'OOMPH!',
  1436. 'channel_follower_count': int,
  1437. 'uploader': 'Herr Lurik',
  1438. 'uploader_url': 'https://www.youtube.com/@HerrLurik',
  1439. 'uploader_id': '@HerrLurik',
  1440. },
  1441. },
  1442. {
  1443. 'note': 'Non-bypassable age-gated video',
  1444. 'url': 'https://youtube.com/watch?v=Cr381pDsSsA',
  1445. 'only_matching': True,
  1446. },
  1447. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  1448. # YouTube Red ad is not captured for creator
  1449. {
  1450. 'url': '__2ABJjxzNo',
  1451. 'info_dict': {
  1452. 'id': '__2ABJjxzNo',
  1453. 'ext': 'mp4',
  1454. 'duration': 266,
  1455. 'upload_date': '20100430',
  1456. 'creator': 'deadmau5',
  1457. 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
  1458. 'title': 'Deadmau5 - Some Chords (HD)',
  1459. 'alt_title': 'Some Chords',
  1460. 'availability': 'public',
  1461. 'tags': 'count:14',
  1462. 'channel_id': 'UCYEK6xds6eo-3tr4xRdflmQ',
  1463. 'view_count': int,
  1464. 'live_status': 'not_live',
  1465. 'channel': 'deadmau5',
  1466. 'thumbnail': 'https://i.ytimg.com/vi_webp/__2ABJjxzNo/maxresdefault.webp',
  1467. 'like_count': int,
  1468. 'track': 'Some Chords',
  1469. 'artist': 'deadmau5',
  1470. 'playable_in_embed': True,
  1471. 'age_limit': 0,
  1472. 'channel_url': 'https://www.youtube.com/channel/UCYEK6xds6eo-3tr4xRdflmQ',
  1473. 'categories': ['Music'],
  1474. 'album': 'Some Chords',
  1475. 'channel_follower_count': int,
  1476. 'uploader': 'deadmau5',
  1477. 'uploader_url': 'https://www.youtube.com/@deadmau5',
  1478. 'uploader_id': '@deadmau5',
  1479. },
  1480. 'expected_warnings': [
  1481. 'DASH manifest missing',
  1482. ],
  1483. },
  1484. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  1485. {
  1486. 'url': 'lqQg6PlCWgI',
  1487. 'info_dict': {
  1488. 'id': 'lqQg6PlCWgI',
  1489. 'ext': 'mp4',
  1490. 'duration': 6085,
  1491. 'upload_date': '20150827',
  1492. 'description': 'md5:04bbbf3ccceb6795947572ca36f45904',
  1493. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  1494. 'like_count': int,
  1495. 'release_timestamp': 1343767800,
  1496. 'playable_in_embed': True,
  1497. 'categories': ['Sports'],
  1498. 'release_date': '20120731',
  1499. 'channel': 'Olympics',
  1500. 'tags': ['Hockey', '2012-07-31', '31 July 2012', 'Riverbank Arena', 'Session', 'Olympics', 'Olympic Games', 'London 2012', '2012 Summer Olympics', 'Summer Games'],
  1501. 'channel_id': 'UCTl3QQTvqHFjurroKxexy2Q',
  1502. 'thumbnail': 'https://i.ytimg.com/vi/lqQg6PlCWgI/maxresdefault.jpg',
  1503. 'age_limit': 0,
  1504. 'availability': 'public',
  1505. 'live_status': 'was_live',
  1506. 'view_count': int,
  1507. 'channel_url': 'https://www.youtube.com/channel/UCTl3QQTvqHFjurroKxexy2Q',
  1508. 'channel_follower_count': int,
  1509. 'uploader': 'Olympics',
  1510. 'uploader_url': 'https://www.youtube.com/@Olympics',
  1511. 'uploader_id': '@Olympics',
  1512. 'channel_is_verified': True,
  1513. 'timestamp': 1440707674,
  1514. },
  1515. 'params': {
  1516. 'skip_download': 'requires avconv',
  1517. },
  1518. },
  1519. # Non-square pixels
  1520. {
  1521. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  1522. 'info_dict': {
  1523. 'id': '_b-2C3KPAM0',
  1524. 'ext': 'mp4',
  1525. 'stretched_ratio': 16 / 9.,
  1526. 'duration': 85,
  1527. 'upload_date': '20110310',
  1528. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  1529. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  1530. 'playable_in_embed': True,
  1531. 'channel': '孫ᄋᄅ',
  1532. 'age_limit': 0,
  1533. 'tags': 'count:11',
  1534. 'channel_url': 'https://www.youtube.com/channel/UCS-xxCmRaA6BFdmgDPA_BIw',
  1535. 'channel_id': 'UCS-xxCmRaA6BFdmgDPA_BIw',
  1536. 'thumbnail': 'https://i.ytimg.com/vi/_b-2C3KPAM0/maxresdefault.jpg',
  1537. 'view_count': int,
  1538. 'categories': ['People & Blogs'],
  1539. 'like_count': int,
  1540. 'live_status': 'not_live',
  1541. 'availability': 'unlisted',
  1542. 'comment_count': int,
  1543. 'channel_follower_count': int,
  1544. 'uploader': '孫ᄋᄅ',
  1545. 'uploader_url': 'https://www.youtube.com/@AllenMeow',
  1546. 'uploader_id': '@AllenMeow',
  1547. 'timestamp': 1299776999,
  1548. },
  1549. },
  1550. # url_encoded_fmt_stream_map is empty string
  1551. {
  1552. 'url': 'qEJwOuvDf7I',
  1553. 'info_dict': {
  1554. 'id': 'qEJwOuvDf7I',
  1555. 'ext': 'webm',
  1556. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  1557. 'description': '',
  1558. 'upload_date': '20150404',
  1559. },
  1560. 'params': {
  1561. 'skip_download': 'requires avconv',
  1562. },
  1563. 'skip': 'This live event has ended.',
  1564. },
  1565. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  1566. {
  1567. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  1568. 'info_dict': {
  1569. 'id': 'FIl7x6_3R5Y',
  1570. 'ext': 'webm',
  1571. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  1572. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  1573. 'duration': 220,
  1574. 'upload_date': '20150625',
  1575. 'formats': 'mincount:31',
  1576. },
  1577. 'skip': 'not actual anymore',
  1578. },
  1579. # DASH manifest with segment_list
  1580. {
  1581. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  1582. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  1583. 'info_dict': {
  1584. 'id': 'CsmdDsKjzN8',
  1585. 'ext': 'mp4',
  1586. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  1587. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  1588. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  1589. },
  1590. 'params': {
  1591. 'youtube_include_dash_manifest': True,
  1592. 'format': '135', # bestvideo
  1593. },
  1594. 'skip': 'This live event has ended.',
  1595. },
  1596. {
  1597. # Multifeed videos (multiple cameras), URL can be of any Camera
  1598. # TODO: fix multifeed titles
  1599. 'url': 'https://www.youtube.com/watch?v=zaPI8MvL8pg',
  1600. 'info_dict': {
  1601. 'id': 'zaPI8MvL8pg',
  1602. 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04',
  1603. 'description': 'md5:563ccbc698b39298481ca3c571169519',
  1604. },
  1605. 'playlist': [{
  1606. 'info_dict': {
  1607. 'id': 'j5yGuxZ8lLU',
  1608. 'ext': 'mp4',
  1609. 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Chris)',
  1610. 'description': 'md5:563ccbc698b39298481ca3c571169519',
  1611. 'duration': 10120,
  1612. 'channel_follower_count': int,
  1613. 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
  1614. 'availability': 'public',
  1615. 'playable_in_embed': True,
  1616. 'upload_date': '20131105',
  1617. 'categories': ['Gaming'],
  1618. 'live_status': 'was_live',
  1619. 'tags': 'count:24',
  1620. 'release_timestamp': 1383701910,
  1621. 'thumbnail': 'https://i.ytimg.com/vi/j5yGuxZ8lLU/maxresdefault.jpg',
  1622. 'comment_count': int,
  1623. 'age_limit': 0,
  1624. 'like_count': int,
  1625. 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
  1626. 'channel': 'WiiLikeToPlay',
  1627. 'view_count': int,
  1628. 'release_date': '20131106',
  1629. 'uploader': 'WiiLikeToPlay',
  1630. 'uploader_id': '@WLTP',
  1631. 'uploader_url': 'https://www.youtube.com/@WLTP',
  1632. },
  1633. }, {
  1634. 'info_dict': {
  1635. 'id': 'zaPI8MvL8pg',
  1636. 'ext': 'mp4',
  1637. 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Tyson)',
  1638. 'availability': 'public',
  1639. 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
  1640. 'channel': 'WiiLikeToPlay',
  1641. 'channel_follower_count': int,
  1642. 'description': 'md5:563ccbc698b39298481ca3c571169519',
  1643. 'duration': 10108,
  1644. 'age_limit': 0,
  1645. 'like_count': int,
  1646. 'tags': 'count:24',
  1647. 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
  1648. 'release_timestamp': 1383701915,
  1649. 'comment_count': int,
  1650. 'upload_date': '20131105',
  1651. 'thumbnail': 'https://i.ytimg.com/vi/zaPI8MvL8pg/maxresdefault.jpg',
  1652. 'release_date': '20131106',
  1653. 'playable_in_embed': True,
  1654. 'live_status': 'was_live',
  1655. 'categories': ['Gaming'],
  1656. 'view_count': int,
  1657. 'uploader': 'WiiLikeToPlay',
  1658. 'uploader_id': '@WLTP',
  1659. 'uploader_url': 'https://www.youtube.com/@WLTP',
  1660. },
  1661. }, {
  1662. 'info_dict': {
  1663. 'id': 'R7r3vfO7Hao',
  1664. 'ext': 'mp4',
  1665. 'title': 'Terraria 1.2 Live Stream | Let\'s Play - Part 04 (Spencer)',
  1666. 'thumbnail': 'https://i.ytimg.com/vi/R7r3vfO7Hao/maxresdefault.jpg',
  1667. 'channel_id': 'UCN2XePorRokPB9TEgRZpddg',
  1668. 'like_count': int,
  1669. 'availability': 'public',
  1670. 'playable_in_embed': True,
  1671. 'upload_date': '20131105',
  1672. 'description': 'md5:563ccbc698b39298481ca3c571169519',
  1673. 'channel_follower_count': int,
  1674. 'tags': 'count:24',
  1675. 'release_date': '20131106',
  1676. 'comment_count': int,
  1677. 'channel_url': 'https://www.youtube.com/channel/UCN2XePorRokPB9TEgRZpddg',
  1678. 'channel': 'WiiLikeToPlay',
  1679. 'categories': ['Gaming'],
  1680. 'release_timestamp': 1383701914,
  1681. 'live_status': 'was_live',
  1682. 'age_limit': 0,
  1683. 'duration': 10128,
  1684. 'view_count': int,
  1685. 'uploader': 'WiiLikeToPlay',
  1686. 'uploader_id': '@WLTP',
  1687. 'uploader_url': 'https://www.youtube.com/@WLTP',
  1688. },
  1689. }],
  1690. 'params': {'skip_download': True},
  1691. 'skip': 'Not multifeed anymore',
  1692. },
  1693. {
  1694. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  1695. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  1696. 'info_dict': {
  1697. 'id': 'gVfLd0zydlo',
  1698. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  1699. },
  1700. 'playlist_count': 2,
  1701. 'skip': 'Not multifeed anymore',
  1702. },
  1703. {
  1704. 'url': 'https://vid.plus/FlRa-iH7PGw',
  1705. 'only_matching': True,
  1706. },
  1707. {
  1708. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  1709. 'only_matching': True,
  1710. },
  1711. {
  1712. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  1713. # Also tests cut-off URL expansion in video description (see
  1714. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  1715. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  1716. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  1717. 'info_dict': {
  1718. 'id': 'lsguqyKfVQg',
  1719. 'ext': 'mp4',
  1720. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  1721. 'alt_title': 'Dark Walk',
  1722. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  1723. 'duration': 133,
  1724. 'upload_date': '20151119',
  1725. 'creator': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
  1726. 'track': 'Dark Walk',
  1727. 'artist': 'Todd Haberman;\nDaniel Law Heath and Aaron Kaplan',
  1728. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  1729. 'thumbnail': 'https://i.ytimg.com/vi_webp/lsguqyKfVQg/maxresdefault.webp',
  1730. 'categories': ['Film & Animation'],
  1731. 'view_count': int,
  1732. 'live_status': 'not_live',
  1733. 'channel_url': 'https://www.youtube.com/channel/UCTSRgz5jylBvFt_S7wnsqLQ',
  1734. 'channel_id': 'UCTSRgz5jylBvFt_S7wnsqLQ',
  1735. 'tags': 'count:13',
  1736. 'availability': 'public',
  1737. 'channel': 'IronSoulElf',
  1738. 'playable_in_embed': True,
  1739. 'like_count': int,
  1740. 'age_limit': 0,
  1741. 'channel_follower_count': int,
  1742. },
  1743. 'params': {
  1744. 'skip_download': True,
  1745. },
  1746. },
  1747. {
  1748. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  1749. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  1750. 'only_matching': True,
  1751. },
  1752. {
  1753. # Video with yt:stretch=17:0
  1754. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  1755. 'info_dict': {
  1756. 'id': 'Q39EVAstoRM',
  1757. 'ext': 'mp4',
  1758. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  1759. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  1760. 'upload_date': '20151107',
  1761. },
  1762. 'params': {
  1763. 'skip_download': True,
  1764. },
  1765. 'skip': 'This video does not exist.',
  1766. },
  1767. {
  1768. # Video with incomplete 'yt:stretch=16:'
  1769. 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
  1770. 'only_matching': True,
  1771. },
  1772. {
  1773. # Video licensed under Creative Commons
  1774. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  1775. 'info_dict': {
  1776. 'id': 'M4gD1WSo5mA',
  1777. 'ext': 'mp4',
  1778. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  1779. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  1780. 'duration': 721,
  1781. 'upload_date': '20150128',
  1782. 'license': 'Creative Commons Attribution license (reuse allowed)',
  1783. 'channel_id': 'UCuLGmD72gJDBwmLw06X58SA',
  1784. 'channel_url': 'https://www.youtube.com/channel/UCuLGmD72gJDBwmLw06X58SA',
  1785. 'like_count': int,
  1786. 'age_limit': 0,
  1787. 'tags': ['Copyright (Legal Subject)', 'Law (Industry)', 'William W. Fisher (Author)'],
  1788. 'channel': 'The Berkman Klein Center for Internet & Society',
  1789. 'availability': 'public',
  1790. 'view_count': int,
  1791. 'categories': ['Education'],
  1792. 'thumbnail': 'https://i.ytimg.com/vi_webp/M4gD1WSo5mA/maxresdefault.webp',
  1793. 'live_status': 'not_live',
  1794. 'playable_in_embed': True,
  1795. 'channel_follower_count': int,
  1796. 'chapters': list,
  1797. 'uploader': 'The Berkman Klein Center for Internet & Society',
  1798. 'uploader_id': '@BKCHarvard',
  1799. 'uploader_url': 'https://www.youtube.com/@BKCHarvard',
  1800. 'timestamp': 1422422076,
  1801. },
  1802. 'params': {
  1803. 'skip_download': True,
  1804. },
  1805. },
  1806. {
  1807. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  1808. 'info_dict': {
  1809. 'id': 'eQcmzGIKrzg',
  1810. 'ext': 'mp4',
  1811. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  1812. 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
  1813. 'duration': 4060,
  1814. 'upload_date': '20151120',
  1815. 'license': 'Creative Commons Attribution license (reuse allowed)',
  1816. 'playable_in_embed': True,
  1817. 'tags': 'count:12',
  1818. 'like_count': int,
  1819. 'channel_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  1820. 'age_limit': 0,
  1821. 'availability': 'public',
  1822. 'categories': ['News & Politics'],
  1823. 'channel': 'Bernie Sanders',
  1824. 'thumbnail': 'https://i.ytimg.com/vi_webp/eQcmzGIKrzg/maxresdefault.webp',
  1825. 'view_count': int,
  1826. 'live_status': 'not_live',
  1827. 'channel_url': 'https://www.youtube.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  1828. 'comment_count': int,
  1829. 'channel_follower_count': int,
  1830. 'chapters': list,
  1831. 'uploader': 'Bernie Sanders',
  1832. 'uploader_url': 'https://www.youtube.com/@BernieSanders',
  1833. 'uploader_id': '@BernieSanders',
  1834. 'channel_is_verified': True,
  1835. 'heatmap': 'count:100',
  1836. 'timestamp': 1447987198,
  1837. },
  1838. 'params': {
  1839. 'skip_download': True,
  1840. },
  1841. },
  1842. {
  1843. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  1844. 'only_matching': True,
  1845. },
  1846. {
  1847. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  1848. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  1849. 'only_matching': True,
  1850. },
  1851. {
  1852. # Rental video preview
  1853. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  1854. 'info_dict': {
  1855. 'id': 'uGpuVWrhIzE',
  1856. 'ext': 'mp4',
  1857. 'title': 'Piku - Trailer',
  1858. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  1859. 'upload_date': '20150811',
  1860. 'license': 'Standard YouTube License',
  1861. },
  1862. 'params': {
  1863. 'skip_download': True,
  1864. },
  1865. 'skip': 'This video is not available.',
  1866. },
  1867. {
  1868. # YouTube Red video with episode data
  1869. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  1870. 'info_dict': {
  1871. 'id': 'iqKdEhx-dD4',
  1872. 'ext': 'mp4',
  1873. 'title': 'Isolation - Mind Field (Ep 1)',
  1874. 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
  1875. 'duration': 2085,
  1876. 'upload_date': '20170118',
  1877. 'series': 'Mind Field',
  1878. 'season_number': 1,
  1879. 'episode_number': 1,
  1880. 'thumbnail': 'https://i.ytimg.com/vi_webp/iqKdEhx-dD4/maxresdefault.webp',
  1881. 'tags': 'count:12',
  1882. 'view_count': int,
  1883. 'availability': 'public',
  1884. 'age_limit': 0,
  1885. 'channel': 'Vsauce',
  1886. 'episode': 'Episode 1',
  1887. 'categories': ['Entertainment'],
  1888. 'season': 'Season 1',
  1889. 'channel_id': 'UC6nSFpj9HTCZ5t-N3Rm3-HA',
  1890. 'channel_url': 'https://www.youtube.com/channel/UC6nSFpj9HTCZ5t-N3Rm3-HA',
  1891. 'like_count': int,
  1892. 'playable_in_embed': True,
  1893. 'live_status': 'not_live',
  1894. 'channel_follower_count': int,
  1895. 'uploader': 'Vsauce',
  1896. 'uploader_url': 'https://www.youtube.com/@Vsauce',
  1897. 'uploader_id': '@Vsauce',
  1898. 'comment_count': int,
  1899. 'channel_is_verified': True,
  1900. 'timestamp': 1484761047,
  1901. },
  1902. 'params': {
  1903. 'skip_download': True,
  1904. },
  1905. 'expected_warnings': [
  1906. 'Skipping DASH manifest',
  1907. ],
  1908. },
  1909. {
  1910. # The following content has been identified by the YouTube community
  1911. # as inappropriate or offensive to some audiences.
  1912. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  1913. 'info_dict': {
  1914. 'id': '6SJNVb0GnPI',
  1915. 'ext': 'mp4',
  1916. 'title': 'Race Differences in Intelligence',
  1917. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1918. 'duration': 965,
  1919. 'upload_date': '20140124',
  1920. },
  1921. 'params': {
  1922. 'skip_download': True,
  1923. },
  1924. 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
  1925. },
  1926. {
  1927. # itag 212
  1928. 'url': '1t24XAntNCY',
  1929. 'only_matching': True,
  1930. },
  1931. {
  1932. # geo restricted to JP
  1933. 'url': 'sJL6WA-aGkQ',
  1934. 'only_matching': True,
  1935. },
  1936. {
  1937. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1938. 'only_matching': True,
  1939. },
  1940. {
  1941. 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
  1942. 'only_matching': True,
  1943. },
  1944. {
  1945. # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
  1946. 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
  1947. 'only_matching': True,
  1948. },
  1949. {
  1950. # DRM protected
  1951. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1952. 'only_matching': True,
  1953. },
  1954. {
  1955. # Video with unsupported adaptive stream type formats
  1956. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1957. 'info_dict': {
  1958. 'id': 'Z4Vy8R84T1U',
  1959. 'ext': 'mp4',
  1960. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1961. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1962. 'duration': 433,
  1963. 'upload_date': '20130923',
  1964. 'formats': 'maxcount:10',
  1965. },
  1966. 'params': {
  1967. 'skip_download': True,
  1968. 'youtube_include_dash_manifest': False,
  1969. },
  1970. 'skip': 'not actual anymore',
  1971. },
  1972. {
  1973. # Youtube Music Auto-generated description
  1974. # TODO: fix metadata extraction
  1975. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1976. 'info_dict': {
  1977. 'id': 'MgNrAu2pzNs',
  1978. 'ext': 'mp4',
  1979. 'title': 'Voyeur Girl',
  1980. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1981. 'upload_date': '20190312',
  1982. 'artists': ['Stephen'],
  1983. 'creators': ['Stephen'],
  1984. 'track': 'Voyeur Girl',
  1985. 'album': 'it\'s too much love to know my dear',
  1986. 'release_date': '20190313',
  1987. 'alt_title': 'Voyeur Girl',
  1988. 'view_count': int,
  1989. 'playable_in_embed': True,
  1990. 'like_count': int,
  1991. 'categories': ['Music'],
  1992. 'channel_url': 'https://www.youtube.com/channel/UC-pWHpBjdGG69N9mM2auIAA',
  1993. 'channel': 'Stephen', # TODO: should be "Stephen - Topic"
  1994. 'uploader': 'Stephen',
  1995. 'availability': 'public',
  1996. 'duration': 169,
  1997. 'thumbnail': 'https://i.ytimg.com/vi_webp/MgNrAu2pzNs/maxresdefault.webp',
  1998. 'age_limit': 0,
  1999. 'channel_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  2000. 'tags': 'count:11',
  2001. 'live_status': 'not_live',
  2002. 'channel_follower_count': int,
  2003. },
  2004. 'params': {
  2005. 'skip_download': True,
  2006. },
  2007. },
  2008. {
  2009. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  2010. 'only_matching': True,
  2011. },
  2012. {
  2013. # invalid -> valid video id redirection
  2014. 'url': 'DJztXj2GPfl',
  2015. 'info_dict': {
  2016. 'id': 'DJztXj2GPfk',
  2017. 'ext': 'mp4',
  2018. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  2019. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  2020. 'upload_date': '20090125',
  2021. 'artist': 'Panjabi MC',
  2022. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  2023. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  2024. },
  2025. 'params': {
  2026. 'skip_download': True,
  2027. },
  2028. 'skip': 'Video unavailable',
  2029. },
  2030. {
  2031. # empty description results in an empty string
  2032. 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
  2033. 'info_dict': {
  2034. 'id': 'x41yOUIvK2k',
  2035. 'ext': 'mp4',
  2036. 'title': 'IMG 3456',
  2037. 'description': '',
  2038. 'upload_date': '20170613',
  2039. 'view_count': int,
  2040. 'thumbnail': 'https://i.ytimg.com/vi_webp/x41yOUIvK2k/maxresdefault.webp',
  2041. 'like_count': int,
  2042. 'channel_id': 'UCo03ZQPBW5U4UC3regpt1nw',
  2043. 'tags': [],
  2044. 'channel_url': 'https://www.youtube.com/channel/UCo03ZQPBW5U4UC3regpt1nw',
  2045. 'availability': 'public',
  2046. 'age_limit': 0,
  2047. 'categories': ['Pets & Animals'],
  2048. 'duration': 7,
  2049. 'playable_in_embed': True,
  2050. 'live_status': 'not_live',
  2051. 'channel': 'l\'Or Vert asbl',
  2052. 'channel_follower_count': int,
  2053. 'uploader': 'l\'Or Vert asbl',
  2054. 'uploader_url': 'https://www.youtube.com/@ElevageOrVert',
  2055. 'uploader_id': '@ElevageOrVert',
  2056. 'timestamp': 1497343210,
  2057. },
  2058. 'params': {
  2059. 'skip_download': True,
  2060. },
  2061. },
  2062. {
  2063. # with '};' inside yt initial data (see [1])
  2064. # see [2] for an example with '};' inside ytInitialPlayerResponse
  2065. # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
  2066. # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
  2067. 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
  2068. 'info_dict': {
  2069. 'id': 'CHqg6qOn4no',
  2070. 'ext': 'mp4',
  2071. 'title': 'Part 77 Sort a list of simple types in c#',
  2072. 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
  2073. 'upload_date': '20130831',
  2074. 'channel_id': 'UCCTVrRB5KpIiK6V2GGVsR1Q',
  2075. 'like_count': int,
  2076. 'channel_url': 'https://www.youtube.com/channel/UCCTVrRB5KpIiK6V2GGVsR1Q',
  2077. 'live_status': 'not_live',
  2078. 'categories': ['Education'],
  2079. 'availability': 'public',
  2080. 'thumbnail': 'https://i.ytimg.com/vi/CHqg6qOn4no/sddefault.jpg',
  2081. 'tags': 'count:12',
  2082. 'playable_in_embed': True,
  2083. 'age_limit': 0,
  2084. 'view_count': int,
  2085. 'duration': 522,
  2086. 'channel': 'kudvenkat',
  2087. 'comment_count': int,
  2088. 'channel_follower_count': int,
  2089. 'chapters': list,
  2090. 'uploader': 'kudvenkat',
  2091. 'uploader_url': 'https://www.youtube.com/@Csharp-video-tutorialsBlogspot',
  2092. 'uploader_id': '@Csharp-video-tutorialsBlogspot',
  2093. 'channel_is_verified': True,
  2094. 'heatmap': 'count:100',
  2095. 'timestamp': 1377976349,
  2096. },
  2097. 'params': {
  2098. 'skip_download': True,
  2099. },
  2100. },
  2101. {
  2102. # another example of '};' in ytInitialData
  2103. 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
  2104. 'only_matching': True,
  2105. },
  2106. {
  2107. 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
  2108. 'only_matching': True,
  2109. },
  2110. {
  2111. # https://github.com/ytdl-org/youtube-dl/pull/28094
  2112. 'url': 'OtqTfy26tG0',
  2113. 'info_dict': {
  2114. 'id': 'OtqTfy26tG0',
  2115. 'ext': 'mp4',
  2116. 'title': 'Burn Out',
  2117. 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
  2118. 'upload_date': '20141120',
  2119. 'artist': 'The Cinematic Orchestra',
  2120. 'track': 'Burn Out',
  2121. 'album': 'Every Day',
  2122. 'like_count': int,
  2123. 'live_status': 'not_live',
  2124. 'alt_title': 'Burn Out',
  2125. 'duration': 614,
  2126. 'age_limit': 0,
  2127. 'view_count': int,
  2128. 'channel_url': 'https://www.youtube.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
  2129. 'creator': 'The Cinematic Orchestra',
  2130. 'channel': 'The Cinematic Orchestra',
  2131. 'tags': ['The Cinematic Orchestra', 'Every Day', 'Burn Out'],
  2132. 'channel_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
  2133. 'availability': 'public',
  2134. 'thumbnail': 'https://i.ytimg.com/vi/OtqTfy26tG0/maxresdefault.jpg',
  2135. 'categories': ['Music'],
  2136. 'playable_in_embed': True,
  2137. 'channel_follower_count': int,
  2138. 'uploader': 'The Cinematic Orchestra',
  2139. 'comment_count': int,
  2140. },
  2141. 'params': {
  2142. 'skip_download': True,
  2143. },
  2144. },
  2145. {
  2146. # controversial video, only works with bpctr when authenticated with cookies
  2147. 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
  2148. 'only_matching': True,
  2149. },
  2150. {
  2151. # controversial video, requires bpctr/contentCheckOk
  2152. 'url': 'https://www.youtube.com/watch?v=SZJvDhaSDnc',
  2153. 'info_dict': {
  2154. 'id': 'SZJvDhaSDnc',
  2155. 'ext': 'mp4',
  2156. 'title': 'San Diego teen commits suicide after bullying over embarrassing video',
  2157. 'channel_id': 'UC-SJ6nODDmufqBzPBwCvYvQ',
  2158. 'upload_date': '20140716',
  2159. 'description': 'md5:acde3a73d3f133fc97e837a9f76b53b7',
  2160. 'duration': 170,
  2161. 'categories': ['News & Politics'],
  2162. 'view_count': int,
  2163. 'channel': 'CBS Mornings',
  2164. 'tags': ['suicide', 'bullying', 'video', 'cbs', 'news'],
  2165. 'thumbnail': 'https://i.ytimg.com/vi/SZJvDhaSDnc/hqdefault.jpg',
  2166. 'age_limit': 18,
  2167. 'availability': 'needs_auth',
  2168. 'channel_url': 'https://www.youtube.com/channel/UC-SJ6nODDmufqBzPBwCvYvQ',
  2169. 'like_count': int,
  2170. 'live_status': 'not_live',
  2171. 'playable_in_embed': True,
  2172. 'channel_follower_count': int,
  2173. 'uploader': 'CBS Mornings',
  2174. 'uploader_url': 'https://www.youtube.com/@CBSMornings',
  2175. 'uploader_id': '@CBSMornings',
  2176. 'comment_count': int,
  2177. 'channel_is_verified': True,
  2178. 'timestamp': 1405513526,
  2179. },
  2180. },
  2181. {
  2182. # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
  2183. 'url': 'cBvYw8_A0vQ',
  2184. 'info_dict': {
  2185. 'id': 'cBvYw8_A0vQ',
  2186. 'ext': 'mp4',
  2187. 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
  2188. 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
  2189. 'upload_date': '20201120',
  2190. 'duration': 1456,
  2191. 'categories': ['Travel & Events'],
  2192. 'channel_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
  2193. 'view_count': int,
  2194. 'channel': 'Walk around Japan',
  2195. 'tags': ['Ueno Tokyo', 'Okachimachi Tokyo', 'Ameyoko Street', 'Tokyo attraction', 'Travel in Tokyo'],
  2196. 'thumbnail': 'https://i.ytimg.com/vi/cBvYw8_A0vQ/hqdefault.jpg',
  2197. 'age_limit': 0,
  2198. 'availability': 'public',
  2199. 'channel_url': 'https://www.youtube.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
  2200. 'live_status': 'not_live',
  2201. 'playable_in_embed': True,
  2202. 'channel_follower_count': int,
  2203. 'uploader': 'Walk around Japan',
  2204. 'uploader_url': 'https://www.youtube.com/@walkaroundjapan7124',
  2205. 'uploader_id': '@walkaroundjapan7124',
  2206. 'timestamp': 1605884416,
  2207. },
  2208. 'params': {
  2209. 'skip_download': True,
  2210. },
  2211. }, {
  2212. # Has multiple audio streams
  2213. 'url': 'WaOKSUlf4TM',
  2214. 'only_matching': True,
  2215. }, {
  2216. # Requires Premium: has format 141 when requested using YTM url
  2217. 'url': 'https://music.youtube.com/watch?v=XclachpHxis',
  2218. 'only_matching': True,
  2219. }, {
  2220. # multiple subtitles with same lang_code
  2221. 'url': 'https://www.youtube.com/watch?v=wsQiKKfKxug',
  2222. 'only_matching': True,
  2223. }, {
  2224. # Force use android client fallback
  2225. 'url': 'https://www.youtube.com/watch?v=YOelRv7fMxY',
  2226. 'info_dict': {
  2227. 'id': 'YOelRv7fMxY',
  2228. 'title': 'DIGGING A SECRET TUNNEL Part 1',
  2229. 'ext': '3gp',
  2230. 'upload_date': '20210624',
  2231. 'channel_id': 'UCp68_FLety0O-n9QU6phsgw',
  2232. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCp68_FLety0O-n9QU6phsgw',
  2233. 'description': 'md5:5d5991195d599b56cd0c4148907eec50',
  2234. 'duration': 596,
  2235. 'categories': ['Entertainment'],
  2236. 'view_count': int,
  2237. 'channel': 'colinfurze',
  2238. 'tags': ['Colin', 'furze', 'Terry', 'tunnel', 'underground', 'bunker'],
  2239. 'thumbnail': 'https://i.ytimg.com/vi/YOelRv7fMxY/maxresdefault.jpg',
  2240. 'age_limit': 0,
  2241. 'availability': 'public',
  2242. 'like_count': int,
  2243. 'live_status': 'not_live',
  2244. 'playable_in_embed': True,
  2245. 'channel_follower_count': int,
  2246. 'chapters': list,
  2247. 'uploader': 'colinfurze',
  2248. 'uploader_url': 'https://www.youtube.com/@colinfurze',
  2249. 'uploader_id': '@colinfurze',
  2250. 'comment_count': int,
  2251. 'channel_is_verified': True,
  2252. 'heatmap': 'count:100',
  2253. },
  2254. 'params': {
  2255. 'format': '17', # 3gp format available on android
  2256. 'extractor_args': {'youtube': {'player_client': ['android']}},
  2257. },
  2258. 'skip': 'android client broken',
  2259. },
  2260. {
  2261. # Skip download of additional client configs (remix client config in this case)
  2262. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  2263. 'only_matching': True,
  2264. 'params': {
  2265. 'extractor_args': {'youtube': {'player_skip': ['configs']}},
  2266. },
  2267. }, {
  2268. # shorts
  2269. 'url': 'https://www.youtube.com/shorts/BGQWPY4IigY',
  2270. 'only_matching': True,
  2271. }, {
  2272. 'note': 'Storyboards',
  2273. 'url': 'https://www.youtube.com/watch?v=5KLPxDtMqe8',
  2274. 'info_dict': {
  2275. 'id': '5KLPxDtMqe8',
  2276. 'ext': 'mhtml',
  2277. 'format_id': 'sb0',
  2278. 'title': 'Your Brain is Plastic',
  2279. 'description': 'md5:89cd86034bdb5466cd87c6ba206cd2bc',
  2280. 'upload_date': '20140324',
  2281. 'like_count': int,
  2282. 'channel_id': 'UCZYTClx2T1of7BRZ86-8fow',
  2283. 'channel_url': 'https://www.youtube.com/channel/UCZYTClx2T1of7BRZ86-8fow',
  2284. 'view_count': int,
  2285. 'thumbnail': 'https://i.ytimg.com/vi/5KLPxDtMqe8/maxresdefault.jpg',
  2286. 'playable_in_embed': True,
  2287. 'tags': 'count:12',
  2288. 'availability': 'public',
  2289. 'channel': 'SciShow',
  2290. 'live_status': 'not_live',
  2291. 'duration': 248,
  2292. 'categories': ['Education'],
  2293. 'age_limit': 0,
  2294. 'channel_follower_count': int,
  2295. 'chapters': list,
  2296. 'uploader': 'SciShow',
  2297. 'uploader_url': 'https://www.youtube.com/@SciShow',
  2298. 'uploader_id': '@SciShow',
  2299. 'comment_count': int,
  2300. 'channel_is_verified': True,
  2301. 'heatmap': 'count:100',
  2302. 'timestamp': 1395685455,
  2303. }, 'params': {'format': 'mhtml', 'skip_download': True},
  2304. }, {
  2305. # Ensure video upload_date is in UTC timezone (video was uploaded 1641170939)
  2306. 'url': 'https://www.youtube.com/watch?v=2NUZ8W2llS4',
  2307. 'info_dict': {
  2308. 'id': '2NUZ8W2llS4',
  2309. 'ext': 'mp4',
  2310. 'title': 'The NP that test your phone performance 🙂',
  2311. 'description': 'md5:144494b24d4f9dfacb97c1bbef5de84d',
  2312. 'channel_id': 'UCRqNBSOHgilHfAczlUmlWHA',
  2313. 'channel_url': 'https://www.youtube.com/channel/UCRqNBSOHgilHfAczlUmlWHA',
  2314. 'duration': 21,
  2315. 'view_count': int,
  2316. 'age_limit': 0,
  2317. 'categories': ['Gaming'],
  2318. 'tags': 'count:23',
  2319. 'playable_in_embed': True,
  2320. 'live_status': 'not_live',
  2321. 'upload_date': '20220103',
  2322. 'like_count': int,
  2323. 'availability': 'public',
  2324. 'channel': 'Leon Nguyen',
  2325. 'thumbnail': 'https://i.ytimg.com/vi_webp/2NUZ8W2llS4/maxresdefault.webp',
  2326. 'comment_count': int,
  2327. 'channel_follower_count': int,
  2328. 'uploader': 'Leon Nguyen',
  2329. 'uploader_url': 'https://www.youtube.com/@LeonNguyen',
  2330. 'uploader_id': '@LeonNguyen',
  2331. 'heatmap': 'count:100',
  2332. 'timestamp': 1641170939,
  2333. },
  2334. }, {
  2335. # date text is premiered video, ensure upload date in UTC (published 1641172509)
  2336. 'url': 'https://www.youtube.com/watch?v=mzZzzBU6lrM',
  2337. 'info_dict': {
  2338. 'id': 'mzZzzBU6lrM',
  2339. 'ext': 'mp4',
  2340. 'title': 'I Met GeorgeNotFound In Real Life...',
  2341. 'description': 'md5:978296ec9783a031738b684d4ebf302d',
  2342. 'channel_id': 'UC_8NknAFiyhOUaZqHR3lq3Q',
  2343. 'channel_url': 'https://www.youtube.com/channel/UC_8NknAFiyhOUaZqHR3lq3Q',
  2344. 'duration': 955,
  2345. 'view_count': int,
  2346. 'age_limit': 0,
  2347. 'categories': ['Entertainment'],
  2348. 'tags': 'count:26',
  2349. 'playable_in_embed': True,
  2350. 'live_status': 'not_live',
  2351. 'release_timestamp': 1641172509,
  2352. 'release_date': '20220103',
  2353. 'upload_date': '20220103',
  2354. 'like_count': int,
  2355. 'availability': 'public',
  2356. 'channel': 'Quackity',
  2357. 'thumbnail': 'https://i.ytimg.com/vi/mzZzzBU6lrM/maxresdefault.jpg',
  2358. 'channel_follower_count': int,
  2359. 'uploader': 'Quackity',
  2360. 'uploader_id': '@Quackity',
  2361. 'uploader_url': 'https://www.youtube.com/@Quackity',
  2362. 'comment_count': int,
  2363. 'channel_is_verified': True,
  2364. 'heatmap': 'count:100',
  2365. 'timestamp': 1641172509,
  2366. },
  2367. },
  2368. { # continuous livestream.
  2369. # Upload date was 2022-07-12T05:12:29-07:00, while stream start is 2022-07-12T15:59:30+00:00
  2370. 'url': 'https://www.youtube.com/watch?v=jfKfPfyJRdk',
  2371. 'info_dict': {
  2372. 'id': 'jfKfPfyJRdk',
  2373. 'ext': 'mp4',
  2374. 'channel_id': 'UCSJ4gkVC6NrvII8umztf0Ow',
  2375. 'like_count': int,
  2376. 'uploader': 'Lofi Girl',
  2377. 'categories': ['Music'],
  2378. 'concurrent_view_count': int,
  2379. 'playable_in_embed': True,
  2380. 'timestamp': 1657627949,
  2381. 'release_date': '20220712',
  2382. 'channel_url': 'https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow',
  2383. 'description': 'md5:13a6f76df898f5674f9127139f3df6f7',
  2384. 'age_limit': 0,
  2385. 'thumbnail': 'https://i.ytimg.com/vi/jfKfPfyJRdk/maxresdefault.jpg',
  2386. 'release_timestamp': 1657641570,
  2387. 'uploader_url': 'https://www.youtube.com/@LofiGirl',
  2388. 'channel_follower_count': int,
  2389. 'channel_is_verified': True,
  2390. 'title': r're:^lofi hip hop radio 📚 - beats to relax/study to',
  2391. 'view_count': int,
  2392. 'live_status': 'is_live',
  2393. 'tags': 'count:32',
  2394. 'channel': 'Lofi Girl',
  2395. 'availability': 'public',
  2396. 'upload_date': '20220712',
  2397. 'uploader_id': '@LofiGirl',
  2398. },
  2399. 'params': {'skip_download': True},
  2400. }, {
  2401. 'url': 'https://www.youtube.com/watch?v=tjjjtzRLHvA',
  2402. 'info_dict': {
  2403. 'id': 'tjjjtzRLHvA',
  2404. 'ext': 'mp4',
  2405. 'title': 'ハッシュタグ無し };if window.ytcsi',
  2406. 'upload_date': '20220323',
  2407. 'like_count': int,
  2408. 'availability': 'unlisted',
  2409. 'channel': 'Lesmiscore',
  2410. 'thumbnail': r're:^https?://.*\.jpg',
  2411. 'age_limit': 0,
  2412. 'categories': ['Music'],
  2413. 'view_count': int,
  2414. 'description': '',
  2415. 'channel_url': 'https://www.youtube.com/channel/UCdqltm_7iv1Vs6kp6Syke5A',
  2416. 'channel_id': 'UCdqltm_7iv1Vs6kp6Syke5A',
  2417. 'live_status': 'not_live',
  2418. 'playable_in_embed': True,
  2419. 'channel_follower_count': int,
  2420. 'duration': 6,
  2421. 'tags': [],
  2422. 'uploader_id': '@lesmiscore',
  2423. 'uploader': 'Lesmiscore',
  2424. 'uploader_url': 'https://www.youtube.com/@lesmiscore',
  2425. 'timestamp': 1648005313,
  2426. },
  2427. }, {
  2428. # Prefer primary title+description language metadata by default
  2429. # Do not prefer translated description if primary is empty
  2430. 'url': 'https://www.youtube.com/watch?v=el3E4MbxRqQ',
  2431. 'info_dict': {
  2432. 'id': 'el3E4MbxRqQ',
  2433. 'ext': 'mp4',
  2434. 'title': 'dlp test video 2 - primary sv no desc',
  2435. 'description': '',
  2436. 'channel': 'cole-dlp-test-acc',
  2437. 'tags': [],
  2438. 'view_count': int,
  2439. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  2440. 'like_count': int,
  2441. 'playable_in_embed': True,
  2442. 'availability': 'unlisted',
  2443. 'thumbnail': r're:^https?://.*\.jpg',
  2444. 'age_limit': 0,
  2445. 'duration': 5,
  2446. 'live_status': 'not_live',
  2447. 'upload_date': '20220908',
  2448. 'categories': ['People & Blogs'],
  2449. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  2450. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  2451. 'uploader_id': '@coletdjnz',
  2452. 'uploader': 'cole-dlp-test-acc',
  2453. 'timestamp': 1662677394,
  2454. },
  2455. 'params': {'skip_download': True},
  2456. }, {
  2457. # Extractor argument: prefer translated title+description
  2458. 'url': 'https://www.youtube.com/watch?v=gHKT4uU8Zng',
  2459. 'info_dict': {
  2460. 'id': 'gHKT4uU8Zng',
  2461. 'ext': 'mp4',
  2462. 'channel': 'cole-dlp-test-acc',
  2463. 'tags': [],
  2464. 'duration': 5,
  2465. 'live_status': 'not_live',
  2466. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  2467. 'upload_date': '20220729',
  2468. 'view_count': int,
  2469. 'categories': ['People & Blogs'],
  2470. 'thumbnail': r're:^https?://.*\.jpg',
  2471. 'title': 'dlp test video title translated (fr)',
  2472. 'availability': 'public',
  2473. 'age_limit': 0,
  2474. 'description': 'dlp test video description translated (fr)',
  2475. 'playable_in_embed': True,
  2476. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  2477. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  2478. 'uploader_id': '@coletdjnz',
  2479. 'uploader': 'cole-dlp-test-acc',
  2480. 'timestamp': 1659073275,
  2481. 'like_count': int,
  2482. },
  2483. 'params': {'skip_download': True, 'extractor_args': {'youtube': {'lang': ['fr']}}},
  2484. 'expected_warnings': [r'Preferring "fr" translated fields'],
  2485. }, {
  2486. 'note': '6 channel audio',
  2487. 'url': 'https://www.youtube.com/watch?v=zgdo7-RRjgo',
  2488. 'only_matching': True,
  2489. }, {
  2490. 'note': 'Multiple HLS formats with same itag',
  2491. 'url': 'https://www.youtube.com/watch?v=kX3nB4PpJko',
  2492. 'info_dict': {
  2493. 'id': 'kX3nB4PpJko',
  2494. 'ext': 'mp4',
  2495. 'categories': ['Entertainment'],
  2496. 'description': 'md5:e8031ff6e426cdb6a77670c9b81f6fa6',
  2497. 'live_status': 'not_live',
  2498. 'duration': 937,
  2499. 'channel_follower_count': int,
  2500. 'thumbnail': 'https://i.ytimg.com/vi_webp/kX3nB4PpJko/maxresdefault.webp',
  2501. 'title': 'Last To Take Hand Off Jet, Keeps It!',
  2502. 'channel': 'MrBeast',
  2503. 'playable_in_embed': True,
  2504. 'view_count': int,
  2505. 'upload_date': '20221112',
  2506. 'channel_url': 'https://www.youtube.com/channel/UCX6OQ3DkcsbYNE6H8uQQuVA',
  2507. 'age_limit': 0,
  2508. 'availability': 'public',
  2509. 'channel_id': 'UCX6OQ3DkcsbYNE6H8uQQuVA',
  2510. 'like_count': int,
  2511. 'tags': [],
  2512. 'uploader': 'MrBeast',
  2513. 'uploader_url': 'https://www.youtube.com/@MrBeast',
  2514. 'uploader_id': '@MrBeast',
  2515. 'comment_count': int,
  2516. 'channel_is_verified': True,
  2517. 'heatmap': 'count:100',
  2518. },
  2519. 'params': {'extractor_args': {'youtube': {'player_client': ['ios']}}, 'format': '233-1'},
  2520. }, {
  2521. 'note': 'Audio formats with Dynamic Range Compression',
  2522. 'url': 'https://www.youtube.com/watch?v=Tq92D6wQ1mg',
  2523. 'info_dict': {
  2524. 'id': 'Tq92D6wQ1mg',
  2525. 'ext': 'webm',
  2526. 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
  2527. 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
  2528. 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
  2529. 'channel_follower_count': int,
  2530. 'description': 'md5:17eccca93a786d51bc67646756894066',
  2531. 'upload_date': '20191228',
  2532. 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
  2533. 'playable_in_embed': True,
  2534. 'like_count': int,
  2535. 'categories': ['Entertainment'],
  2536. 'thumbnail': 'https://i.ytimg.com/vi/Tq92D6wQ1mg/sddefault.jpg',
  2537. 'age_limit': 18,
  2538. 'channel': 'Projekt Melody',
  2539. 'view_count': int,
  2540. 'availability': 'needs_auth',
  2541. 'comment_count': int,
  2542. 'live_status': 'not_live',
  2543. 'duration': 106,
  2544. 'uploader': 'Projekt Melody',
  2545. 'uploader_id': '@ProjektMelody',
  2546. 'uploader_url': 'https://www.youtube.com/@ProjektMelody',
  2547. 'timestamp': 1577508724,
  2548. },
  2549. 'params': {'extractor_args': {'youtube': {'player_client': ['tv_embedded']}}, 'format': '251-drc'},
  2550. },
  2551. {
  2552. 'url': 'https://www.youtube.com/live/qVv6vCqciTM',
  2553. 'info_dict': {
  2554. 'id': 'qVv6vCqciTM',
  2555. 'ext': 'mp4',
  2556. 'age_limit': 0,
  2557. 'comment_count': int,
  2558. 'chapters': 'count:13',
  2559. 'upload_date': '20221223',
  2560. 'thumbnail': 'https://i.ytimg.com/vi/qVv6vCqciTM/maxresdefault.jpg',
  2561. 'channel_url': 'https://www.youtube.com/channel/UCIdEIHpS0TdkqRkHL5OkLtA',
  2562. 'like_count': int,
  2563. 'release_date': '20221223',
  2564. 'tags': ['Vtuber', '月ノ美兎', '名取さな', 'にじさんじ', 'クリスマス', '3D配信'],
  2565. 'title': '【 #インターネット女クリスマス 】3Dで歌ってはしゃぐインターネットの女たち【月ノ美兎/名取さな】',
  2566. 'view_count': int,
  2567. 'playable_in_embed': True,
  2568. 'duration': 4438,
  2569. 'availability': 'public',
  2570. 'channel_follower_count': int,
  2571. 'channel_id': 'UCIdEIHpS0TdkqRkHL5OkLtA',
  2572. 'categories': ['Entertainment'],
  2573. 'live_status': 'was_live',
  2574. 'release_timestamp': 1671793345,
  2575. 'channel': 'さなちゃんねる',
  2576. 'description': 'md5:6aebf95cc4a1d731aebc01ad6cc9806d',
  2577. 'uploader': 'さなちゃんねる',
  2578. 'uploader_url': 'https://www.youtube.com/@sana_natori',
  2579. 'uploader_id': '@sana_natori',
  2580. 'channel_is_verified': True,
  2581. 'heatmap': 'count:100',
  2582. 'timestamp': 1671798112,
  2583. },
  2584. },
  2585. {
  2586. # Fallbacks when webpage and web client is unavailable
  2587. 'url': 'https://www.youtube.com/watch?v=wSSmNUl9Snw',
  2588. 'info_dict': {
  2589. 'id': 'wSSmNUl9Snw',
  2590. 'ext': 'mp4',
  2591. # 'categories': ['Science & Technology'],
  2592. 'view_count': int,
  2593. 'chapters': 'count:2',
  2594. 'channel': 'Scott Manley',
  2595. 'like_count': int,
  2596. 'age_limit': 0,
  2597. # 'availability': 'public',
  2598. 'channel_follower_count': int,
  2599. 'live_status': 'not_live',
  2600. 'upload_date': '20170831',
  2601. 'duration': 682,
  2602. 'tags': 'count:8',
  2603. 'uploader_url': 'https://www.youtube.com/@scottmanley',
  2604. 'description': 'md5:f4bed7b200404b72a394c2f97b782c02',
  2605. 'uploader': 'Scott Manley',
  2606. 'uploader_id': '@scottmanley',
  2607. 'title': 'The Computer Hack That Saved Apollo 14',
  2608. 'channel_id': 'UCxzC4EngIsMrPmbm6Nxvb-A',
  2609. 'thumbnail': r're:^https?://.*\.webp',
  2610. 'channel_url': 'https://www.youtube.com/channel/UCxzC4EngIsMrPmbm6Nxvb-A',
  2611. 'playable_in_embed': True,
  2612. 'comment_count': int,
  2613. 'channel_is_verified': True,
  2614. 'heatmap': 'count:100',
  2615. },
  2616. 'params': {
  2617. 'extractor_args': {'youtube': {'player_client': ['ios'], 'player_skip': ['webpage']}},
  2618. },
  2619. },
  2620. ]
  2621. _WEBPAGE_TESTS = [
  2622. # YouTube <object> embed
  2623. {
  2624. 'url': 'http://www.improbable.com/2017/04/03/untrained-modern-youths-and-ancient-masters-in-selfie-portraits/',
  2625. 'md5': '873c81d308b979f0e23ee7e620b312a3',
  2626. 'info_dict': {
  2627. 'id': 'msN87y-iEx0',
  2628. 'ext': 'mp4',
  2629. 'title': 'Feynman: Mirrors FUN TO IMAGINE 6',
  2630. 'upload_date': '20080526',
  2631. 'description': 'md5:873c81d308b979f0e23ee7e620b312a3',
  2632. 'age_limit': 0,
  2633. 'tags': ['feynman', 'mirror', 'science', 'physics', 'imagination', 'fun', 'cool', 'puzzle'],
  2634. 'channel_id': 'UCCeo--lls1vna5YJABWAcVA',
  2635. 'playable_in_embed': True,
  2636. 'thumbnail': 'https://i.ytimg.com/vi/msN87y-iEx0/hqdefault.jpg',
  2637. 'like_count': int,
  2638. 'comment_count': int,
  2639. 'channel': 'Christopher Sykes',
  2640. 'live_status': 'not_live',
  2641. 'channel_url': 'https://www.youtube.com/channel/UCCeo--lls1vna5YJABWAcVA',
  2642. 'availability': 'public',
  2643. 'duration': 195,
  2644. 'view_count': int,
  2645. 'categories': ['Science & Technology'],
  2646. 'channel_follower_count': int,
  2647. 'uploader': 'Christopher Sykes',
  2648. 'uploader_url': 'https://www.youtube.com/@ChristopherSykesDocumentaries',
  2649. 'uploader_id': '@ChristopherSykesDocumentaries',
  2650. 'heatmap': 'count:100',
  2651. 'timestamp': 1211825920,
  2652. },
  2653. 'params': {
  2654. 'skip_download': True,
  2655. },
  2656. },
  2657. ]
  2658. @classmethod
  2659. def suitable(cls, url):
  2660. from ..utils import parse_qs
  2661. qs = parse_qs(url)
  2662. if qs.get('list', [None])[0]:
  2663. return False
  2664. return super().suitable(url)
  2665. def __init__(self, *args, **kwargs):
  2666. super().__init__(*args, **kwargs)
  2667. self._code_cache = {}
  2668. self._player_cache = {}
  2669. def _prepare_live_from_start_formats(self, formats, video_id, live_start_time, url, webpage_url, smuggled_data, is_live):
  2670. lock = threading.Lock()
  2671. start_time = time.time()
  2672. formats = [f for f in formats if f.get('is_from_start')]
  2673. def refetch_manifest(format_id, delay):
  2674. nonlocal formats, start_time, is_live
  2675. if time.time() <= start_time + delay:
  2676. return
  2677. _, _, prs, player_url = self._download_player_responses(url, smuggled_data, video_id, webpage_url)
  2678. video_details = traverse_obj(prs, (..., 'videoDetails'), expected_type=dict)
  2679. microformats = traverse_obj(
  2680. prs, (..., 'microformat', 'playerMicroformatRenderer'),
  2681. expected_type=dict)
  2682. _, live_status, _, formats, _ = self._list_formats(video_id, microformats, video_details, prs, player_url)
  2683. is_live = live_status == 'is_live'
  2684. start_time = time.time()
  2685. def mpd_feed(format_id, delay):
  2686. """
  2687. @returns (manifest_url, manifest_stream_number, is_live) or None
  2688. """
  2689. for retry in self.RetryManager(fatal=False):
  2690. with lock:
  2691. refetch_manifest(format_id, delay)
  2692. f = next((f for f in formats if f['format_id'] == format_id), None)
  2693. if not f:
  2694. if not is_live:
  2695. retry.error = f'{video_id}: Video is no longer live'
  2696. else:
  2697. retry.error = f'Cannot find refreshed manifest for format {format_id}{bug_reports_message()}'
  2698. continue
  2699. return f['manifest_url'], f['manifest_stream_number'], is_live
  2700. return None
  2701. for f in formats:
  2702. f['is_live'] = is_live
  2703. gen = functools.partial(self._live_dash_fragments, video_id, f['format_id'],
  2704. live_start_time, mpd_feed, not is_live and f.copy())
  2705. if is_live:
  2706. f['fragments'] = gen
  2707. f['protocol'] = 'http_dash_segments_generator'
  2708. else:
  2709. f['fragments'] = LazyList(gen({}))
  2710. del f['is_from_start']
  2711. def _live_dash_fragments(self, video_id, format_id, live_start_time, mpd_feed, manifestless_orig_fmt, ctx):
  2712. FETCH_SPAN, MAX_DURATION = 5, 432000
  2713. mpd_url, stream_number, is_live = None, None, True
  2714. begin_index = 0
  2715. download_start_time = ctx.get('start') or time.time()
  2716. lack_early_segments = download_start_time - (live_start_time or download_start_time) > MAX_DURATION
  2717. if lack_early_segments:
  2718. self.report_warning(bug_reports_message(
  2719. 'Starting download from the last 120 hours of the live stream since '
  2720. 'YouTube does not have data before that. If you think this is wrong,'), only_once=True)
  2721. lack_early_segments = True
  2722. known_idx, no_fragment_score, last_segment_url = begin_index, 0, None
  2723. fragments, fragment_base_url = None, None
  2724. def _extract_sequence_from_mpd(refresh_sequence, immediate):
  2725. nonlocal mpd_url, stream_number, is_live, no_fragment_score, fragments, fragment_base_url
  2726. # Obtain from MPD's maximum seq value
  2727. old_mpd_url = mpd_url
  2728. last_error = ctx.pop('last_error', None)
  2729. expire_fast = immediate or last_error and isinstance(last_error, HTTPError) and last_error.status == 403
  2730. mpd_url, stream_number, is_live = (mpd_feed(format_id, 5 if expire_fast else 18000)
  2731. or (mpd_url, stream_number, False))
  2732. if not refresh_sequence:
  2733. if expire_fast and not is_live:
  2734. return False, last_seq
  2735. elif old_mpd_url == mpd_url:
  2736. return True, last_seq
  2737. if manifestless_orig_fmt:
  2738. fmt_info = manifestless_orig_fmt
  2739. else:
  2740. try:
  2741. fmts, _ = self._extract_mpd_formats_and_subtitles(
  2742. mpd_url, None, note=False, errnote=False, fatal=False)
  2743. except ExtractorError:
  2744. fmts = None
  2745. if not fmts:
  2746. no_fragment_score += 2
  2747. return False, last_seq
  2748. fmt_info = next(x for x in fmts if x['manifest_stream_number'] == stream_number)
  2749. fragments = fmt_info['fragments']
  2750. fragment_base_url = fmt_info['fragment_base_url']
  2751. assert fragment_base_url
  2752. _last_seq = int(re.search(r'(?:/|^)sq/(\d+)', fragments[-1]['path']).group(1))
  2753. return True, _last_seq
  2754. self.write_debug(f'[{video_id}] Generating fragments for format {format_id}')
  2755. while is_live:
  2756. fetch_time = time.time()
  2757. if no_fragment_score > 30:
  2758. return
  2759. if last_segment_url:
  2760. # Obtain from "X-Head-Seqnum" header value from each segment
  2761. try:
  2762. urlh = self._request_webpage(
  2763. last_segment_url, None, note=False, errnote=False, fatal=False)
  2764. except ExtractorError:
  2765. urlh = None
  2766. last_seq = try_get(urlh, lambda x: int_or_none(x.headers['X-Head-Seqnum']))
  2767. if last_seq is None:
  2768. no_fragment_score += 2
  2769. last_segment_url = None
  2770. continue
  2771. else:
  2772. should_continue, last_seq = _extract_sequence_from_mpd(True, no_fragment_score > 15)
  2773. no_fragment_score += 2
  2774. if not should_continue:
  2775. continue
  2776. if known_idx > last_seq:
  2777. last_segment_url = None
  2778. continue
  2779. last_seq += 1
  2780. if begin_index < 0 and known_idx < 0:
  2781. # skip from the start when it's negative value
  2782. known_idx = last_seq + begin_index
  2783. if lack_early_segments:
  2784. known_idx = max(known_idx, last_seq - int(MAX_DURATION // fragments[-1]['duration']))
  2785. try:
  2786. for idx in range(known_idx, last_seq):
  2787. # do not update sequence here or you'll get skipped some part of it
  2788. should_continue, _ = _extract_sequence_from_mpd(False, False)
  2789. if not should_continue:
  2790. known_idx = idx - 1
  2791. raise ExtractorError('breaking out of outer loop')
  2792. last_segment_url = urljoin(fragment_base_url, f'sq/{idx}')
  2793. yield {
  2794. 'url': last_segment_url,
  2795. 'fragment_count': last_seq,
  2796. }
  2797. if known_idx == last_seq:
  2798. no_fragment_score += 5
  2799. else:
  2800. no_fragment_score = 0
  2801. known_idx = last_seq
  2802. except ExtractorError:
  2803. continue
  2804. if manifestless_orig_fmt:
  2805. # Stop at the first iteration if running for post-live manifestless;
  2806. # fragment count no longer increase since it starts
  2807. break
  2808. time.sleep(max(0, FETCH_SPAN + fetch_time - time.time()))
  2809. def _extract_player_url(self, *ytcfgs, webpage=None):
  2810. player_url = traverse_obj(
  2811. ytcfgs, (..., 'PLAYER_JS_URL'), (..., 'WEB_PLAYER_CONTEXT_CONFIGS', ..., 'jsUrl'),
  2812. get_all=False, expected_type=str)
  2813. if not player_url:
  2814. return
  2815. return urljoin('https://www.youtube.com', player_url)
  2816. def _download_player_url(self, video_id, fatal=False):
  2817. res = self._download_webpage(
  2818. 'https://www.youtube.com/iframe_api',
  2819. note='Downloading iframe API JS', video_id=video_id, fatal=fatal)
  2820. if res:
  2821. player_version = self._search_regex(
  2822. r'player\\?/([0-9a-fA-F]{8})\\?/', res, 'player version', fatal=fatal)
  2823. if player_version:
  2824. return f'https://www.youtube.com/s/player/{player_version}/player_ias.vflset/en_US/base.js'
  2825. def _signature_cache_id(self, example_sig):
  2826. """ Return a string representation of a signature """
  2827. return '.'.join(str(len(part)) for part in example_sig.split('.'))
  2828. @classmethod
  2829. def _extract_player_info(cls, player_url):
  2830. for player_re in cls._PLAYER_INFO_RE:
  2831. id_m = re.search(player_re, player_url)
  2832. if id_m:
  2833. break
  2834. else:
  2835. raise ExtractorError(f'Cannot identify player {player_url!r}')
  2836. return id_m.group('id')
  2837. def _load_player(self, video_id, player_url, fatal=True):
  2838. player_id = self._extract_player_info(player_url)
  2839. if player_id not in self._code_cache:
  2840. code = self._download_webpage(
  2841. player_url, video_id, fatal=fatal,
  2842. note='Downloading player ' + player_id,
  2843. errnote=f'Download of {player_url} failed')
  2844. if code:
  2845. self._code_cache[player_id] = code
  2846. return self._code_cache.get(player_id)
  2847. def _extract_signature_function(self, video_id, player_url, example_sig):
  2848. player_id = self._extract_player_info(player_url)
  2849. # Read from filesystem cache
  2850. func_id = f'js_{player_id}_{self._signature_cache_id(example_sig)}'
  2851. assert os.path.basename(func_id) == func_id
  2852. self.write_debug(f'Extracting signature function {func_id}')
  2853. cache_spec, code = self.cache.load('youtube-sigfuncs', func_id), None
  2854. if not cache_spec:
  2855. code = self._load_player(video_id, player_url)
  2856. if code:
  2857. res = self._parse_sig_js(code)
  2858. test_string = ''.join(map(chr, range(len(example_sig))))
  2859. cache_spec = [ord(c) for c in res(test_string)]
  2860. self.cache.store('youtube-sigfuncs', func_id, cache_spec)
  2861. return lambda s: ''.join(s[i] for i in cache_spec)
  2862. def _print_sig_code(self, func, example_sig):
  2863. if not self.get_param('youtube_print_sig_code'):
  2864. return
  2865. def gen_sig_code(idxs):
  2866. def _genslice(start, end, step):
  2867. starts = '' if start == 0 else str(start)
  2868. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  2869. steps = '' if step == 1 else (':%d' % step)
  2870. return f's[{starts}{ends}{steps}]'
  2871. step = None
  2872. # Quelch pyflakes warnings - start will be set when step is set
  2873. start = '(Never used)'
  2874. for i, prev in zip(idxs[1:], idxs[:-1]):
  2875. if step is not None:
  2876. if i - prev == step:
  2877. continue
  2878. yield _genslice(start, prev, step)
  2879. step = None
  2880. continue
  2881. if i - prev in [-1, 1]:
  2882. step = i - prev
  2883. start = prev
  2884. continue
  2885. else:
  2886. yield 's[%d]' % prev
  2887. if step is None:
  2888. yield 's[%d]' % i
  2889. else:
  2890. yield _genslice(start, i, step)
  2891. test_string = ''.join(map(chr, range(len(example_sig))))
  2892. cache_res = func(test_string)
  2893. cache_spec = [ord(c) for c in cache_res]
  2894. expr_code = ' + '.join(gen_sig_code(cache_spec))
  2895. signature_id_tuple = '({})'.format(', '.join(str(len(p)) for p in example_sig.split('.')))
  2896. code = (f'if tuple(len(p) for p in s.split(\'.\')) == {signature_id_tuple}:\n'
  2897. f' return {expr_code}\n')
  2898. self.to_screen('Extracted signature function:\n' + code)
  2899. def _parse_sig_js(self, jscode):
  2900. funcname = self._search_regex(
  2901. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2902. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2903. r'\bm=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(h\.s\)\)',
  2904. r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(c\)\)',
  2905. r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)(?:;[a-zA-Z0-9$]{2}\.[a-zA-Z0-9$]{2}\(a,\d+\))?',
  2906. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  2907. # Obsolete patterns
  2908. r'("|\')signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2909. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  2910. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2911. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2912. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  2913. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  2914. jscode, 'Initial JS player signature function name', group='sig')
  2915. jsi = JSInterpreter(jscode)
  2916. initial_function = jsi.extract_function(funcname)
  2917. return lambda s: initial_function([s])
  2918. def _cached(self, func, *cache_id):
  2919. def inner(*args, **kwargs):
  2920. if cache_id not in self._player_cache:
  2921. try:
  2922. self._player_cache[cache_id] = func(*args, **kwargs)
  2923. except ExtractorError as e:
  2924. self._player_cache[cache_id] = e
  2925. except Exception as e:
  2926. self._player_cache[cache_id] = ExtractorError(traceback.format_exc(), cause=e)
  2927. ret = self._player_cache[cache_id]
  2928. if isinstance(ret, Exception):
  2929. raise ret
  2930. return ret
  2931. return inner
  2932. def _decrypt_signature(self, s, video_id, player_url):
  2933. """Turn the encrypted s field into a working signature"""
  2934. extract_sig = self._cached(
  2935. self._extract_signature_function, 'sig', player_url, self._signature_cache_id(s))
  2936. func = extract_sig(video_id, player_url, s)
  2937. self._print_sig_code(func, s)
  2938. return func(s)
  2939. def _decrypt_nsig(self, s, video_id, player_url):
  2940. """Turn the encrypted n field into a working signature"""
  2941. if player_url is None:
  2942. raise ExtractorError('Cannot decrypt nsig without player_url')
  2943. player_url = urljoin('https://www.youtube.com', player_url)
  2944. try:
  2945. jsi, player_id, func_code = self._extract_n_function_code(video_id, player_url)
  2946. except ExtractorError as e:
  2947. raise ExtractorError('Unable to extract nsig function code', cause=e)
  2948. if self.get_param('youtube_print_sig_code'):
  2949. self.to_screen(f'Extracted nsig function from {player_id}:\n{func_code[1]}\n')
  2950. try:
  2951. extract_nsig = self._cached(self._extract_n_function_from_code, 'nsig func', player_url)
  2952. ret = extract_nsig(jsi, func_code)(s)
  2953. except JSInterpreter.Exception as e:
  2954. try:
  2955. jsi = PhantomJSwrapper(self, timeout=5000)
  2956. except ExtractorError:
  2957. raise e
  2958. self.report_warning(
  2959. f'Native nsig extraction failed: Trying with PhantomJS\n'
  2960. f' n = {s} ; player = {player_url}', video_id)
  2961. self.write_debug(e, only_once=True)
  2962. args, func_body = func_code
  2963. ret = jsi.execute(
  2964. f'console.log(function({", ".join(args)}) {{ {func_body} }}({s!r}));',
  2965. video_id=video_id, note='Executing signature code').strip()
  2966. self.write_debug(f'Decrypted nsig {s} => {ret}')
  2967. return ret
  2968. def _extract_n_function_name(self, jscode):
  2969. funcname, idx = self._search_regex(
  2970. r'\.get\("n"\)\)&&\(b=(?P<nfunc>[a-zA-Z0-9$]+)(?:\[(?P<idx>\d+)\])?\([a-zA-Z0-9]\)',
  2971. jscode, 'Initial JS player n function name', group=('nfunc', 'idx'))
  2972. if not idx:
  2973. return funcname
  2974. return json.loads(js_to_json(self._search_regex(
  2975. rf'var {re.escape(funcname)}\s*=\s*(\[.+?\])\s*[,;]', jscode,
  2976. f'Initial JS player n function list ({funcname}.{idx})')))[int(idx)]
  2977. def _extract_n_function_code(self, video_id, player_url):
  2978. player_id = self._extract_player_info(player_url)
  2979. func_code = self.cache.load('youtube-nsig', player_id, min_ver='2022.09.1')
  2980. jscode = func_code or self._load_player(video_id, player_url)
  2981. jsi = JSInterpreter(jscode)
  2982. if func_code:
  2983. return jsi, player_id, func_code
  2984. func_name = self._extract_n_function_name(jscode)
  2985. # For redundancy
  2986. func_code = self._search_regex(
  2987. rf'''(?xs){func_name}\s*=\s*function\s*\((?P<var>[\w$]+)\)\s*
  2988. # NB: The end of the regex is intentionally kept strict
  2989. {{(?P<code>.+?}}\s*return\ [\w$]+.join\(""\))}};''',
  2990. jscode, 'nsig function', group=('var', 'code'), default=None)
  2991. if func_code:
  2992. func_code = ([func_code[0]], func_code[1])
  2993. else:
  2994. self.write_debug('Extracting nsig function with jsinterp')
  2995. func_code = jsi.extract_function_code(func_name)
  2996. self.cache.store('youtube-nsig', player_id, func_code)
  2997. return jsi, player_id, func_code
  2998. def _extract_n_function_from_code(self, jsi, func_code):
  2999. func = jsi.extract_function_from_code(*func_code)
  3000. def extract_nsig(s):
  3001. try:
  3002. ret = func([s])
  3003. except JSInterpreter.Exception:
  3004. raise
  3005. except Exception as e:
  3006. raise JSInterpreter.Exception(traceback.format_exc(), cause=e)
  3007. if ret.startswith('enhanced_except_'):
  3008. raise JSInterpreter.Exception('Signature function returned an exception')
  3009. return ret
  3010. return extract_nsig
  3011. def _extract_signature_timestamp(self, video_id, player_url, ytcfg=None, fatal=False):
  3012. """
  3013. Extract signatureTimestamp (sts)
  3014. Required to tell API what sig/player version is in use.
  3015. """
  3016. sts = None
  3017. if isinstance(ytcfg, dict):
  3018. sts = int_or_none(ytcfg.get('STS'))
  3019. if not sts:
  3020. # Attempt to extract from player
  3021. if player_url is None:
  3022. error_msg = 'Cannot extract signature timestamp without player_url.'
  3023. if fatal:
  3024. raise ExtractorError(error_msg)
  3025. self.report_warning(error_msg)
  3026. return
  3027. code = self._load_player(video_id, player_url, fatal=fatal)
  3028. if code:
  3029. sts = int_or_none(self._search_regex(
  3030. r'(?:signatureTimestamp|sts)\s*:\s*(?P<sts>[0-9]{5})', code,
  3031. 'JS player signature timestamp', group='sts', fatal=fatal))
  3032. return sts
  3033. def _mark_watched(self, video_id, player_responses):
  3034. for is_full, key in enumerate(('videostatsPlaybackUrl', 'videostatsWatchtimeUrl')):
  3035. label = 'fully ' if is_full else ''
  3036. url = get_first(player_responses, ('playbackTracking', key, 'baseUrl'),
  3037. expected_type=url_or_none)
  3038. if not url:
  3039. self.report_warning(f'Unable to mark {label}watched')
  3040. return
  3041. parsed_url = urllib.parse.urlparse(url)
  3042. qs = urllib.parse.parse_qs(parsed_url.query)
  3043. # cpn generation algorithm is reverse engineered from base.js.
  3044. # In fact it works even with dummy cpn.
  3045. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  3046. cpn = ''.join(CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(16))
  3047. # # more consistent results setting it to right before the end
  3048. video_length = [str(float((qs.get('len') or ['1.5'])[0]) - 1)]
  3049. qs.update({
  3050. 'ver': ['2'],
  3051. 'cpn': [cpn],
  3052. 'cmt': video_length,
  3053. 'el': 'detailpage', # otherwise defaults to "shorts"
  3054. })
  3055. if is_full:
  3056. # these seem to mark watchtime "history" in the real world
  3057. # they're required, so send in a single value
  3058. qs.update({
  3059. 'st': 0,
  3060. 'et': video_length,
  3061. })
  3062. url = urllib.parse.urlunparse(
  3063. parsed_url._replace(query=urllib.parse.urlencode(qs, True)))
  3064. self._download_webpage(
  3065. url, video_id, f'Marking {label}watched',
  3066. 'Unable to mark watched', fatal=False)
  3067. @classmethod
  3068. def _extract_from_webpage(cls, url, webpage):
  3069. # Invidious Instances
  3070. # https://github.com/yt-dlp/yt-dlp/issues/195
  3071. # https://github.com/iv-org/invidious/pull/1730
  3072. mobj = re.search(
  3073. r'<link rel="alternate" href="(?P<url>https://www\.youtube\.com/watch\?v=[0-9A-Za-z_-]{11})"',
  3074. webpage)
  3075. if mobj:
  3076. yield cls.url_result(mobj.group('url'), cls)
  3077. raise cls.StopExtraction
  3078. yield from super()._extract_from_webpage(url, webpage)
  3079. # lazyYT YouTube embed
  3080. for id_ in re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage):
  3081. yield cls.url_result(unescapeHTML(id_), cls, id_)
  3082. # Wordpress "YouTube Video Importer" plugin
  3083. for m in re.findall(r'''(?x)<div[^>]+
  3084. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  3085. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage):
  3086. yield cls.url_result(m[-1], cls, m[-1])
  3087. @classmethod
  3088. def extract_id(cls, url):
  3089. video_id = cls.get_temp_id(url)
  3090. if not video_id:
  3091. raise ExtractorError(f'Invalid URL: {url}')
  3092. return video_id
  3093. def _extract_chapters_from_json(self, data, duration):
  3094. chapter_list = traverse_obj(
  3095. data, (
  3096. 'playerOverlays', 'playerOverlayRenderer', 'decoratedPlayerBarRenderer',
  3097. 'decoratedPlayerBarRenderer', 'playerBar', 'chapteredPlayerBarRenderer', 'chapters',
  3098. ), expected_type=list)
  3099. return self._extract_chapters_helper(
  3100. chapter_list,
  3101. start_function=lambda chapter: float_or_none(
  3102. traverse_obj(chapter, ('chapterRenderer', 'timeRangeStartMillis')), scale=1000),
  3103. title_function=lambda chapter: traverse_obj(
  3104. chapter, ('chapterRenderer', 'title', 'simpleText'), expected_type=str),
  3105. duration=duration)
  3106. def _extract_chapters_from_engagement_panel(self, data, duration):
  3107. content_list = traverse_obj(
  3108. data,
  3109. ('engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'macroMarkersListRenderer', 'contents'),
  3110. expected_type=list)
  3111. chapter_time = lambda chapter: parse_duration(self._get_text(chapter, 'timeDescription'))
  3112. chapter_title = lambda chapter: self._get_text(chapter, 'title')
  3113. return next(filter(None, (
  3114. self._extract_chapters_helper(traverse_obj(contents, (..., 'macroMarkersListItemRenderer')),
  3115. chapter_time, chapter_title, duration)
  3116. for contents in content_list)), [])
  3117. def _extract_heatmap(self, data):
  3118. return traverse_obj(data, (
  3119. 'frameworkUpdates', 'entityBatchUpdate', 'mutations',
  3120. lambda _, v: v['payload']['macroMarkersListEntity']['markersList']['markerType'] == 'MARKER_TYPE_HEATMAP',
  3121. 'payload', 'macroMarkersListEntity', 'markersList', 'markers', ..., {
  3122. 'start_time': ('startMillis', {functools.partial(float_or_none, scale=1000)}),
  3123. 'end_time': {lambda x: (int(x['startMillis']) + int(x['durationMillis'])) / 1000},
  3124. 'value': ('intensityScoreNormalized', {float_or_none}),
  3125. })) or None
  3126. def _extract_comment(self, entities, parent=None):
  3127. comment_entity_payload = get_first(entities, ('payload', 'commentEntityPayload', {dict}))
  3128. if not (comment_id := traverse_obj(comment_entity_payload, ('properties', 'commentId', {str}))):
  3129. return
  3130. toolbar_entity_payload = get_first(entities, ('payload', 'engagementToolbarStateEntityPayload', {dict}))
  3131. time_text = traverse_obj(comment_entity_payload, ('properties', 'publishedTime', {str})) or ''
  3132. return {
  3133. 'id': comment_id,
  3134. 'parent': parent or 'root',
  3135. **traverse_obj(comment_entity_payload, {
  3136. 'text': ('properties', 'content', 'content', {str}),
  3137. 'like_count': ('toolbar', 'likeCountA11y', {parse_count}),
  3138. 'author_id': ('author', 'channelId', {self.ucid_or_none}),
  3139. 'author': ('author', 'displayName', {str}),
  3140. 'author_thumbnail': ('author', 'avatarThumbnailUrl', {url_or_none}),
  3141. 'author_is_uploader': ('author', 'isCreator', {bool}),
  3142. 'author_is_verified': ('author', 'isVerified', {bool}),
  3143. 'author_url': ('author', 'channelCommand', 'innertubeCommand', (
  3144. ('browseEndpoint', 'canonicalBaseUrl'), ('commandMetadata', 'webCommandMetadata', 'url'),
  3145. ), {lambda x: urljoin('https://www.youtube.com', x)}),
  3146. }, get_all=False),
  3147. 'is_favorited': (None if toolbar_entity_payload is None else
  3148. toolbar_entity_payload.get('heartState') == 'TOOLBAR_HEART_STATE_HEARTED'),
  3149. '_time_text': time_text, # FIXME: non-standard, but we need a way of showing that it is an estimate.
  3150. 'timestamp': self._parse_time_text(time_text),
  3151. }
  3152. def _extract_comment_old(self, comment_renderer, parent=None):
  3153. comment_id = comment_renderer.get('commentId')
  3154. if not comment_id:
  3155. return
  3156. info = {
  3157. 'id': comment_id,
  3158. 'text': self._get_text(comment_renderer, 'contentText'),
  3159. 'like_count': self._get_count(comment_renderer, 'voteCount'),
  3160. 'author_id': traverse_obj(comment_renderer, ('authorEndpoint', 'browseEndpoint', 'browseId', {self.ucid_or_none})),
  3161. 'author': self._get_text(comment_renderer, 'authorText'),
  3162. 'author_thumbnail': traverse_obj(comment_renderer, ('authorThumbnail', 'thumbnails', -1, 'url', {url_or_none})),
  3163. 'parent': parent or 'root',
  3164. }
  3165. # Timestamp is an estimate calculated from the current time and time_text
  3166. time_text = self._get_text(comment_renderer, 'publishedTimeText') or ''
  3167. timestamp = self._parse_time_text(time_text)
  3168. info.update({
  3169. # FIXME: non-standard, but we need a way of showing that it is an estimate.
  3170. '_time_text': time_text,
  3171. 'timestamp': timestamp,
  3172. })
  3173. info['author_url'] = urljoin(
  3174. 'https://www.youtube.com', traverse_obj(comment_renderer, ('authorEndpoint', (
  3175. ('browseEndpoint', 'canonicalBaseUrl'), ('commandMetadata', 'webCommandMetadata', 'url'))),
  3176. expected_type=str, get_all=False))
  3177. author_is_uploader = traverse_obj(comment_renderer, 'authorIsChannelOwner')
  3178. if author_is_uploader is not None:
  3179. info['author_is_uploader'] = author_is_uploader
  3180. comment_abr = traverse_obj(
  3181. comment_renderer, ('actionButtons', 'commentActionButtonsRenderer'), expected_type=dict)
  3182. if comment_abr is not None:
  3183. info['is_favorited'] = 'creatorHeart' in comment_abr
  3184. badges = self._extract_badges([traverse_obj(comment_renderer, 'authorCommentBadge')])
  3185. if self._has_badge(badges, BadgeType.VERIFIED):
  3186. info['author_is_verified'] = True
  3187. is_pinned = traverse_obj(comment_renderer, 'pinnedCommentBadge')
  3188. if is_pinned:
  3189. info['is_pinned'] = True
  3190. return info
  3191. def _comment_entries(self, root_continuation_data, ytcfg, video_id, parent=None, tracker=None):
  3192. get_single_config_arg = lambda c: self._configuration_arg(c, [''])[0]
  3193. def extract_header(contents):
  3194. _continuation = None
  3195. for content in contents:
  3196. comments_header_renderer = traverse_obj(content, 'commentsHeaderRenderer')
  3197. expected_comment_count = self._get_count(
  3198. comments_header_renderer, 'countText', 'commentsCount')
  3199. if expected_comment_count is not None:
  3200. tracker['est_total'] = expected_comment_count
  3201. self.to_screen(f'Downloading ~{expected_comment_count} comments')
  3202. comment_sort_index = int(get_single_config_arg('comment_sort') != 'top') # 1 = new, 0 = top
  3203. sort_menu_item = try_get(
  3204. comments_header_renderer,
  3205. lambda x: x['sortMenu']['sortFilterSubMenuRenderer']['subMenuItems'][comment_sort_index], dict) or {}
  3206. sort_continuation_ep = sort_menu_item.get('serviceEndpoint') or {}
  3207. _continuation = self._extract_continuation_ep_data(sort_continuation_ep) or self._extract_continuation(sort_menu_item)
  3208. if not _continuation:
  3209. continue
  3210. sort_text = str_or_none(sort_menu_item.get('title'))
  3211. if not sort_text:
  3212. sort_text = 'top comments' if comment_sort_index == 0 else 'newest first'
  3213. self.to_screen(f'Sorting comments by {sort_text.lower()}')
  3214. break
  3215. return _continuation
  3216. def extract_thread(contents, entity_payloads):
  3217. if not parent:
  3218. tracker['current_page_thread'] = 0
  3219. for content in contents:
  3220. if not parent and tracker['total_parent_comments'] >= max_parents:
  3221. yield
  3222. comment_thread_renderer = try_get(content, lambda x: x['commentThreadRenderer'])
  3223. # old comment format
  3224. if not entity_payloads:
  3225. comment_renderer = get_first(
  3226. (comment_thread_renderer, content), [['commentRenderer', ('comment', 'commentRenderer')]],
  3227. expected_type=dict, default={})
  3228. comment = self._extract_comment_old(comment_renderer, parent)
  3229. # new comment format
  3230. else:
  3231. view_model = (
  3232. traverse_obj(comment_thread_renderer, ('commentViewModel', 'commentViewModel', {dict}))
  3233. or traverse_obj(content, ('commentViewModel', {dict})))
  3234. comment_keys = traverse_obj(view_model, (('commentKey', 'toolbarStateKey'), {str}))
  3235. if not comment_keys:
  3236. continue
  3237. entities = traverse_obj(entity_payloads, lambda _, v: v['entityKey'] in comment_keys)
  3238. comment = self._extract_comment(entities, parent)
  3239. if comment:
  3240. comment['is_pinned'] = traverse_obj(view_model, ('pinnedText', {str})) is not None
  3241. if not comment:
  3242. continue
  3243. comment_id = comment['id']
  3244. if comment.get('is_pinned'):
  3245. tracker['pinned_comment_ids'].add(comment_id)
  3246. # Sometimes YouTube may break and give us infinite looping comments.
  3247. # See: https://github.com/yt-dlp/yt-dlp/issues/6290
  3248. if comment_id in tracker['seen_comment_ids']:
  3249. if comment_id in tracker['pinned_comment_ids'] and not comment.get('is_pinned'):
  3250. # Pinned comments may appear a second time in newest first sort
  3251. # See: https://github.com/yt-dlp/yt-dlp/issues/6712
  3252. continue
  3253. self.report_warning(
  3254. 'Detected YouTube comments looping. Stopping comment extraction '
  3255. f'{"for this thread" if parent else ""} as we probably cannot get any more.')
  3256. yield
  3257. else:
  3258. tracker['seen_comment_ids'].add(comment['id'])
  3259. tracker['running_total'] += 1
  3260. tracker['total_reply_comments' if parent else 'total_parent_comments'] += 1
  3261. yield comment
  3262. # Attempt to get the replies
  3263. comment_replies_renderer = try_get(
  3264. comment_thread_renderer, lambda x: x['replies']['commentRepliesRenderer'], dict)
  3265. if comment_replies_renderer:
  3266. tracker['current_page_thread'] += 1
  3267. comment_entries_iter = self._comment_entries(
  3268. comment_replies_renderer, ytcfg, video_id,
  3269. parent=comment.get('id'), tracker=tracker)
  3270. yield from itertools.islice(comment_entries_iter, min(
  3271. max_replies_per_thread, max(0, max_replies - tracker['total_reply_comments'])))
  3272. # Keeps track of counts across recursive calls
  3273. if not tracker:
  3274. tracker = {
  3275. 'running_total': 0,
  3276. 'est_total': None,
  3277. 'current_page_thread': 0,
  3278. 'total_parent_comments': 0,
  3279. 'total_reply_comments': 0,
  3280. 'seen_comment_ids': set(),
  3281. 'pinned_comment_ids': set(),
  3282. }
  3283. # TODO: Deprecated
  3284. # YouTube comments have a max depth of 2
  3285. max_depth = int_or_none(get_single_config_arg('max_comment_depth'))
  3286. if max_depth:
  3287. self._downloader.deprecated_feature('[youtube] max_comment_depth extractor argument is deprecated. '
  3288. 'Set max replies in the max-comments extractor argument instead')
  3289. if max_depth == 1 and parent:
  3290. return
  3291. max_comments, max_parents, max_replies, max_replies_per_thread, *_ = (
  3292. int_or_none(p, default=sys.maxsize) for p in self._configuration_arg('max_comments') + [''] * 4)
  3293. continuation = self._extract_continuation(root_continuation_data)
  3294. response = None
  3295. is_forced_continuation = False
  3296. is_first_continuation = parent is None
  3297. if is_first_continuation and not continuation:
  3298. # Sometimes you can get comments by generating the continuation yourself,
  3299. # even if YouTube initially reports them being disabled - e.g. stories comments.
  3300. # Note: if the comment section is actually disabled, YouTube may return a response with
  3301. # required check_get_keys missing. So we will disable that check initially in this case.
  3302. continuation = self._build_api_continuation_query(self._generate_comment_continuation(video_id))
  3303. is_forced_continuation = True
  3304. continuation_items_path = (
  3305. 'onResponseReceivedEndpoints', ..., ('reloadContinuationItemsCommand', 'appendContinuationItemsAction'), 'continuationItems')
  3306. for page_num in itertools.count(0):
  3307. if not continuation:
  3308. break
  3309. headers = self.generate_api_headers(ytcfg=ytcfg, visitor_data=self._extract_visitor_data(response))
  3310. comment_prog_str = f"({tracker['running_total']}/~{tracker['est_total']})"
  3311. if page_num == 0:
  3312. if is_first_continuation:
  3313. note_prefix = 'Downloading comment section API JSON'
  3314. else:
  3315. note_prefix = ' Downloading comment API JSON reply thread %d %s' % (
  3316. tracker['current_page_thread'], comment_prog_str)
  3317. else:
  3318. note_prefix = '{}Downloading comment{} API JSON page {} {}'.format(
  3319. ' ' if parent else '', ' replies' if parent else '',
  3320. page_num, comment_prog_str)
  3321. # Do a deep check for incomplete data as sometimes YouTube may return no comments for a continuation
  3322. # Ignore check if YouTube says the comment count is 0.
  3323. check_get_keys = None
  3324. if not is_forced_continuation and not (tracker['est_total'] == 0 and tracker['running_total'] == 0):
  3325. check_get_keys = [[*continuation_items_path, ..., (
  3326. 'commentsHeaderRenderer' if is_first_continuation else ('commentThreadRenderer', 'commentViewModel', 'commentRenderer'))]]
  3327. try:
  3328. response = self._extract_response(
  3329. item_id=None, query=continuation,
  3330. ep='next', ytcfg=ytcfg, headers=headers, note=note_prefix,
  3331. check_get_keys=check_get_keys)
  3332. except ExtractorError as e:
  3333. # Ignore incomplete data error for replies if retries didn't work.
  3334. # This is to allow any other parent comments and comment threads to be downloaded.
  3335. # See: https://github.com/yt-dlp/yt-dlp/issues/4669
  3336. if 'incomplete data' in str(e).lower() and parent:
  3337. if self.get_param('ignoreerrors') in (True, 'only_download'):
  3338. self.report_warning(
  3339. 'Received incomplete data for a comment reply thread and retrying did not help. '
  3340. 'Ignoring to let other comments be downloaded. Pass --no-ignore-errors to not ignore.')
  3341. return
  3342. else:
  3343. raise ExtractorError(
  3344. 'Incomplete data received for comment reply thread. '
  3345. 'Pass --ignore-errors to ignore and allow rest of comments to download.',
  3346. expected=True)
  3347. raise
  3348. is_forced_continuation = False
  3349. continuation = None
  3350. mutations = traverse_obj(response, ('frameworkUpdates', 'entityBatchUpdate', 'mutations', ..., {dict}))
  3351. for continuation_items in traverse_obj(response, continuation_items_path, expected_type=list, default=[]):
  3352. if is_first_continuation:
  3353. continuation = extract_header(continuation_items)
  3354. is_first_continuation = False
  3355. if continuation:
  3356. break
  3357. continue
  3358. for entry in extract_thread(continuation_items, mutations):
  3359. if not entry:
  3360. return
  3361. yield entry
  3362. continuation = self._extract_continuation({'contents': continuation_items})
  3363. if continuation:
  3364. break
  3365. message = self._get_text(root_continuation_data, ('contents', ..., 'messageRenderer', 'text'), max_runs=1)
  3366. if message and not parent and tracker['running_total'] == 0:
  3367. self.report_warning(f'Youtube said: {message}', video_id=video_id, only_once=True)
  3368. raise self.CommentsDisabled
  3369. @staticmethod
  3370. def _generate_comment_continuation(video_id):
  3371. """
  3372. Generates initial comment section continuation token from given video id
  3373. """
  3374. token = f'\x12\r\x12\x0b{video_id}\x18\x062\'"\x11"\x0b{video_id}0\x00x\x020\x00B\x10comments-section'
  3375. return base64.b64encode(token.encode()).decode()
  3376. def _get_comments(self, ytcfg, video_id, contents, webpage):
  3377. """Entry for comment extraction"""
  3378. def _real_comment_extract(contents):
  3379. renderer = next((
  3380. item for item in traverse_obj(contents, (..., 'itemSectionRenderer'), default={})
  3381. if item.get('sectionIdentifier') == 'comment-item-section'), None)
  3382. yield from self._comment_entries(renderer, ytcfg, video_id)
  3383. max_comments = int_or_none(self._configuration_arg('max_comments', [''])[0])
  3384. return itertools.islice(_real_comment_extract(contents), 0, max_comments)
  3385. @staticmethod
  3386. def _get_checkok_params():
  3387. return {'contentCheckOk': True, 'racyCheckOk': True}
  3388. @classmethod
  3389. def _generate_player_context(cls, sts=None):
  3390. context = {
  3391. 'html5Preference': 'HTML5_PREF_WANTS',
  3392. }
  3393. if sts is not None:
  3394. context['signatureTimestamp'] = sts
  3395. return {
  3396. 'playbackContext': {
  3397. 'contentPlaybackContext': context,
  3398. },
  3399. **cls._get_checkok_params(),
  3400. }
  3401. @staticmethod
  3402. def _is_agegated(player_response):
  3403. if traverse_obj(player_response, ('playabilityStatus', 'desktopLegacyAgeGateReason')):
  3404. return True
  3405. reasons = traverse_obj(player_response, ('playabilityStatus', ('status', 'reason')))
  3406. AGE_GATE_REASONS = (
  3407. 'confirm your age', 'age-restricted', 'inappropriate', # reason
  3408. 'age_verification_required', 'age_check_required', # status
  3409. )
  3410. return any(expected in reason for expected in AGE_GATE_REASONS for reason in reasons)
  3411. @staticmethod
  3412. def _is_unplayable(player_response):
  3413. return traverse_obj(player_response, ('playabilityStatus', 'status')) == 'UNPLAYABLE'
  3414. def _extract_player_response(self, client, video_id, master_ytcfg, player_ytcfg, player_url, initial_pr, smuggled_data):
  3415. session_index = self._extract_session_index(player_ytcfg, master_ytcfg)
  3416. syncid = self._extract_account_syncid(player_ytcfg, master_ytcfg, initial_pr)
  3417. sts = self._extract_signature_timestamp(video_id, player_url, master_ytcfg, fatal=False) if player_url else None
  3418. headers = self.generate_api_headers(
  3419. ytcfg=player_ytcfg, account_syncid=syncid, session_index=session_index, default_client=client)
  3420. yt_query = {
  3421. 'videoId': video_id,
  3422. }
  3423. pp_arg = self._configuration_arg('player_params', [None], casesense=True)[0]
  3424. if pp_arg:
  3425. yt_query['params'] = pp_arg
  3426. yt_query.update(self._generate_player_context(sts))
  3427. return self._extract_response(
  3428. item_id=video_id, ep='player', query=yt_query,
  3429. ytcfg=player_ytcfg, headers=headers, fatal=True,
  3430. default_client=client,
  3431. note='Downloading {} player API JSON'.format(client.replace('_', ' ').strip()),
  3432. ) or None
  3433. def _get_requested_clients(self, url, smuggled_data):
  3434. requested_clients = []
  3435. android_clients = []
  3436. default = ['ios', 'web']
  3437. allowed_clients = sorted(
  3438. (client for client in INNERTUBE_CLIENTS if client[:1] != '_'),
  3439. key=lambda client: INNERTUBE_CLIENTS[client]['priority'], reverse=True)
  3440. for client in self._configuration_arg('player_client'):
  3441. if client == 'default':
  3442. requested_clients.extend(default)
  3443. elif client == 'all':
  3444. requested_clients.extend(allowed_clients)
  3445. elif client not in allowed_clients:
  3446. self.report_warning(f'Skipping unsupported client {client}')
  3447. elif client.startswith('android'):
  3448. android_clients.append(client)
  3449. else:
  3450. requested_clients.append(client)
  3451. # Force deprioritization of broken Android clients for format de-duplication
  3452. requested_clients.extend(android_clients)
  3453. if not requested_clients:
  3454. requested_clients = default
  3455. if smuggled_data.get('is_music_url') or self.is_music_url(url):
  3456. requested_clients.extend(
  3457. f'{client}_music' for client in requested_clients if f'{client}_music' in INNERTUBE_CLIENTS)
  3458. return orderedSet(requested_clients)
  3459. def _invalid_player_response(self, pr, video_id):
  3460. # YouTube may return a different video player response than expected.
  3461. # See: https://github.com/TeamNewPipe/NewPipe/issues/8713
  3462. if (pr_id := traverse_obj(pr, ('videoDetails', 'videoId'))) != video_id:
  3463. return pr_id
  3464. def _extract_player_responses(self, clients, video_id, webpage, master_ytcfg, smuggled_data):
  3465. initial_pr = None
  3466. if webpage:
  3467. initial_pr = self._search_json(
  3468. self._YT_INITIAL_PLAYER_RESPONSE_RE, webpage, 'initial player response', video_id, fatal=False)
  3469. prs = []
  3470. if initial_pr and not self._invalid_player_response(initial_pr, video_id):
  3471. # Android player_response does not have microFormats which are needed for
  3472. # extraction of some data. So we return the initial_pr with formats
  3473. # stripped out even if not requested by the user
  3474. # See: https://github.com/yt-dlp/yt-dlp/issues/501
  3475. prs.append({**initial_pr, 'streamingData': None})
  3476. all_clients = set(clients)
  3477. clients = clients[::-1]
  3478. def append_client(*client_names):
  3479. """ Append the first client name that exists but not already used """
  3480. for client_name in client_names:
  3481. actual_client = _split_innertube_client(client_name)[0]
  3482. if actual_client in INNERTUBE_CLIENTS:
  3483. if actual_client not in all_clients:
  3484. clients.append(client_name)
  3485. all_clients.add(actual_client)
  3486. return
  3487. tried_iframe_fallback = False
  3488. player_url = None
  3489. skipped_clients = {}
  3490. while clients:
  3491. client, base_client, variant = _split_innertube_client(clients.pop())
  3492. player_ytcfg = master_ytcfg if client == 'web' else {}
  3493. if 'configs' not in self._configuration_arg('player_skip') and client != 'web':
  3494. player_ytcfg = self._download_ytcfg(client, video_id) or player_ytcfg
  3495. player_url = player_url or self._extract_player_url(master_ytcfg, player_ytcfg, webpage=webpage)
  3496. require_js_player = self._get_default_ytcfg(client).get('REQUIRE_JS_PLAYER')
  3497. if 'js' in self._configuration_arg('player_skip'):
  3498. require_js_player = False
  3499. player_url = None
  3500. if not player_url and not tried_iframe_fallback and require_js_player:
  3501. player_url = self._download_player_url(video_id)
  3502. tried_iframe_fallback = True
  3503. try:
  3504. pr = initial_pr if client == 'web' and initial_pr else self._extract_player_response(
  3505. client, video_id, player_ytcfg or master_ytcfg, player_ytcfg, player_url if require_js_player else None, initial_pr, smuggled_data)
  3506. except ExtractorError as e:
  3507. self.report_warning(e)
  3508. continue
  3509. if pr_id := self._invalid_player_response(pr, video_id):
  3510. skipped_clients[client] = pr_id
  3511. elif pr:
  3512. # Save client name for introspection later
  3513. name = short_client_name(client)
  3514. sd = traverse_obj(pr, ('streamingData', {dict})) or {}
  3515. sd[STREAMING_DATA_CLIENT_NAME] = name
  3516. for f in traverse_obj(sd, (('formats', 'adaptiveFormats'), ..., {dict})):
  3517. f[STREAMING_DATA_CLIENT_NAME] = name
  3518. prs.append(pr)
  3519. # creator clients can bypass AGE_VERIFICATION_REQUIRED if logged in
  3520. if variant == 'embedded' and self._is_unplayable(pr) and self.is_authenticated:
  3521. append_client(f'{base_client}_creator')
  3522. elif self._is_agegated(pr):
  3523. if variant == 'tv_embedded':
  3524. append_client(f'{base_client}_embedded')
  3525. elif not variant:
  3526. append_client(f'tv_embedded.{base_client}', f'{base_client}_embedded')
  3527. if skipped_clients:
  3528. self.report_warning(
  3529. f'Skipping player responses from {"/".join(skipped_clients)} clients '
  3530. f'(got player responses for video "{"/".join(set(skipped_clients.values()))}" instead of "{video_id}")')
  3531. if not prs:
  3532. raise ExtractorError(
  3533. 'All player responses are invalid. Your IP is likely being blocked by Youtube', expected=True)
  3534. elif not prs:
  3535. raise ExtractorError('Failed to extract any player response')
  3536. return prs, player_url
  3537. def _needs_live_processing(self, live_status, duration):
  3538. if (live_status == 'is_live' and self.get_param('live_from_start')
  3539. or live_status == 'post_live' and (duration or 0) > 2 * 3600):
  3540. return live_status
  3541. def _extract_formats_and_subtitles(self, streaming_data, video_id, player_url, live_status, duration):
  3542. CHUNK_SIZE = 10 << 20
  3543. PREFERRED_LANG_VALUE = 10
  3544. original_language = None
  3545. itags, stream_ids = collections.defaultdict(set), []
  3546. itag_qualities, res_qualities = {}, {0: None}
  3547. q = qualities([
  3548. # Normally tiny is the smallest video-only formats. But
  3549. # audio-only formats with unknown quality may get tagged as tiny
  3550. 'tiny',
  3551. 'audio_quality_ultralow', 'audio_quality_low', 'audio_quality_medium', 'audio_quality_high', # Audio only formats
  3552. 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres',
  3553. ])
  3554. streaming_formats = traverse_obj(streaming_data, (..., ('formats', 'adaptiveFormats'), ...))
  3555. format_types = self._configuration_arg('formats')
  3556. all_formats = 'duplicate' in format_types
  3557. if self._configuration_arg('include_duplicate_formats'):
  3558. all_formats = True
  3559. self._downloader.deprecated_feature('[youtube] include_duplicate_formats extractor argument is deprecated. '
  3560. 'Use formats=duplicate extractor argument instead')
  3561. def build_fragments(f):
  3562. return LazyList({
  3563. 'url': update_url_query(f['url'], {
  3564. 'range': f'{range_start}-{min(range_start + CHUNK_SIZE - 1, f["filesize"])}',
  3565. }),
  3566. } for range_start in range(0, f['filesize'], CHUNK_SIZE))
  3567. for fmt in streaming_formats:
  3568. if fmt.get('targetDurationSec'):
  3569. continue
  3570. itag = str_or_none(fmt.get('itag'))
  3571. audio_track = fmt.get('audioTrack') or {}
  3572. stream_id = (itag, audio_track.get('id'), fmt.get('isDrc'))
  3573. if not all_formats:
  3574. if stream_id in stream_ids:
  3575. continue
  3576. quality = fmt.get('quality')
  3577. height = int_or_none(fmt.get('height'))
  3578. if quality == 'tiny' or not quality:
  3579. quality = fmt.get('audioQuality', '').lower() or quality
  3580. # The 3gp format (17) in android client has a quality of "small",
  3581. # but is actually worse than other formats
  3582. if itag == '17':
  3583. quality = 'tiny'
  3584. if quality:
  3585. if itag:
  3586. itag_qualities[itag] = quality
  3587. if height:
  3588. res_qualities[height] = quality
  3589. is_default = audio_track.get('audioIsDefault')
  3590. is_descriptive = 'descriptive' in (audio_track.get('displayName') or '').lower()
  3591. language_code = audio_track.get('id', '').split('.')[0]
  3592. if language_code and is_default:
  3593. original_language = language_code
  3594. # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
  3595. # (adding `&sq=0` to the URL) and parsing emsg box to determine the
  3596. # number of fragment that would subsequently requested with (`&sq=N`)
  3597. if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
  3598. continue
  3599. fmt_url = fmt.get('url')
  3600. if not fmt_url:
  3601. sc = urllib.parse.parse_qs(fmt.get('signatureCipher'))
  3602. fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
  3603. encrypted_sig = try_get(sc, lambda x: x['s'][0])
  3604. if not all((sc, fmt_url, player_url, encrypted_sig)):
  3605. continue
  3606. try:
  3607. fmt_url += '&{}={}'.format(
  3608. traverse_obj(sc, ('sp', -1)) or 'signature',
  3609. self._decrypt_signature(encrypted_sig, video_id, player_url),
  3610. )
  3611. except ExtractorError as e:
  3612. self.report_warning('Signature extraction failed: Some formats may be missing',
  3613. video_id=video_id, only_once=True)
  3614. self.write_debug(e, only_once=True)
  3615. continue
  3616. query = parse_qs(fmt_url)
  3617. if query.get('n'):
  3618. try:
  3619. decrypt_nsig = self._cached(self._decrypt_nsig, 'nsig', query['n'][0])
  3620. fmt_url = update_url_query(fmt_url, {
  3621. 'n': decrypt_nsig(query['n'][0], video_id, player_url),
  3622. })
  3623. except ExtractorError as e:
  3624. phantomjs_hint = ''
  3625. if isinstance(e, JSInterpreter.Exception):
  3626. phantomjs_hint = (f' Install {self._downloader._format_err("PhantomJS", self._downloader.Styles.EMPHASIS)} '
  3627. f'to workaround the issue. {PhantomJSwrapper.INSTALL_HINT}\n')
  3628. if player_url:
  3629. self.report_warning(
  3630. f'nsig extraction failed: Some formats may be missing\n{phantomjs_hint}'
  3631. f' n = {query["n"][0]} ; player = {player_url}', video_id=video_id, only_once=True)
  3632. self.write_debug(e, only_once=True)
  3633. else:
  3634. self.report_warning(
  3635. 'Cannot decrypt nsig without player_url: Some formats may be missing',
  3636. video_id=video_id, only_once=True)
  3637. continue
  3638. tbr = float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
  3639. format_duration = traverse_obj(fmt, ('approxDurationMs', {lambda x: float_or_none(x, 1000)}))
  3640. # Some formats may have much smaller duration than others (possibly damaged during encoding)
  3641. # E.g. 2-nOtRESiUc Ref: https://github.com/yt-dlp/yt-dlp/issues/2823
  3642. # Make sure to avoid false positives with small duration differences.
  3643. # E.g. __2ABJjxzNo, ySuUZEjARPY
  3644. is_damaged = try_call(lambda: format_duration < duration // 2)
  3645. if is_damaged:
  3646. self.report_warning(
  3647. f'{video_id}: Some formats are possibly damaged. They will be deprioritized', only_once=True)
  3648. client_name = fmt.get(STREAMING_DATA_CLIENT_NAME)
  3649. # Android client formats are broken due to integrity check enforcement
  3650. # Ref: https://github.com/yt-dlp/yt-dlp/issues/9554
  3651. is_broken = client_name and client_name.startswith(short_client_name('android'))
  3652. if is_broken:
  3653. self.report_warning(
  3654. f'{video_id}: Android client formats are broken and may yield HTTP Error 403. '
  3655. 'They will be deprioritized', only_once=True)
  3656. name = fmt.get('qualityLabel') or quality.replace('audio_quality_', '') or ''
  3657. fps = int_or_none(fmt.get('fps')) or 0
  3658. dct = {
  3659. 'asr': int_or_none(fmt.get('audioSampleRate')),
  3660. 'filesize': int_or_none(fmt.get('contentLength')),
  3661. 'format_id': f'{itag}{"-drc" if fmt.get("isDrc") else ""}',
  3662. 'format_note': join_nonempty(
  3663. join_nonempty(audio_track.get('displayName'), is_default and ' (default)', delim=''),
  3664. name, fmt.get('isDrc') and 'DRC',
  3665. try_get(fmt, lambda x: x['projectionType'].replace('RECTANGULAR', '').lower()),
  3666. try_get(fmt, lambda x: x['spatialAudioType'].replace('SPATIAL_AUDIO_TYPE_', '').lower()),
  3667. is_damaged and 'DAMAGED', is_broken and 'BROKEN',
  3668. (self.get_param('verbose') or all_formats) and client_name,
  3669. delim=', '),
  3670. # Format 22 is likely to be damaged. See https://github.com/yt-dlp/yt-dlp/issues/3372
  3671. 'source_preference': (-5 if itag == '22' else -1) + (100 if 'Premium' in name else 0),
  3672. 'fps': fps if fps > 1 else None, # For some formats, fps is wrongly returned as 1
  3673. 'audio_channels': fmt.get('audioChannels'),
  3674. 'height': height,
  3675. 'quality': q(quality) - bool(fmt.get('isDrc')) / 2,
  3676. 'has_drm': bool(fmt.get('drmFamilies')),
  3677. 'tbr': tbr,
  3678. 'filesize_approx': filesize_from_tbr(tbr, format_duration),
  3679. 'url': fmt_url,
  3680. 'width': int_or_none(fmt.get('width')),
  3681. 'language': join_nonempty(language_code, 'desc' if is_descriptive else '') or None,
  3682. 'language_preference': PREFERRED_LANG_VALUE if is_default else -10 if is_descriptive else -1,
  3683. # Strictly de-prioritize broken, damaged and 3gp formats
  3684. 'preference': -20 if is_broken else -10 if is_damaged else -2 if itag == '17' else None,
  3685. }
  3686. mime_mobj = re.match(
  3687. r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', fmt.get('mimeType') or '')
  3688. if mime_mobj:
  3689. dct['ext'] = mimetype2ext(mime_mobj.group(1))
  3690. dct.update(parse_codecs(mime_mobj.group(2)))
  3691. if itag:
  3692. itags[itag].add(('https', dct.get('language')))
  3693. stream_ids.append(stream_id)
  3694. single_stream = 'none' in (dct.get('acodec'), dct.get('vcodec'))
  3695. if single_stream and dct.get('ext'):
  3696. dct['container'] = dct['ext'] + '_dash'
  3697. if (all_formats or 'dashy' in format_types) and dct['filesize']:
  3698. yield {
  3699. **dct,
  3700. 'format_id': f'{dct["format_id"]}-dashy' if all_formats else dct['format_id'],
  3701. 'protocol': 'http_dash_segments',
  3702. 'fragments': build_fragments(dct),
  3703. }
  3704. if all_formats or 'dashy' not in format_types:
  3705. dct['downloader_options'] = {'http_chunk_size': CHUNK_SIZE}
  3706. yield dct
  3707. needs_live_processing = self._needs_live_processing(live_status, duration)
  3708. skip_bad_formats = 'incomplete' not in format_types
  3709. if self._configuration_arg('include_incomplete_formats'):
  3710. skip_bad_formats = False
  3711. self._downloader.deprecated_feature('[youtube] include_incomplete_formats extractor argument is deprecated. '
  3712. 'Use formats=incomplete extractor argument instead')
  3713. skip_manifests = set(self._configuration_arg('skip'))
  3714. if (not self.get_param('youtube_include_hls_manifest', True)
  3715. or needs_live_processing == 'is_live' # These will be filtered out by YoutubeDL anyway
  3716. or needs_live_processing and skip_bad_formats):
  3717. skip_manifests.add('hls')
  3718. if not self.get_param('youtube_include_dash_manifest', True):
  3719. skip_manifests.add('dash')
  3720. if self._configuration_arg('include_live_dash'):
  3721. self._downloader.deprecated_feature('[youtube] include_live_dash extractor argument is deprecated. '
  3722. 'Use formats=incomplete extractor argument instead')
  3723. elif skip_bad_formats and live_status == 'is_live' and needs_live_processing != 'is_live':
  3724. skip_manifests.add('dash')
  3725. def process_manifest_format(f, proto, client_name, itag):
  3726. key = (proto, f.get('language'))
  3727. if not all_formats and key in itags[itag]:
  3728. return False
  3729. itags[itag].add(key)
  3730. if itag and all_formats:
  3731. f['format_id'] = f'{itag}-{proto}'
  3732. elif any(p != proto for p, _ in itags[itag]):
  3733. f['format_id'] = f'{itag}-{proto}'
  3734. elif itag:
  3735. f['format_id'] = itag
  3736. if original_language and f.get('language') == original_language:
  3737. f['format_note'] = join_nonempty(f.get('format_note'), '(default)', delim=' ')
  3738. f['language_preference'] = PREFERRED_LANG_VALUE
  3739. if f.get('source_preference') is None:
  3740. f['source_preference'] = -1
  3741. if itag in ('616', '235'):
  3742. f['format_note'] = join_nonempty(f.get('format_note'), 'Premium', delim=' ')
  3743. f['source_preference'] += 100
  3744. f['quality'] = q(itag_qualities.get(try_get(f, lambda f: f['format_id'].split('-')[0]), -1))
  3745. if f['quality'] == -1 and f.get('height'):
  3746. f['quality'] = q(res_qualities[min(res_qualities, key=lambda x: abs(x - f['height']))])
  3747. if self.get_param('verbose') or all_formats:
  3748. f['format_note'] = join_nonempty(f.get('format_note'), client_name, delim=', ')
  3749. if f.get('fps') and f['fps'] <= 1:
  3750. del f['fps']
  3751. if proto == 'hls' and f.get('has_drm'):
  3752. f['has_drm'] = 'maybe'
  3753. f['source_preference'] -= 5
  3754. return True
  3755. subtitles = {}
  3756. for sd in streaming_data:
  3757. client_name = sd.get(STREAMING_DATA_CLIENT_NAME)
  3758. hls_manifest_url = 'hls' not in skip_manifests and sd.get('hlsManifestUrl')
  3759. if hls_manifest_url:
  3760. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  3761. hls_manifest_url, video_id, 'mp4', fatal=False, live=live_status == 'is_live')
  3762. subtitles = self._merge_subtitles(subs, subtitles)
  3763. for f in fmts:
  3764. if process_manifest_format(f, 'hls', client_name, self._search_regex(
  3765. r'/itag/(\d+)', f['url'], 'itag', default=None)):
  3766. yield f
  3767. dash_manifest_url = 'dash' not in skip_manifests and sd.get('dashManifestUrl')
  3768. if dash_manifest_url:
  3769. formats, subs = self._extract_mpd_formats_and_subtitles(dash_manifest_url, video_id, fatal=False)
  3770. subtitles = self._merge_subtitles(subs, subtitles) # Prioritize HLS subs over DASH
  3771. for f in formats:
  3772. if process_manifest_format(f, 'dash', client_name, f['format_id']):
  3773. f['filesize'] = int_or_none(self._search_regex(
  3774. r'/clen/(\d+)', f.get('fragment_base_url') or f['url'], 'file size', default=None))
  3775. if needs_live_processing:
  3776. f['is_from_start'] = True
  3777. yield f
  3778. yield subtitles
  3779. def _extract_storyboard(self, player_responses, duration):
  3780. spec = get_first(
  3781. player_responses, ('storyboards', 'playerStoryboardSpecRenderer', 'spec'), default='').split('|')[::-1]
  3782. base_url = url_or_none(urljoin('https://i.ytimg.com/', spec.pop() or None))
  3783. if not base_url:
  3784. return
  3785. L = len(spec) - 1
  3786. for i, args in enumerate(spec):
  3787. args = args.split('#')
  3788. counts = list(map(int_or_none, args[:5]))
  3789. if len(args) != 8 or not all(counts):
  3790. self.report_warning(f'Malformed storyboard {i}: {"#".join(args)}{bug_reports_message()}')
  3791. continue
  3792. width, height, frame_count, cols, rows = counts
  3793. N, sigh = args[6:]
  3794. url = base_url.replace('$L', str(L - i)).replace('$N', N) + f'&sigh={sigh}'
  3795. fragment_count = frame_count / (cols * rows)
  3796. fragment_duration = duration / fragment_count
  3797. yield {
  3798. 'format_id': f'sb{i}',
  3799. 'format_note': 'storyboard',
  3800. 'ext': 'mhtml',
  3801. 'protocol': 'mhtml',
  3802. 'acodec': 'none',
  3803. 'vcodec': 'none',
  3804. 'url': url,
  3805. 'width': width,
  3806. 'height': height,
  3807. 'fps': frame_count / duration,
  3808. 'rows': rows,
  3809. 'columns': cols,
  3810. 'fragments': [{
  3811. 'url': url.replace('$M', str(j)),
  3812. 'duration': min(fragment_duration, duration - (j * fragment_duration)),
  3813. } for j in range(math.ceil(fragment_count))],
  3814. }
  3815. def _download_player_responses(self, url, smuggled_data, video_id, webpage_url):
  3816. webpage = None
  3817. if 'webpage' not in self._configuration_arg('player_skip'):
  3818. query = {'bpctr': '9999999999', 'has_verified': '1'}
  3819. pp = self._configuration_arg('player_params', [None], casesense=True)[0]
  3820. if pp:
  3821. query['pp'] = pp
  3822. webpage = self._download_webpage(
  3823. webpage_url, video_id, fatal=False, query=query)
  3824. master_ytcfg = self.extract_ytcfg(video_id, webpage) or self._get_default_ytcfg()
  3825. player_responses, player_url = self._extract_player_responses(
  3826. self._get_requested_clients(url, smuggled_data),
  3827. video_id, webpage, master_ytcfg, smuggled_data)
  3828. return webpage, master_ytcfg, player_responses, player_url
  3829. def _list_formats(self, video_id, microformats, video_details, player_responses, player_url, duration=None):
  3830. live_broadcast_details = traverse_obj(microformats, (..., 'liveBroadcastDetails'))
  3831. is_live = get_first(video_details, 'isLive')
  3832. if is_live is None:
  3833. is_live = get_first(live_broadcast_details, 'isLiveNow')
  3834. live_content = get_first(video_details, 'isLiveContent')
  3835. is_upcoming = get_first(video_details, 'isUpcoming')
  3836. post_live = get_first(video_details, 'isPostLiveDvr')
  3837. live_status = ('post_live' if post_live
  3838. else 'is_live' if is_live
  3839. else 'is_upcoming' if is_upcoming
  3840. else 'was_live' if live_content
  3841. else 'not_live' if False in (is_live, live_content)
  3842. else None)
  3843. streaming_data = traverse_obj(player_responses, (..., 'streamingData'))
  3844. *formats, subtitles = self._extract_formats_and_subtitles(streaming_data, video_id, player_url, live_status, duration)
  3845. if all(f.get('has_drm') for f in formats):
  3846. # If there are no formats that definitely don't have DRM, all have DRM
  3847. for f in formats:
  3848. f['has_drm'] = True
  3849. return live_broadcast_details, live_status, streaming_data, formats, subtitles
  3850. def _real_extract(self, url):
  3851. url, smuggled_data = unsmuggle_url(url, {})
  3852. video_id = self._match_id(url)
  3853. base_url = self.http_scheme() + '//www.youtube.com/'
  3854. webpage_url = base_url + 'watch?v=' + video_id
  3855. webpage, master_ytcfg, player_responses, player_url = self._download_player_responses(url, smuggled_data, video_id, webpage_url)
  3856. playability_statuses = traverse_obj(
  3857. player_responses, (..., 'playabilityStatus'), expected_type=dict)
  3858. trailer_video_id = get_first(
  3859. playability_statuses,
  3860. ('errorScreen', 'playerLegacyDesktopYpcTrailerRenderer', 'trailerVideoId'),
  3861. expected_type=str)
  3862. if trailer_video_id:
  3863. return self.url_result(
  3864. trailer_video_id, self.ie_key(), trailer_video_id)
  3865. search_meta = ((lambda x: self._html_search_meta(x, webpage, default=None))
  3866. if webpage else (lambda x: None))
  3867. video_details = traverse_obj(player_responses, (..., 'videoDetails'), expected_type=dict)
  3868. microformats = traverse_obj(
  3869. player_responses, (..., 'microformat', 'playerMicroformatRenderer'),
  3870. expected_type=dict)
  3871. translated_title = self._get_text(microformats, (..., 'title'))
  3872. video_title = (self._preferred_lang and translated_title
  3873. or get_first(video_details, 'title') # primary
  3874. or translated_title
  3875. or search_meta(['og:title', 'twitter:title', 'title']))
  3876. translated_description = self._get_text(microformats, (..., 'description'))
  3877. original_description = get_first(video_details, 'shortDescription')
  3878. video_description = (
  3879. self._preferred_lang and translated_description
  3880. # If original description is blank, it will be an empty string.
  3881. # Do not prefer translated description in this case.
  3882. or original_description if original_description is not None else translated_description)
  3883. multifeed_metadata_list = get_first(
  3884. player_responses,
  3885. ('multicamera', 'playerLegacyMulticameraRenderer', 'metadataList'),
  3886. expected_type=str)
  3887. if multifeed_metadata_list and not smuggled_data.get('force_singlefeed'):
  3888. if self.get_param('noplaylist'):
  3889. self.to_screen(f'Downloading just video {video_id} because of --no-playlist')
  3890. else:
  3891. entries = []
  3892. feed_ids = []
  3893. for feed in multifeed_metadata_list.split(','):
  3894. # Unquote should take place before split on comma (,) since textual
  3895. # fields may contain comma as well (see
  3896. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  3897. feed_data = urllib.parse.parse_qs(
  3898. urllib.parse.unquote_plus(feed))
  3899. def feed_entry(name):
  3900. return try_get(
  3901. feed_data, lambda x: x[name][0], str)
  3902. feed_id = feed_entry('id')
  3903. if not feed_id:
  3904. continue
  3905. feed_title = feed_entry('title')
  3906. title = video_title
  3907. if feed_title:
  3908. title += f' ({feed_title})'
  3909. entries.append({
  3910. '_type': 'url_transparent',
  3911. 'ie_key': 'Youtube',
  3912. 'url': smuggle_url(
  3913. '{}watch?v={}'.format(base_url, feed_data['id'][0]),
  3914. {'force_singlefeed': True}),
  3915. 'title': title,
  3916. })
  3917. feed_ids.append(feed_id)
  3918. self.to_screen(
  3919. 'Downloading multifeed video ({}) - add --no-playlist to just download video {}'.format(
  3920. ', '.join(feed_ids), video_id))
  3921. return self.playlist_result(
  3922. entries, video_id, video_title, video_description)
  3923. duration = (int_or_none(get_first(video_details, 'lengthSeconds'))
  3924. or int_or_none(get_first(microformats, 'lengthSeconds'))
  3925. or parse_duration(search_meta('duration')) or None)
  3926. live_broadcast_details, live_status, streaming_data, formats, automatic_captions = \
  3927. self._list_formats(video_id, microformats, video_details, player_responses, player_url, duration)
  3928. if live_status == 'post_live':
  3929. self.write_debug(f'{video_id}: Video is in Post-Live Manifestless mode')
  3930. if not formats:
  3931. if not self.get_param('allow_unplayable_formats') and traverse_obj(streaming_data, (..., 'licenseInfos')):
  3932. self.report_drm(video_id)
  3933. pemr = get_first(
  3934. playability_statuses,
  3935. ('errorScreen', 'playerErrorMessageRenderer'), expected_type=dict) or {}
  3936. reason = self._get_text(pemr, 'reason') or get_first(playability_statuses, 'reason')
  3937. subreason = clean_html(self._get_text(pemr, 'subreason') or '')
  3938. if subreason:
  3939. if subreason == 'The uploader has not made this video available in your country.':
  3940. countries = get_first(microformats, 'availableCountries')
  3941. if not countries:
  3942. regions_allowed = search_meta('regionsAllowed')
  3943. countries = regions_allowed.split(',') if regions_allowed else None
  3944. self.raise_geo_restricted(subreason, countries, metadata_available=True)
  3945. reason += f'. {subreason}'
  3946. if reason:
  3947. self.raise_no_formats(reason, expected=True)
  3948. keywords = get_first(video_details, 'keywords', expected_type=list) or []
  3949. if not keywords and webpage:
  3950. keywords = [
  3951. unescapeHTML(m.group('content'))
  3952. for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
  3953. for keyword in keywords:
  3954. if keyword.startswith('yt:stretch='):
  3955. mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
  3956. if mobj:
  3957. # NB: float is intentional for forcing float division
  3958. w, h = (float(v) for v in mobj.groups())
  3959. if w > 0 and h > 0:
  3960. ratio = w / h
  3961. for f in formats:
  3962. if f.get('vcodec') != 'none':
  3963. f['stretched_ratio'] = ratio
  3964. break
  3965. thumbnails = self._extract_thumbnails((video_details, microformats), (..., ..., 'thumbnail'))
  3966. thumbnail_url = search_meta(['og:image', 'twitter:image'])
  3967. if thumbnail_url:
  3968. thumbnails.append({
  3969. 'url': thumbnail_url,
  3970. })
  3971. original_thumbnails = thumbnails.copy()
  3972. # The best resolution thumbnails sometimes does not appear in the webpage
  3973. # See: https://github.com/yt-dlp/yt-dlp/issues/340
  3974. # List of possible thumbnails - Ref: <https://stackoverflow.com/a/20542029>
  3975. thumbnail_names = [
  3976. # While the *1,*2,*3 thumbnails are just below their corresponding "*default" variants
  3977. # in resolution, these are not the custom thumbnail. So de-prioritize them
  3978. 'maxresdefault', 'hq720', 'sddefault', 'hqdefault', '0', 'mqdefault', 'default',
  3979. 'sd1', 'sd2', 'sd3', 'hq1', 'hq2', 'hq3', 'mq1', 'mq2', 'mq3', '1', '2', '3',
  3980. ]
  3981. n_thumbnail_names = len(thumbnail_names)
  3982. thumbnails.extend({
  3983. 'url': 'https://i.ytimg.com/vi{webp}/{video_id}/{name}{live}.{ext}'.format(
  3984. video_id=video_id, name=name, ext=ext,
  3985. webp='_webp' if ext == 'webp' else '', live='_live' if live_status == 'is_live' else ''),
  3986. } for name in thumbnail_names for ext in ('webp', 'jpg'))
  3987. for thumb in thumbnails:
  3988. i = next((i for i, t in enumerate(thumbnail_names) if f'/{video_id}/{t}' in thumb['url']), n_thumbnail_names)
  3989. thumb['preference'] = (0 if '.webp' in thumb['url'] else -1) - (2 * i)
  3990. self._remove_duplicate_formats(thumbnails)
  3991. self._downloader._sort_thumbnails(original_thumbnails)
  3992. category = get_first(microformats, 'category') or search_meta('genre')
  3993. channel_id = self.ucid_or_none(str_or_none(
  3994. get_first(video_details, 'channelId')
  3995. or get_first(microformats, 'externalChannelId')
  3996. or search_meta('channelId')))
  3997. owner_profile_url = get_first(microformats, 'ownerProfileUrl')
  3998. live_start_time = parse_iso8601(get_first(live_broadcast_details, 'startTimestamp'))
  3999. live_end_time = parse_iso8601(get_first(live_broadcast_details, 'endTimestamp'))
  4000. if not duration and live_end_time and live_start_time:
  4001. duration = live_end_time - live_start_time
  4002. needs_live_processing = self._needs_live_processing(live_status, duration)
  4003. def is_bad_format(fmt):
  4004. if needs_live_processing and not fmt.get('is_from_start'):
  4005. return True
  4006. elif (live_status == 'is_live' and needs_live_processing != 'is_live'
  4007. and fmt.get('protocol') == 'http_dash_segments'):
  4008. return True
  4009. for fmt in filter(is_bad_format, formats):
  4010. fmt['preference'] = (fmt.get('preference') or -1) - 10
  4011. fmt['format_note'] = join_nonempty(fmt.get('format_note'), '(Last 2 hours)', delim=' ')
  4012. if needs_live_processing:
  4013. self._prepare_live_from_start_formats(
  4014. formats, video_id, live_start_time, url, webpage_url, smuggled_data, live_status == 'is_live')
  4015. formats.extend(self._extract_storyboard(player_responses, duration))
  4016. channel_handle = self.handle_from_url(owner_profile_url)
  4017. info = {
  4018. 'id': video_id,
  4019. 'title': video_title,
  4020. 'formats': formats,
  4021. 'thumbnails': thumbnails,
  4022. # The best thumbnail that we are sure exists. Prevents unnecessary
  4023. # URL checking if user don't care about getting the best possible thumbnail
  4024. 'thumbnail': traverse_obj(original_thumbnails, (-1, 'url')),
  4025. 'description': video_description,
  4026. 'channel_id': channel_id,
  4027. 'channel_url': format_field(channel_id, None, 'https://www.youtube.com/channel/%s', default=None),
  4028. 'duration': duration,
  4029. 'view_count': int_or_none(
  4030. get_first((video_details, microformats), (..., 'viewCount'))
  4031. or search_meta('interactionCount')),
  4032. 'average_rating': float_or_none(get_first(video_details, 'averageRating')),
  4033. 'age_limit': 18 if (
  4034. get_first(microformats, 'isFamilySafe') is False
  4035. or search_meta('isFamilyFriendly') == 'false'
  4036. or search_meta('og:restrictions:age') == '18+') else 0,
  4037. 'webpage_url': webpage_url,
  4038. 'categories': [category] if category else None,
  4039. 'tags': keywords,
  4040. 'playable_in_embed': get_first(playability_statuses, 'playableInEmbed'),
  4041. 'live_status': live_status,
  4042. 'release_timestamp': live_start_time,
  4043. '_format_sort_fields': ( # source_preference is lower for potentially damaged formats
  4044. 'quality', 'res', 'fps', 'hdr:12', 'source', 'vcodec:vp9.2', 'channels', 'acodec', 'lang', 'proto'),
  4045. }
  4046. subtitles = {}
  4047. pctr = traverse_obj(player_responses, (..., 'captions', 'playerCaptionsTracklistRenderer'), expected_type=dict)
  4048. if pctr:
  4049. def get_lang_code(track):
  4050. return (remove_start(track.get('vssId') or '', '.').replace('.', '-')
  4051. or track.get('languageCode'))
  4052. # Converted into dicts to remove duplicates
  4053. captions = {
  4054. get_lang_code(sub): sub
  4055. for sub in traverse_obj(pctr, (..., 'captionTracks', ...))}
  4056. translation_languages = {
  4057. lang.get('languageCode'): self._get_text(lang.get('languageName'), max_runs=1)
  4058. for lang in traverse_obj(pctr, (..., 'translationLanguages', ...))}
  4059. def process_language(container, base_url, lang_code, sub_name, query):
  4060. lang_subs = container.setdefault(lang_code, [])
  4061. for fmt in self._SUBTITLE_FORMATS:
  4062. query.update({
  4063. 'fmt': fmt,
  4064. })
  4065. lang_subs.append({
  4066. 'ext': fmt,
  4067. 'url': urljoin('https://www.youtube.com', update_url_query(base_url, query)),
  4068. 'name': sub_name,
  4069. })
  4070. # NB: Constructing the full subtitle dictionary is slow
  4071. get_translated_subs = 'translated_subs' not in self._configuration_arg('skip') and (
  4072. self.get_param('writeautomaticsub', False) or self.get_param('listsubtitles'))
  4073. for lang_code, caption_track in captions.items():
  4074. base_url = caption_track.get('baseUrl')
  4075. orig_lang = parse_qs(base_url).get('lang', [None])[-1]
  4076. if not base_url:
  4077. continue
  4078. lang_name = self._get_text(caption_track, 'name', max_runs=1)
  4079. if caption_track.get('kind') != 'asr':
  4080. if not lang_code:
  4081. continue
  4082. process_language(
  4083. subtitles, base_url, lang_code, lang_name, {})
  4084. if not caption_track.get('isTranslatable'):
  4085. continue
  4086. for trans_code, trans_name in translation_languages.items():
  4087. if not trans_code:
  4088. continue
  4089. orig_trans_code = trans_code
  4090. if caption_track.get('kind') != 'asr' and trans_code != 'und':
  4091. if not get_translated_subs:
  4092. continue
  4093. trans_code += f'-{lang_code}'
  4094. trans_name += format_field(lang_name, None, ' from %s')
  4095. if lang_code == f'a-{orig_trans_code}':
  4096. # Set audio language based on original subtitles
  4097. for f in formats:
  4098. if f.get('acodec') != 'none' and not f.get('language'):
  4099. f['language'] = orig_trans_code
  4100. # Add an "-orig" label to the original language so that it can be distinguished.
  4101. # The subs are returned without "-orig" as well for compatibility
  4102. process_language(
  4103. automatic_captions, base_url, f'{trans_code}-orig', f'{trans_name} (Original)', {})
  4104. # Setting tlang=lang returns damaged subtitles.
  4105. process_language(automatic_captions, base_url, trans_code, trans_name,
  4106. {} if orig_lang == orig_trans_code else {'tlang': trans_code})
  4107. info['automatic_captions'] = automatic_captions
  4108. info['subtitles'] = subtitles
  4109. parsed_url = urllib.parse.urlparse(url)
  4110. for component in [parsed_url.fragment, parsed_url.query]:
  4111. query = urllib.parse.parse_qs(component)
  4112. for k, v in query.items():
  4113. for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
  4114. d_k += '_time'
  4115. if d_k not in info and k in s_ks:
  4116. info[d_k] = parse_duration(v[0])
  4117. # Youtube Music Auto-generated description
  4118. if (video_description or '').strip().endswith('\nAuto-generated by YouTube.'):
  4119. # XXX: Causes catastrophic backtracking if description has "·"
  4120. # E.g. https://www.youtube.com/watch?v=DoPaAxMQoiI
  4121. # Simulating atomic groups: (?P<a>[^xy]+)x => (?=(?P<a>[^xy]+))(?P=a)x
  4122. # reduces it, but does not fully fix it. https://regex101.com/r/8Ssf2h/2
  4123. mobj = re.search(
  4124. r'''(?xs)
  4125. (?=(?P<track>[^\n·]+))(?P=track)·
  4126. (?=(?P<artist>[^\n]+))(?P=artist)\n+
  4127. (?=(?P<album>[^\n]+))(?P=album)\n
  4128. (?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?
  4129. (?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?
  4130. (.+?\nArtist\s*:\s*
  4131. (?=(?P<clean_artist>[^\n]+))(?P=clean_artist)\n
  4132. )?.+\nAuto-generated\ by\ YouTube\.\s*$
  4133. ''', video_description)
  4134. if mobj:
  4135. release_year = mobj.group('release_year')
  4136. release_date = mobj.group('release_date')
  4137. if release_date:
  4138. release_date = release_date.replace('-', '')
  4139. if not release_year:
  4140. release_year = release_date[:4]
  4141. info.update({
  4142. 'album': mobj.group('album'.strip()),
  4143. 'artists': ([a] if (a := mobj.group('clean_artist'))
  4144. else [a.strip() for a in mobj.group('artist').split('·')]),
  4145. 'track': mobj.group('track').strip(),
  4146. 'release_date': release_date,
  4147. 'release_year': int_or_none(release_year),
  4148. })
  4149. initial_data = None
  4150. if webpage:
  4151. initial_data = self.extract_yt_initial_data(video_id, webpage, fatal=False)
  4152. if not traverse_obj(initial_data, 'contents'):
  4153. self.report_warning('Incomplete data received in embedded initial data; re-fetching using API.')
  4154. initial_data = None
  4155. if not initial_data:
  4156. query = {'videoId': video_id}
  4157. query.update(self._get_checkok_params())
  4158. initial_data = self._extract_response(
  4159. item_id=video_id, ep='next', fatal=False,
  4160. ytcfg=master_ytcfg, query=query, check_get_keys='contents',
  4161. headers=self.generate_api_headers(ytcfg=master_ytcfg),
  4162. note='Downloading initial data API JSON')
  4163. info['comment_count'] = traverse_obj(initial_data, (
  4164. 'contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents', ..., 'itemSectionRenderer',
  4165. 'contents', ..., 'commentsEntryPointHeaderRenderer', 'commentCount',
  4166. ), (
  4167. 'engagementPanels', lambda _, v: v['engagementPanelSectionListRenderer']['panelIdentifier'] == 'comment-item-section',
  4168. 'engagementPanelSectionListRenderer', 'header', 'engagementPanelTitleHeaderRenderer', 'contextualInfo',
  4169. ), expected_type=self._get_count, get_all=False)
  4170. try: # This will error if there is no livechat
  4171. initial_data['contents']['twoColumnWatchNextResults']['conversationBar']['liveChatRenderer']['continuations'][0]['reloadContinuationData']['continuation']
  4172. except (KeyError, IndexError, TypeError):
  4173. pass
  4174. else:
  4175. info.setdefault('subtitles', {})['live_chat'] = [{
  4176. # url is needed to set cookies
  4177. 'url': f'https://www.youtube.com/watch?v={video_id}&bpctr=9999999999&has_verified=1',
  4178. 'video_id': video_id,
  4179. 'ext': 'json',
  4180. 'protocol': ('youtube_live_chat' if live_status in ('is_live', 'is_upcoming')
  4181. else 'youtube_live_chat_replay'),
  4182. }]
  4183. if initial_data:
  4184. info['chapters'] = (
  4185. self._extract_chapters_from_json(initial_data, duration)
  4186. or self._extract_chapters_from_engagement_panel(initial_data, duration)
  4187. or self._extract_chapters_from_description(video_description, duration)
  4188. or None)
  4189. info['heatmap'] = self._extract_heatmap(initial_data)
  4190. contents = traverse_obj(
  4191. initial_data, ('contents', 'twoColumnWatchNextResults', 'results', 'results', 'contents'),
  4192. expected_type=list, default=[])
  4193. vpir = get_first(contents, 'videoPrimaryInfoRenderer')
  4194. if vpir:
  4195. stl = vpir.get('superTitleLink')
  4196. if stl:
  4197. stl = self._get_text(stl)
  4198. if try_get(
  4199. vpir,
  4200. lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
  4201. info['location'] = stl
  4202. else:
  4203. mobj = re.search(r'(.+?)\s*S(\d+)\s*•?\s*E(\d+)', stl)
  4204. if mobj:
  4205. info.update({
  4206. 'series': mobj.group(1),
  4207. 'season_number': int(mobj.group(2)),
  4208. 'episode_number': int(mobj.group(3)),
  4209. })
  4210. for tlb in (try_get(
  4211. vpir,
  4212. lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
  4213. list) or []):
  4214. tbrs = variadic(
  4215. traverse_obj(
  4216. tlb, ('toggleButtonRenderer', ...),
  4217. ('segmentedLikeDislikeButtonRenderer', ..., 'toggleButtonRenderer')))
  4218. for tbr in tbrs:
  4219. for getter, regex in [(
  4220. lambda x: x['defaultText']['accessibility']['accessibilityData'],
  4221. r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
  4222. lambda x: x['accessibility'],
  4223. lambda x: x['accessibilityData']['accessibilityData'],
  4224. ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
  4225. label = (try_get(tbr, getter, dict) or {}).get('label')
  4226. if label:
  4227. mobj = re.match(regex, label)
  4228. if mobj:
  4229. info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
  4230. break
  4231. info['like_count'] = traverse_obj(vpir, (
  4232. 'videoActions', 'menuRenderer', 'topLevelButtons', ...,
  4233. 'segmentedLikeDislikeButtonViewModel', 'likeButtonViewModel', 'likeButtonViewModel',
  4234. 'toggleButtonViewModel', 'toggleButtonViewModel', 'defaultButtonViewModel',
  4235. 'buttonViewModel', 'accessibilityText', {parse_count}), get_all=False)
  4236. vcr = traverse_obj(vpir, ('viewCount', 'videoViewCountRenderer'))
  4237. if vcr:
  4238. vc = self._get_count(vcr, 'viewCount')
  4239. # Upcoming premieres with waiting count are treated as live here
  4240. if vcr.get('isLive'):
  4241. info['concurrent_view_count'] = vc
  4242. elif info.get('view_count') is None:
  4243. info['view_count'] = vc
  4244. vsir = get_first(contents, 'videoSecondaryInfoRenderer')
  4245. if vsir:
  4246. vor = traverse_obj(vsir, ('owner', 'videoOwnerRenderer'))
  4247. info.update({
  4248. 'channel': self._get_text(vor, 'title'),
  4249. 'channel_follower_count': self._get_count(vor, 'subscriberCountText')})
  4250. if not channel_handle:
  4251. channel_handle = self.handle_from_url(
  4252. traverse_obj(vor, (
  4253. ('navigationEndpoint', ('title', 'runs', ..., 'navigationEndpoint')),
  4254. (('commandMetadata', 'webCommandMetadata', 'url'), ('browseEndpoint', 'canonicalBaseUrl')),
  4255. {str}), get_all=False))
  4256. rows = try_get(
  4257. vsir,
  4258. lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
  4259. list) or []
  4260. multiple_songs = False
  4261. for row in rows:
  4262. if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
  4263. multiple_songs = True
  4264. break
  4265. for row in rows:
  4266. mrr = row.get('metadataRowRenderer') or {}
  4267. mrr_title = mrr.get('title')
  4268. if not mrr_title:
  4269. continue
  4270. mrr_title = self._get_text(mrr, 'title')
  4271. mrr_contents_text = self._get_text(mrr, ('contents', 0))
  4272. if mrr_title == 'License':
  4273. info['license'] = mrr_contents_text
  4274. elif not multiple_songs:
  4275. if mrr_title == 'Album':
  4276. info['album'] = mrr_contents_text
  4277. elif mrr_title == 'Artist':
  4278. info['artists'] = [mrr_contents_text] if mrr_contents_text else None
  4279. elif mrr_title == 'Song':
  4280. info['track'] = mrr_contents_text
  4281. owner_badges = self._extract_badges(traverse_obj(vsir, ('owner', 'videoOwnerRenderer', 'badges')))
  4282. if self._has_badge(owner_badges, BadgeType.VERIFIED):
  4283. info['channel_is_verified'] = True
  4284. info.update({
  4285. 'uploader': info.get('channel'),
  4286. 'uploader_id': channel_handle,
  4287. 'uploader_url': format_field(channel_handle, None, 'https://www.youtube.com/%s', default=None),
  4288. })
  4289. # We only want timestamp IF it has time precision AND a timezone
  4290. # Currently the uploadDate in microformats appears to be in US/Pacific timezone.
  4291. timestamp = (
  4292. parse_iso8601(get_first(microformats, 'uploadDate'), timezone=NO_DEFAULT)
  4293. or parse_iso8601(search_meta('uploadDate'), timezone=NO_DEFAULT)
  4294. )
  4295. upload_date = (
  4296. dt.datetime.fromtimestamp(timestamp, dt.timezone.utc).strftime('%Y%m%d') if timestamp else
  4297. (
  4298. unified_strdate(get_first(microformats, 'uploadDate'))
  4299. or unified_strdate(search_meta('uploadDate'))
  4300. ))
  4301. # In the case we cannot get the timestamp:
  4302. # The upload date for scheduled, live and past live streams / premieres in microformats
  4303. # may be different from the stream date. Although not in UTC, we will prefer it in this case.
  4304. # See: https://github.com/yt-dlp/yt-dlp/pull/2223#issuecomment-1008485139
  4305. if not upload_date or (not timestamp and live_status in ('not_live', None)):
  4306. # this should be in UTC, as configured in the cookie/client context
  4307. upload_date = strftime_or_none(
  4308. self._parse_time_text(self._get_text(vpir, 'dateText'))) or upload_date
  4309. info['upload_date'] = upload_date
  4310. info['timestamp'] = timestamp
  4311. if upload_date and live_status not in ('is_live', 'post_live', 'is_upcoming'):
  4312. # Newly uploaded videos' HLS formats are potentially problematic and need to be checked
  4313. upload_datetime = datetime_from_str(upload_date).replace(tzinfo=dt.timezone.utc)
  4314. if upload_datetime >= datetime_from_str('today-2days'):
  4315. for fmt in info['formats']:
  4316. if fmt.get('protocol') == 'm3u8_native':
  4317. fmt['__needs_testing'] = True
  4318. for s_k, d_k in [('artists', 'creators'), ('track', 'alt_title')]:
  4319. v = info.get(s_k)
  4320. if v:
  4321. info[d_k] = v
  4322. badges = self._extract_badges(traverse_obj(vpir, 'badges'))
  4323. is_private = (self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE)
  4324. or get_first(video_details, 'isPrivate', expected_type=bool))
  4325. info['availability'] = (
  4326. 'public' if self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
  4327. else self._availability(
  4328. is_private=is_private,
  4329. needs_premium=(
  4330. self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM)
  4331. or False if initial_data and is_private is not None else None),
  4332. needs_subscription=(
  4333. self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION)
  4334. or False if initial_data and is_private is not None else None),
  4335. needs_auth=info['age_limit'] >= 18,
  4336. is_unlisted=None if is_private is None else (
  4337. self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED)
  4338. or get_first(microformats, 'isUnlisted', expected_type=bool))))
  4339. info['__post_extractor'] = self.extract_comments(master_ytcfg, video_id, contents, webpage)
  4340. self.mark_watched(video_id, player_responses)
  4341. return info
  4342. class YoutubeTabBaseInfoExtractor(YoutubeBaseInfoExtractor):
  4343. @staticmethod
  4344. def passthrough_smuggled_data(func):
  4345. def _smuggle(info, smuggled_data):
  4346. if info.get('_type') not in ('url', 'url_transparent'):
  4347. return info
  4348. if smuggled_data.get('is_music_url'):
  4349. parsed_url = urllib.parse.urlparse(info['url'])
  4350. if parsed_url.netloc in ('www.youtube.com', 'music.youtube.com'):
  4351. smuggled_data.pop('is_music_url')
  4352. info['url'] = urllib.parse.urlunparse(parsed_url._replace(netloc='music.youtube.com'))
  4353. if smuggled_data:
  4354. info['url'] = smuggle_url(info['url'], smuggled_data)
  4355. return info
  4356. @functools.wraps(func)
  4357. def wrapper(self, url):
  4358. url, smuggled_data = unsmuggle_url(url, {})
  4359. if self.is_music_url(url):
  4360. smuggled_data['is_music_url'] = True
  4361. info_dict = func(self, url, smuggled_data)
  4362. if smuggled_data:
  4363. _smuggle(info_dict, smuggled_data)
  4364. if info_dict.get('entries'):
  4365. info_dict['entries'] = (_smuggle(i, smuggled_data.copy()) for i in info_dict['entries'])
  4366. return info_dict
  4367. return wrapper
  4368. @staticmethod
  4369. def _extract_basic_item_renderer(item):
  4370. # Modified from _extract_grid_item_renderer
  4371. known_basic_renderers = (
  4372. 'playlistRenderer', 'videoRenderer', 'channelRenderer', 'showRenderer', 'reelItemRenderer',
  4373. )
  4374. for key, renderer in item.items():
  4375. if not isinstance(renderer, dict):
  4376. continue
  4377. elif key in known_basic_renderers:
  4378. return renderer
  4379. elif key.startswith('grid') and key.endswith('Renderer'):
  4380. return renderer
  4381. def _extract_channel_renderer(self, renderer):
  4382. channel_id = self.ucid_or_none(renderer['channelId'])
  4383. title = self._get_text(renderer, 'title')
  4384. channel_url = format_field(channel_id, None, 'https://www.youtube.com/channel/%s', default=None)
  4385. channel_handle = self.handle_from_url(
  4386. traverse_obj(renderer, (
  4387. 'navigationEndpoint', (('commandMetadata', 'webCommandMetadata', 'url'),
  4388. ('browseEndpoint', 'canonicalBaseUrl')),
  4389. {str}), get_all=False))
  4390. if not channel_handle:
  4391. # As of 2023-06-01, YouTube sets subscriberCountText to the handle in search
  4392. channel_handle = self.handle_or_none(self._get_text(renderer, 'subscriberCountText'))
  4393. return {
  4394. '_type': 'url',
  4395. 'url': channel_url,
  4396. 'id': channel_id,
  4397. 'ie_key': YoutubeTabIE.ie_key(),
  4398. 'channel': title,
  4399. 'uploader': title,
  4400. 'channel_id': channel_id,
  4401. 'channel_url': channel_url,
  4402. 'title': title,
  4403. 'uploader_id': channel_handle,
  4404. 'uploader_url': format_field(channel_handle, None, 'https://www.youtube.com/%s', default=None),
  4405. # See above. YouTube sets videoCountText to the subscriber text in search channel renderers.
  4406. # However, in feed/channels this is set correctly to the subscriber count
  4407. 'channel_follower_count': traverse_obj(
  4408. renderer, 'subscriberCountText', 'videoCountText', expected_type=self._get_count),
  4409. 'thumbnails': self._extract_thumbnails(renderer, 'thumbnail'),
  4410. 'playlist_count': (
  4411. # videoCountText may be the subscriber count
  4412. self._get_count(renderer, 'videoCountText')
  4413. if self._get_count(renderer, 'subscriberCountText') is not None else None),
  4414. 'description': self._get_text(renderer, 'descriptionSnippet'),
  4415. 'channel_is_verified': True if self._has_badge(
  4416. self._extract_badges(traverse_obj(renderer, 'ownerBadges')), BadgeType.VERIFIED) else None,
  4417. }
  4418. def _grid_entries(self, grid_renderer):
  4419. for item in grid_renderer['items']:
  4420. if not isinstance(item, dict):
  4421. continue
  4422. renderer = self._extract_basic_item_renderer(item)
  4423. if not isinstance(renderer, dict):
  4424. continue
  4425. title = self._get_text(renderer, 'title')
  4426. # playlist
  4427. playlist_id = renderer.get('playlistId')
  4428. if playlist_id:
  4429. yield self.url_result(
  4430. f'https://www.youtube.com/playlist?list={playlist_id}',
  4431. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  4432. video_title=title)
  4433. continue
  4434. # video
  4435. video_id = renderer.get('videoId')
  4436. if video_id:
  4437. yield self._extract_video(renderer)
  4438. continue
  4439. # channel
  4440. channel_id = renderer.get('channelId')
  4441. if channel_id:
  4442. yield self._extract_channel_renderer(renderer)
  4443. continue
  4444. # generic endpoint URL support
  4445. ep_url = urljoin('https://www.youtube.com/', try_get(
  4446. renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
  4447. str))
  4448. if ep_url:
  4449. for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
  4450. if ie.suitable(ep_url):
  4451. yield self.url_result(
  4452. ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
  4453. break
  4454. def _music_reponsive_list_entry(self, renderer):
  4455. video_id = traverse_obj(renderer, ('playlistItemData', 'videoId'))
  4456. if video_id:
  4457. title = traverse_obj(renderer, (
  4458. 'flexColumns', 0, 'musicResponsiveListItemFlexColumnRenderer',
  4459. 'text', 'runs', 0, 'text'))
  4460. return self.url_result(f'https://music.youtube.com/watch?v={video_id}',
  4461. ie=YoutubeIE.ie_key(), video_id=video_id, title=title)
  4462. playlist_id = traverse_obj(renderer, ('navigationEndpoint', 'watchEndpoint', 'playlistId'))
  4463. if playlist_id:
  4464. video_id = traverse_obj(renderer, ('navigationEndpoint', 'watchEndpoint', 'videoId'))
  4465. if video_id:
  4466. return self.url_result(f'https://music.youtube.com/watch?v={video_id}&list={playlist_id}',
  4467. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  4468. return self.url_result(f'https://music.youtube.com/playlist?list={playlist_id}',
  4469. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  4470. browse_id = traverse_obj(renderer, ('navigationEndpoint', 'browseEndpoint', 'browseId'))
  4471. if browse_id:
  4472. return self.url_result(f'https://music.youtube.com/browse/{browse_id}',
  4473. ie=YoutubeTabIE.ie_key(), video_id=browse_id)
  4474. def _shelf_entries_from_content(self, shelf_renderer):
  4475. content = shelf_renderer.get('content')
  4476. if not isinstance(content, dict):
  4477. return
  4478. renderer = content.get('gridRenderer') or content.get('expandedShelfContentsRenderer')
  4479. if renderer:
  4480. # TODO: add support for nested playlists so each shelf is processed
  4481. # as separate playlist
  4482. # TODO: this includes only first N items
  4483. yield from self._grid_entries(renderer)
  4484. renderer = content.get('horizontalListRenderer')
  4485. if renderer:
  4486. # TODO: handle case
  4487. pass
  4488. def _shelf_entries(self, shelf_renderer, skip_channels=False):
  4489. ep = try_get(
  4490. shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  4491. str)
  4492. shelf_url = urljoin('https://www.youtube.com', ep)
  4493. if shelf_url:
  4494. # Skipping links to another channels, note that checking for
  4495. # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
  4496. # will not work
  4497. if skip_channels and '/channels?' in shelf_url:
  4498. return
  4499. title = self._get_text(shelf_renderer, 'title')
  4500. yield self.url_result(shelf_url, video_title=title)
  4501. # Shelf may not contain shelf URL, fallback to extraction from content
  4502. yield from self._shelf_entries_from_content(shelf_renderer)
  4503. def _playlist_entries(self, video_list_renderer):
  4504. for content in video_list_renderer['contents']:
  4505. if not isinstance(content, dict):
  4506. continue
  4507. renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
  4508. if not isinstance(renderer, dict):
  4509. continue
  4510. video_id = renderer.get('videoId')
  4511. if not video_id:
  4512. continue
  4513. yield self._extract_video(renderer)
  4514. def _rich_entries(self, rich_grid_renderer):
  4515. renderer = traverse_obj(
  4516. rich_grid_renderer,
  4517. ('content', ('videoRenderer', 'reelItemRenderer', 'playlistRenderer')), get_all=False) or {}
  4518. video_id = renderer.get('videoId')
  4519. if video_id:
  4520. yield self._extract_video(renderer)
  4521. return
  4522. playlist_id = renderer.get('playlistId')
  4523. if playlist_id:
  4524. yield self.url_result(
  4525. f'https://www.youtube.com/playlist?list={playlist_id}',
  4526. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  4527. video_title=self._get_text(renderer, 'title'))
  4528. return
  4529. def _video_entry(self, video_renderer):
  4530. video_id = video_renderer.get('videoId')
  4531. if video_id:
  4532. return self._extract_video(video_renderer)
  4533. def _hashtag_tile_entry(self, hashtag_tile_renderer):
  4534. url = urljoin('https://youtube.com', traverse_obj(
  4535. hashtag_tile_renderer, ('onTapCommand', 'commandMetadata', 'webCommandMetadata', 'url')))
  4536. if url:
  4537. return self.url_result(
  4538. url, ie=YoutubeTabIE.ie_key(), title=self._get_text(hashtag_tile_renderer, 'hashtag'))
  4539. def _post_thread_entries(self, post_thread_renderer):
  4540. post_renderer = try_get(
  4541. post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
  4542. if not post_renderer:
  4543. return
  4544. # video attachment
  4545. video_renderer = try_get(
  4546. post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict) or {}
  4547. video_id = video_renderer.get('videoId')
  4548. if video_id:
  4549. entry = self._extract_video(video_renderer)
  4550. if entry:
  4551. yield entry
  4552. # playlist attachment
  4553. playlist_id = try_get(
  4554. post_renderer, lambda x: x['backstageAttachment']['playlistRenderer']['playlistId'], str)
  4555. if playlist_id:
  4556. yield self.url_result(
  4557. f'https://www.youtube.com/playlist?list={playlist_id}',
  4558. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  4559. # inline video links
  4560. runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
  4561. for run in runs:
  4562. if not isinstance(run, dict):
  4563. continue
  4564. ep_url = try_get(
  4565. run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], str)
  4566. if not ep_url:
  4567. continue
  4568. if not YoutubeIE.suitable(ep_url):
  4569. continue
  4570. ep_video_id = YoutubeIE._match_id(ep_url)
  4571. if video_id == ep_video_id:
  4572. continue
  4573. yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=ep_video_id)
  4574. def _post_thread_continuation_entries(self, post_thread_continuation):
  4575. contents = post_thread_continuation.get('contents')
  4576. if not isinstance(contents, list):
  4577. return
  4578. for content in contents:
  4579. renderer = content.get('backstagePostThreadRenderer')
  4580. if isinstance(renderer, dict):
  4581. yield from self._post_thread_entries(renderer)
  4582. continue
  4583. renderer = content.get('videoRenderer')
  4584. if isinstance(renderer, dict):
  4585. yield self._video_entry(renderer)
  4586. r''' # unused
  4587. def _rich_grid_entries(self, contents):
  4588. for content in contents:
  4589. video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
  4590. if video_renderer:
  4591. entry = self._video_entry(video_renderer)
  4592. if entry:
  4593. yield entry
  4594. '''
  4595. def _report_history_entries(self, renderer):
  4596. for url in traverse_obj(renderer, (
  4597. 'rows', ..., 'reportHistoryTableRowRenderer', 'cells', ...,
  4598. 'reportHistoryTableCellRenderer', 'cell', 'reportHistoryTableTextCellRenderer', 'text', 'runs', ...,
  4599. 'navigationEndpoint', 'commandMetadata', 'webCommandMetadata', 'url')):
  4600. yield self.url_result(urljoin('https://www.youtube.com', url), YoutubeIE)
  4601. def _extract_entries(self, parent_renderer, continuation_list):
  4602. # continuation_list is modified in-place with continuation_list = [continuation_token]
  4603. continuation_list[:] = [None]
  4604. contents = try_get(parent_renderer, lambda x: x['contents'], list) or []
  4605. for content in contents:
  4606. if not isinstance(content, dict):
  4607. continue
  4608. is_renderer = traverse_obj(
  4609. content, 'itemSectionRenderer', 'musicShelfRenderer', 'musicShelfContinuation',
  4610. expected_type=dict)
  4611. if not is_renderer:
  4612. if content.get('richItemRenderer'):
  4613. for entry in self._rich_entries(content['richItemRenderer']):
  4614. yield entry
  4615. continuation_list[0] = self._extract_continuation(parent_renderer)
  4616. elif content.get('reportHistorySectionRenderer'): # https://www.youtube.com/reporthistory
  4617. table = traverse_obj(content, ('reportHistorySectionRenderer', 'table', 'tableRenderer'))
  4618. yield from self._report_history_entries(table)
  4619. continuation_list[0] = self._extract_continuation(table)
  4620. continue
  4621. isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
  4622. for isr_content in isr_contents:
  4623. if not isinstance(isr_content, dict):
  4624. continue
  4625. known_renderers = {
  4626. 'playlistVideoListRenderer': self._playlist_entries,
  4627. 'gridRenderer': self._grid_entries,
  4628. 'reelShelfRenderer': self._grid_entries,
  4629. 'shelfRenderer': self._shelf_entries,
  4630. 'musicResponsiveListItemRenderer': lambda x: [self._music_reponsive_list_entry(x)],
  4631. 'backstagePostThreadRenderer': self._post_thread_entries,
  4632. 'videoRenderer': lambda x: [self._video_entry(x)],
  4633. 'playlistRenderer': lambda x: self._grid_entries({'items': [{'playlistRenderer': x}]}),
  4634. 'channelRenderer': lambda x: self._grid_entries({'items': [{'channelRenderer': x}]}),
  4635. 'hashtagTileRenderer': lambda x: [self._hashtag_tile_entry(x)],
  4636. 'richGridRenderer': lambda x: self._extract_entries(x, continuation_list),
  4637. }
  4638. for key, renderer in isr_content.items():
  4639. if key not in known_renderers:
  4640. continue
  4641. for entry in known_renderers[key](renderer):
  4642. if entry:
  4643. yield entry
  4644. continuation_list[0] = self._extract_continuation(renderer)
  4645. break
  4646. if not continuation_list[0]:
  4647. continuation_list[0] = self._extract_continuation(is_renderer)
  4648. if not continuation_list[0]:
  4649. continuation_list[0] = self._extract_continuation(parent_renderer)
  4650. def _entries(self, tab, item_id, ytcfg, account_syncid, visitor_data):
  4651. continuation_list = [None]
  4652. extract_entries = lambda x: self._extract_entries(x, continuation_list)
  4653. tab_content = try_get(tab, lambda x: x['content'], dict)
  4654. if not tab_content:
  4655. return
  4656. parent_renderer = (
  4657. try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
  4658. or try_get(tab_content, lambda x: x['richGridRenderer'], dict) or {})
  4659. yield from extract_entries(parent_renderer)
  4660. continuation = continuation_list[0]
  4661. seen_continuations = set()
  4662. for page_num in itertools.count(1):
  4663. if not continuation:
  4664. break
  4665. continuation_token = continuation.get('continuation')
  4666. if continuation_token is not None and continuation_token in seen_continuations:
  4667. self.write_debug('Detected YouTube feed looping - assuming end of feed.')
  4668. break
  4669. seen_continuations.add(continuation_token)
  4670. headers = self.generate_api_headers(
  4671. ytcfg=ytcfg, account_syncid=account_syncid, visitor_data=visitor_data)
  4672. response = self._extract_response(
  4673. item_id=f'{item_id} page {page_num}',
  4674. query=continuation, headers=headers, ytcfg=ytcfg,
  4675. check_get_keys=('continuationContents', 'onResponseReceivedActions', 'onResponseReceivedEndpoints'))
  4676. if not response:
  4677. break
  4678. # Extracting updated visitor data is required to prevent an infinite extraction loop in some cases
  4679. # See: https://github.com/ytdl-org/youtube-dl/issues/28702
  4680. visitor_data = self._extract_visitor_data(response) or visitor_data
  4681. known_renderers = {
  4682. 'videoRenderer': (self._grid_entries, 'items'), # for membership tab
  4683. 'gridPlaylistRenderer': (self._grid_entries, 'items'),
  4684. 'gridVideoRenderer': (self._grid_entries, 'items'),
  4685. 'gridChannelRenderer': (self._grid_entries, 'items'),
  4686. 'playlistVideoRenderer': (self._playlist_entries, 'contents'),
  4687. 'itemSectionRenderer': (extract_entries, 'contents'), # for feeds
  4688. 'richItemRenderer': (extract_entries, 'contents'), # for hashtag
  4689. 'backstagePostThreadRenderer': (self._post_thread_continuation_entries, 'contents'),
  4690. 'reportHistoryTableRowRenderer': (self._report_history_entries, 'rows'),
  4691. 'playlistVideoListContinuation': (self._playlist_entries, None),
  4692. 'gridContinuation': (self._grid_entries, None),
  4693. 'itemSectionContinuation': (self._post_thread_continuation_entries, None),
  4694. 'sectionListContinuation': (extract_entries, None), # for feeds
  4695. }
  4696. continuation_items = traverse_obj(response, (
  4697. ('onResponseReceivedActions', 'onResponseReceivedEndpoints'), ...,
  4698. 'appendContinuationItemsAction', 'continuationItems',
  4699. ), 'continuationContents', get_all=False)
  4700. continuation_item = traverse_obj(continuation_items, 0, None, expected_type=dict, default={})
  4701. video_items_renderer = None
  4702. for key in continuation_item:
  4703. if key not in known_renderers:
  4704. continue
  4705. func, parent_key = known_renderers[key]
  4706. video_items_renderer = {parent_key: continuation_items} if parent_key else continuation_items
  4707. continuation_list = [None]
  4708. yield from func(video_items_renderer)
  4709. continuation = continuation_list[0] or self._extract_continuation(video_items_renderer)
  4710. if not video_items_renderer:
  4711. break
  4712. @staticmethod
  4713. def _extract_selected_tab(tabs, fatal=True):
  4714. for tab_renderer in tabs:
  4715. if tab_renderer.get('selected'):
  4716. return tab_renderer
  4717. if fatal:
  4718. raise ExtractorError('Unable to find selected tab')
  4719. @staticmethod
  4720. def _extract_tab_renderers(response):
  4721. return traverse_obj(
  4722. response, ('contents', 'twoColumnBrowseResultsRenderer', 'tabs', ..., ('tabRenderer', 'expandableTabRenderer')), expected_type=dict)
  4723. def _extract_from_tabs(self, item_id, ytcfg, data, tabs):
  4724. metadata = self._extract_metadata_from_tabs(item_id, data)
  4725. selected_tab = self._extract_selected_tab(tabs)
  4726. metadata['title'] += format_field(selected_tab, 'title', ' - %s')
  4727. metadata['title'] += format_field(selected_tab, 'expandedText', ' - %s')
  4728. return self.playlist_result(
  4729. self._entries(
  4730. selected_tab, metadata['id'], ytcfg,
  4731. self._extract_account_syncid(ytcfg, data),
  4732. self._extract_visitor_data(data, ytcfg)),
  4733. **metadata)
  4734. def _extract_metadata_from_tabs(self, item_id, data):
  4735. info = {'id': item_id}
  4736. metadata_renderer = traverse_obj(data, ('metadata', 'channelMetadataRenderer'), expected_type=dict)
  4737. if metadata_renderer:
  4738. channel_id = traverse_obj(metadata_renderer, ('externalId', {self.ucid_or_none}),
  4739. ('channelUrl', {self.ucid_from_url}))
  4740. info.update({
  4741. 'channel': metadata_renderer.get('title'),
  4742. 'channel_id': channel_id,
  4743. })
  4744. if info['channel_id']:
  4745. info['id'] = info['channel_id']
  4746. else:
  4747. metadata_renderer = traverse_obj(data, ('metadata', 'playlistMetadataRenderer'), expected_type=dict)
  4748. # pageHeaderViewModel slow rollout began April 2024
  4749. page_header_view_model = traverse_obj(data, (
  4750. 'header', 'pageHeaderRenderer', 'content', 'pageHeaderViewModel', {dict}))
  4751. # We can get the uncropped banner/avatar by replacing the crop params with '=s0'
  4752. # See: https://github.com/yt-dlp/yt-dlp/issues/2237#issuecomment-1013694714
  4753. def _get_uncropped(url):
  4754. return url_or_none((url or '').split('=')[0] + '=s0')
  4755. avatar_thumbnails = self._extract_thumbnails(metadata_renderer, 'avatar')
  4756. if avatar_thumbnails:
  4757. uncropped_avatar = _get_uncropped(avatar_thumbnails[0]['url'])
  4758. if uncropped_avatar:
  4759. avatar_thumbnails.append({
  4760. 'url': uncropped_avatar,
  4761. 'id': 'avatar_uncropped',
  4762. 'preference': 1,
  4763. })
  4764. channel_banners = (
  4765. self._extract_thumbnails(data, ('header', ..., ('banner', 'mobileBanner', 'tvBanner')))
  4766. or self._extract_thumbnails(
  4767. page_header_view_model, ('banner', 'imageBannerViewModel', 'image'), final_key='sources'))
  4768. for banner in channel_banners:
  4769. banner['preference'] = -10
  4770. if channel_banners:
  4771. uncropped_banner = _get_uncropped(channel_banners[0]['url'])
  4772. if uncropped_banner:
  4773. channel_banners.append({
  4774. 'url': uncropped_banner,
  4775. 'id': 'banner_uncropped',
  4776. 'preference': -5,
  4777. })
  4778. # Deprecated - remove primary_sidebar_renderer when layout discontinued
  4779. primary_sidebar_renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarPrimaryInfoRenderer')
  4780. playlist_header_renderer = traverse_obj(data, ('header', 'playlistHeaderRenderer'), expected_type=dict)
  4781. primary_thumbnails = self._extract_thumbnails(
  4782. primary_sidebar_renderer, ('thumbnailRenderer', ('playlistVideoThumbnailRenderer', 'playlistCustomThumbnailRenderer'), 'thumbnail'))
  4783. playlist_thumbnails = self._extract_thumbnails(
  4784. playlist_header_renderer, ('playlistHeaderBanner', 'heroPlaylistThumbnailRenderer', 'thumbnail'))
  4785. info.update({
  4786. 'title': (traverse_obj(metadata_renderer, 'title')
  4787. or self._get_text(data, ('header', 'hashtagHeaderRenderer', 'hashtag'))
  4788. or info['id']),
  4789. 'availability': self._extract_availability(data),
  4790. 'channel_follower_count': (
  4791. self._get_count(data, ('header', ..., 'subscriberCountText'))
  4792. or traverse_obj(page_header_view_model, (
  4793. 'metadata', 'contentMetadataViewModel', 'metadataRows', ..., 'metadataParts',
  4794. lambda _, v: 'subscribers' in v['text']['content'], 'text', 'content', {parse_count}, any))),
  4795. 'description': try_get(metadata_renderer, lambda x: x.get('description', '')),
  4796. 'tags': (traverse_obj(data, ('microformat', 'microformatDataRenderer', 'tags', ..., {str}))
  4797. or traverse_obj(metadata_renderer, ('keywords', {lambda x: x and shlex.split(x)}, ...))),
  4798. 'thumbnails': (primary_thumbnails or playlist_thumbnails) + avatar_thumbnails + channel_banners,
  4799. })
  4800. channel_handle = (
  4801. traverse_obj(metadata_renderer, (('vanityChannelUrl', ('ownerUrls', ...)), {self.handle_from_url}), get_all=False)
  4802. or traverse_obj(data, ('header', ..., 'channelHandleText', {self.handle_or_none}), get_all=False))
  4803. if channel_handle:
  4804. info.update({
  4805. 'uploader_id': channel_handle,
  4806. 'uploader_url': format_field(channel_handle, None, 'https://www.youtube.com/%s', default=None),
  4807. })
  4808. channel_badges = self._extract_badges(traverse_obj(data, ('header', ..., 'badges'), get_all=False))
  4809. if self._has_badge(channel_badges, BadgeType.VERIFIED):
  4810. info['channel_is_verified'] = True
  4811. # Playlist stats is a text runs array containing [video count, view count, last updated].
  4812. # last updated or (view count and last updated) may be missing.
  4813. playlist_stats = get_first(
  4814. (primary_sidebar_renderer, playlist_header_renderer), (('stats', 'briefStats', 'numVideosText'), ))
  4815. last_updated_unix = self._parse_time_text(
  4816. self._get_text(playlist_stats, 2) # deprecated, remove when old layout discontinued
  4817. or self._get_text(playlist_header_renderer, ('byline', 1, 'playlistBylineRenderer', 'text')))
  4818. info['modified_date'] = strftime_or_none(last_updated_unix)
  4819. info['view_count'] = self._get_count(playlist_stats, 1)
  4820. if info['view_count'] is None: # 0 is allowed
  4821. info['view_count'] = self._get_count(playlist_header_renderer, 'viewCountText')
  4822. if info['view_count'] is None:
  4823. info['view_count'] = self._get_count(data, (
  4824. 'contents', 'twoColumnBrowseResultsRenderer', 'tabs', ..., 'tabRenderer', 'content', 'sectionListRenderer',
  4825. 'contents', ..., 'itemSectionRenderer', 'contents', ..., 'channelAboutFullMetadataRenderer', 'viewCountText'))
  4826. info['playlist_count'] = self._get_count(playlist_stats, 0)
  4827. if info['playlist_count'] is None: # 0 is allowed
  4828. info['playlist_count'] = self._get_count(playlist_header_renderer, ('byline', 0, 'playlistBylineRenderer', 'text'))
  4829. if not info.get('channel_id'):
  4830. owner = traverse_obj(playlist_header_renderer, 'ownerText')
  4831. if not owner: # Deprecated
  4832. owner = traverse_obj(
  4833. self._extract_sidebar_info_renderer(data, 'playlistSidebarSecondaryInfoRenderer'),
  4834. ('videoOwner', 'videoOwnerRenderer', 'title'))
  4835. owner_text = self._get_text(owner)
  4836. browse_ep = traverse_obj(owner, ('runs', 0, 'navigationEndpoint', 'browseEndpoint')) or {}
  4837. info.update({
  4838. 'channel': self._search_regex(r'^by (.+) and \d+ others?$', owner_text, 'uploader', default=owner_text),
  4839. 'channel_id': self.ucid_or_none(browse_ep.get('browseId')),
  4840. 'uploader_id': self.handle_from_url(urljoin('https://www.youtube.com', browse_ep.get('canonicalBaseUrl'))),
  4841. })
  4842. info.update({
  4843. 'uploader': info['channel'],
  4844. 'channel_url': format_field(info.get('channel_id'), None, 'https://www.youtube.com/channel/%s', default=None),
  4845. 'uploader_url': format_field(info.get('uploader_id'), None, 'https://www.youtube.com/%s', default=None),
  4846. })
  4847. return info
  4848. def _extract_inline_playlist(self, playlist, playlist_id, data, ytcfg):
  4849. first_id = last_id = response = None
  4850. for page_num in itertools.count(1):
  4851. videos = list(self._playlist_entries(playlist))
  4852. if not videos:
  4853. return
  4854. start = next((i for i, v in enumerate(videos) if v['id'] == last_id), -1) + 1
  4855. if start >= len(videos):
  4856. return
  4857. yield from videos[start:]
  4858. first_id = first_id or videos[0]['id']
  4859. last_id = videos[-1]['id']
  4860. watch_endpoint = try_get(
  4861. playlist, lambda x: x['contents'][-1]['playlistPanelVideoRenderer']['navigationEndpoint']['watchEndpoint'])
  4862. headers = self.generate_api_headers(
  4863. ytcfg=ytcfg, account_syncid=self._extract_account_syncid(ytcfg, data),
  4864. visitor_data=self._extract_visitor_data(response, data, ytcfg))
  4865. query = {
  4866. 'playlistId': playlist_id,
  4867. 'videoId': watch_endpoint.get('videoId') or last_id,
  4868. 'index': watch_endpoint.get('index') or len(videos),
  4869. 'params': watch_endpoint.get('params') or 'OAE%3D',
  4870. }
  4871. response = self._extract_response(
  4872. item_id=f'{playlist_id} page {page_num}',
  4873. query=query, ep='next', headers=headers, ytcfg=ytcfg,
  4874. check_get_keys='contents',
  4875. )
  4876. playlist = try_get(
  4877. response, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
  4878. def _extract_from_playlist(self, item_id, url, data, playlist, ytcfg):
  4879. title = playlist.get('title') or try_get(
  4880. data, lambda x: x['titleText']['simpleText'], str)
  4881. playlist_id = playlist.get('playlistId') or item_id
  4882. # Delegating everything except mix playlists to regular tab-based playlist URL
  4883. playlist_url = urljoin(url, try_get(
  4884. playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  4885. str))
  4886. # Some playlists are unviewable but YouTube still provides a link to the (broken) playlist page [1]
  4887. # [1] MLCT, RLTDwFCb4jeqaKWnciAYM-ZVHg
  4888. is_known_unviewable = re.fullmatch(r'MLCT|RLTD[\w-]{22}', playlist_id)
  4889. if playlist_url and playlist_url != url and not is_known_unviewable:
  4890. return self.url_result(
  4891. playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  4892. video_title=title)
  4893. return self.playlist_result(
  4894. self._extract_inline_playlist(playlist, playlist_id, data, ytcfg),
  4895. playlist_id=playlist_id, playlist_title=title)
  4896. def _extract_availability(self, data):
  4897. """
  4898. Gets the availability of a given playlist/tab.
  4899. Note: Unless YouTube tells us explicitly, we do not assume it is public
  4900. @param data: response
  4901. """
  4902. sidebar_renderer = self._extract_sidebar_info_renderer(data, 'playlistSidebarPrimaryInfoRenderer') or {}
  4903. playlist_header_renderer = traverse_obj(data, ('header', 'playlistHeaderRenderer')) or {}
  4904. player_header_privacy = playlist_header_renderer.get('privacy')
  4905. badges = self._extract_badges(traverse_obj(sidebar_renderer, 'badges'))
  4906. # Personal playlists, when authenticated, have a dropdown visibility selector instead of a badge
  4907. privacy_setting_icon = get_first(
  4908. (playlist_header_renderer, sidebar_renderer),
  4909. ('privacyForm', 'dropdownFormFieldRenderer', 'dropdown', 'dropdownRenderer', 'entries',
  4910. lambda _, v: v['privacyDropdownItemRenderer']['isSelected'], 'privacyDropdownItemRenderer', 'icon', 'iconType'),
  4911. expected_type=str)
  4912. microformats_is_unlisted = traverse_obj(
  4913. data, ('microformat', 'microformatDataRenderer', 'unlisted'), expected_type=bool)
  4914. return (
  4915. 'public' if (
  4916. self._has_badge(badges, BadgeType.AVAILABILITY_PUBLIC)
  4917. or player_header_privacy == 'PUBLIC'
  4918. or privacy_setting_icon == 'PRIVACY_PUBLIC')
  4919. else self._availability(
  4920. is_private=(
  4921. self._has_badge(badges, BadgeType.AVAILABILITY_PRIVATE)
  4922. or player_header_privacy == 'PRIVATE' if player_header_privacy is not None
  4923. else privacy_setting_icon == 'PRIVACY_PRIVATE' if privacy_setting_icon is not None else None),
  4924. is_unlisted=(
  4925. self._has_badge(badges, BadgeType.AVAILABILITY_UNLISTED)
  4926. or player_header_privacy == 'UNLISTED' if player_header_privacy is not None
  4927. else privacy_setting_icon == 'PRIVACY_UNLISTED' if privacy_setting_icon is not None
  4928. else microformats_is_unlisted if microformats_is_unlisted is not None else None),
  4929. needs_subscription=self._has_badge(badges, BadgeType.AVAILABILITY_SUBSCRIPTION) or None,
  4930. needs_premium=self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or None,
  4931. needs_auth=False))
  4932. @staticmethod
  4933. def _extract_sidebar_info_renderer(data, info_renderer, expected_type=dict):
  4934. sidebar_renderer = try_get(
  4935. data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list) or []
  4936. for item in sidebar_renderer:
  4937. renderer = try_get(item, lambda x: x[info_renderer], expected_type)
  4938. if renderer:
  4939. return renderer
  4940. def _reload_with_unavailable_videos(self, item_id, data, ytcfg):
  4941. """
  4942. Reload playlists with unavailable videos (e.g. private videos, region blocked, etc.)
  4943. """
  4944. is_playlist = bool(traverse_obj(
  4945. data, ('metadata', 'playlistMetadataRenderer'), ('header', 'playlistHeaderRenderer')))
  4946. if not is_playlist:
  4947. return
  4948. headers = self.generate_api_headers(
  4949. ytcfg=ytcfg, account_syncid=self._extract_account_syncid(ytcfg, data),
  4950. visitor_data=self._extract_visitor_data(data, ytcfg))
  4951. query = {
  4952. 'params': 'wgYCCAA=',
  4953. 'browseId': f'VL{item_id}',
  4954. }
  4955. return self._extract_response(
  4956. item_id=item_id, headers=headers, query=query,
  4957. check_get_keys='contents', fatal=False, ytcfg=ytcfg,
  4958. note='Redownloading playlist API JSON with unavailable videos')
  4959. @functools.cached_property
  4960. def skip_webpage(self):
  4961. return 'webpage' in self._configuration_arg('skip', ie_key=YoutubeTabIE.ie_key())
  4962. def _extract_webpage(self, url, item_id, fatal=True):
  4963. webpage, data = None, None
  4964. for retry in self.RetryManager(fatal=fatal):
  4965. try:
  4966. webpage = self._download_webpage(url, item_id, note='Downloading webpage')
  4967. data = self.extract_yt_initial_data(item_id, webpage or '', fatal=fatal) or {}
  4968. except ExtractorError as e:
  4969. if isinstance(e.cause, network_exceptions):
  4970. if not isinstance(e.cause, HTTPError) or e.cause.status not in (403, 429):
  4971. retry.error = e
  4972. continue
  4973. self._error_or_warning(e, fatal=fatal)
  4974. break
  4975. try:
  4976. self._extract_and_report_alerts(data)
  4977. except ExtractorError as e:
  4978. self._error_or_warning(e, fatal=fatal)
  4979. break
  4980. # Sometimes youtube returns a webpage with incomplete ytInitialData
  4981. # See: https://github.com/yt-dlp/yt-dlp/issues/116
  4982. if not traverse_obj(data, 'contents', 'currentVideoEndpoint', 'onResponseReceivedActions'):
  4983. retry.error = ExtractorError('Incomplete yt initial data received')
  4984. data = None
  4985. continue
  4986. return webpage, data
  4987. def _report_playlist_authcheck(self, ytcfg, fatal=True):
  4988. """Use if failed to extract ytcfg (and data) from initial webpage"""
  4989. if not ytcfg and self.is_authenticated:
  4990. msg = 'Playlists that require authentication may not extract correctly without a successful webpage download'
  4991. if 'authcheck' not in self._configuration_arg('skip', ie_key=YoutubeTabIE.ie_key()) and fatal:
  4992. raise ExtractorError(
  4993. f'{msg}. If you are not downloading private content, or '
  4994. 'your cookies are only for the first account and channel,'
  4995. ' pass "--extractor-args youtubetab:skip=authcheck" to skip this check',
  4996. expected=True)
  4997. self.report_warning(msg, only_once=True)
  4998. def _extract_data(self, url, item_id, ytcfg=None, fatal=True, webpage_fatal=False, default_client='web'):
  4999. data = None
  5000. if not self.skip_webpage:
  5001. webpage, data = self._extract_webpage(url, item_id, fatal=webpage_fatal)
  5002. ytcfg = ytcfg or self.extract_ytcfg(item_id, webpage)
  5003. # Reject webpage data if redirected to home page without explicitly requesting
  5004. selected_tab = self._extract_selected_tab(self._extract_tab_renderers(data), fatal=False) or {}
  5005. if (url != 'https://www.youtube.com/feed/recommended'
  5006. and selected_tab.get('tabIdentifier') == 'FEwhat_to_watch' # Home page
  5007. and 'no-youtube-channel-redirect' not in self.get_param('compat_opts', [])):
  5008. msg = 'The channel/playlist does not exist and the URL redirected to youtube.com home page'
  5009. if fatal:
  5010. raise ExtractorError(msg, expected=True)
  5011. self.report_warning(msg, only_once=True)
  5012. if not data:
  5013. self._report_playlist_authcheck(ytcfg, fatal=fatal)
  5014. data = self._extract_tab_endpoint(url, item_id, ytcfg, fatal=fatal, default_client=default_client)
  5015. return data, ytcfg
  5016. def _extract_tab_endpoint(self, url, item_id, ytcfg=None, fatal=True, default_client='web'):
  5017. headers = self.generate_api_headers(ytcfg=ytcfg, default_client=default_client)
  5018. resolve_response = self._extract_response(
  5019. item_id=item_id, query={'url': url}, check_get_keys='endpoint', headers=headers, ytcfg=ytcfg, fatal=fatal,
  5020. ep='navigation/resolve_url', note='Downloading API parameters API JSON', default_client=default_client)
  5021. endpoints = {'browseEndpoint': 'browse', 'watchEndpoint': 'next'}
  5022. for ep_key, ep in endpoints.items():
  5023. params = try_get(resolve_response, lambda x: x['endpoint'][ep_key], dict)
  5024. if params:
  5025. return self._extract_response(
  5026. item_id=item_id, query=params, ep=ep, headers=headers,
  5027. ytcfg=ytcfg, fatal=fatal, default_client=default_client,
  5028. check_get_keys=('contents', 'currentVideoEndpoint', 'onResponseReceivedActions'))
  5029. err_note = 'Failed to resolve url (does the playlist exist?)'
  5030. if fatal:
  5031. raise ExtractorError(err_note, expected=True)
  5032. self.report_warning(err_note, item_id)
  5033. _SEARCH_PARAMS = None
  5034. def _search_results(self, query, params=NO_DEFAULT, default_client='web'):
  5035. data = {'query': query}
  5036. if params is NO_DEFAULT:
  5037. params = self._SEARCH_PARAMS
  5038. if params:
  5039. data['params'] = params
  5040. content_keys = (
  5041. ('contents', 'twoColumnSearchResultsRenderer', 'primaryContents', 'sectionListRenderer', 'contents'),
  5042. ('onResponseReceivedCommands', 0, 'appendContinuationItemsAction', 'continuationItems'),
  5043. # ytmusic search
  5044. ('contents', 'tabbedSearchResultsRenderer', 'tabs', 0, 'tabRenderer', 'content', 'sectionListRenderer', 'contents'),
  5045. ('continuationContents', ),
  5046. )
  5047. display_id = f'query "{query}"'
  5048. check_get_keys = tuple({keys[0] for keys in content_keys})
  5049. ytcfg = self._download_ytcfg(default_client, display_id) if not self.skip_webpage else {}
  5050. self._report_playlist_authcheck(ytcfg, fatal=False)
  5051. continuation_list = [None]
  5052. search = None
  5053. for page_num in itertools.count(1):
  5054. data.update(continuation_list[0] or {})
  5055. headers = self.generate_api_headers(
  5056. ytcfg=ytcfg, visitor_data=self._extract_visitor_data(search), default_client=default_client)
  5057. search = self._extract_response(
  5058. item_id=f'{display_id} page {page_num}', ep='search', query=data,
  5059. default_client=default_client, check_get_keys=check_get_keys, ytcfg=ytcfg, headers=headers)
  5060. slr_contents = traverse_obj(search, *content_keys)
  5061. yield from self._extract_entries({'contents': list(variadic(slr_contents))}, continuation_list)
  5062. if not continuation_list[0]:
  5063. break
  5064. class YoutubeTabIE(YoutubeTabBaseInfoExtractor):
  5065. IE_DESC = 'YouTube Tabs'
  5066. _VALID_URL = r'''(?x:
  5067. https?://
  5068. (?!consent\.)(?:\w+\.)?
  5069. (?:
  5070. youtube(?:kids)?\.com|
  5071. {invidious}
  5072. )/
  5073. (?:
  5074. (?P<channel_type>channel|c|user|browse)/|
  5075. (?P<not_channel>
  5076. feed/|hashtag/|
  5077. (?:playlist|watch)\?.*?\blist=
  5078. )|
  5079. (?!(?:{reserved_names})\b) # Direct URLs
  5080. )
  5081. (?P<id>[^/?\#&]+)
  5082. )'''.format(
  5083. reserved_names=YoutubeBaseInfoExtractor._RESERVED_NAMES,
  5084. invidious='|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
  5085. )
  5086. IE_NAME = 'youtube:tab'
  5087. _TESTS = [{
  5088. 'note': 'playlists, multipage',
  5089. 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
  5090. 'playlist_mincount': 94,
  5091. 'info_dict': {
  5092. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  5093. 'title': 'Igor Kleiner Ph.D. - Playlists',
  5094. 'description': 'md5:15d7dd9e333cb987907fcb0d604b233a',
  5095. 'uploader': 'Igor Kleiner Ph.D.',
  5096. 'uploader_id': '@IgorDataScience',
  5097. 'uploader_url': 'https://www.youtube.com/@IgorDataScience',
  5098. 'channel': 'Igor Kleiner Ph.D.',
  5099. 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
  5100. 'tags': ['критическое мышление', 'наука просто', 'математика', 'анализ данных'],
  5101. 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
  5102. 'channel_follower_count': int,
  5103. },
  5104. }, {
  5105. 'note': 'playlists, multipage, different order',
  5106. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  5107. 'playlist_mincount': 94,
  5108. 'info_dict': {
  5109. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  5110. 'title': 'Igor Kleiner Ph.D. - Playlists',
  5111. 'description': 'md5:15d7dd9e333cb987907fcb0d604b233a',
  5112. 'uploader': 'Igor Kleiner Ph.D.',
  5113. 'uploader_id': '@IgorDataScience',
  5114. 'uploader_url': 'https://www.youtube.com/@IgorDataScience',
  5115. 'tags': ['критическое мышление', 'наука просто', 'математика', 'анализ данных'],
  5116. 'channel_id': 'UCqj7Cz7revf5maW9g5pgNcg',
  5117. 'channel': 'Igor Kleiner Ph.D.',
  5118. 'channel_url': 'https://www.youtube.com/channel/UCqj7Cz7revf5maW9g5pgNcg',
  5119. 'channel_follower_count': int,
  5120. },
  5121. }, {
  5122. 'note': 'playlists, series',
  5123. 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
  5124. 'playlist_mincount': 5,
  5125. 'info_dict': {
  5126. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  5127. 'title': '3Blue1Brown - Playlists',
  5128. 'description': 'md5:4d1da95432004b7ba840ebc895b6b4c9',
  5129. 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
  5130. 'channel': '3Blue1Brown',
  5131. 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
  5132. 'uploader_id': '@3blue1brown',
  5133. 'uploader_url': 'https://www.youtube.com/@3blue1brown',
  5134. 'uploader': '3Blue1Brown',
  5135. 'tags': ['Mathematics'],
  5136. 'channel_follower_count': int,
  5137. 'channel_is_verified': True,
  5138. },
  5139. }, {
  5140. 'note': 'playlists, singlepage',
  5141. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  5142. 'playlist_mincount': 4,
  5143. 'info_dict': {
  5144. 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
  5145. 'title': 'ThirstForScience - Playlists',
  5146. 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
  5147. 'uploader': 'ThirstForScience',
  5148. 'uploader_url': 'https://www.youtube.com/@ThirstForScience',
  5149. 'uploader_id': '@ThirstForScience',
  5150. 'channel_id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
  5151. 'channel_url': 'https://www.youtube.com/channel/UCAEtajcuhQ6an9WEzY9LEMQ',
  5152. 'tags': 'count:12',
  5153. 'channel': 'ThirstForScience',
  5154. 'channel_follower_count': int,
  5155. },
  5156. }, {
  5157. 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
  5158. 'only_matching': True,
  5159. }, {
  5160. 'note': 'basic, single video playlist',
  5161. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  5162. 'info_dict': {
  5163. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  5164. 'title': 'youtube-dl public playlist',
  5165. 'description': '',
  5166. 'tags': [],
  5167. 'view_count': int,
  5168. 'modified_date': '20201130',
  5169. 'channel': 'Sergey M.',
  5170. 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  5171. 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  5172. 'availability': 'public',
  5173. 'uploader': 'Sergey M.',
  5174. 'uploader_url': 'https://www.youtube.com/@sergeym.6173',
  5175. 'uploader_id': '@sergeym.6173',
  5176. },
  5177. 'playlist_count': 1,
  5178. }, {
  5179. 'note': 'empty playlist',
  5180. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  5181. 'info_dict': {
  5182. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  5183. 'title': 'youtube-dl empty playlist',
  5184. 'tags': [],
  5185. 'channel': 'Sergey M.',
  5186. 'description': '',
  5187. 'modified_date': '20230921',
  5188. 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  5189. 'channel_url': 'https://www.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  5190. 'availability': 'unlisted',
  5191. 'uploader_url': 'https://www.youtube.com/@sergeym.6173',
  5192. 'uploader_id': '@sergeym.6173',
  5193. 'uploader': 'Sergey M.',
  5194. },
  5195. 'playlist_count': 0,
  5196. }, {
  5197. 'note': 'Home tab',
  5198. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
  5199. 'info_dict': {
  5200. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5201. 'title': 'lex will - Home',
  5202. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5203. 'uploader': 'lex will',
  5204. 'uploader_id': '@lexwill718',
  5205. 'channel': 'lex will',
  5206. 'tags': ['bible', 'history', 'prophesy'],
  5207. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5208. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5209. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5210. 'channel_follower_count': int,
  5211. },
  5212. 'playlist_mincount': 2,
  5213. }, {
  5214. 'note': 'Videos tab',
  5215. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
  5216. 'info_dict': {
  5217. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5218. 'title': 'lex will - Videos',
  5219. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5220. 'uploader': 'lex will',
  5221. 'uploader_id': '@lexwill718',
  5222. 'tags': ['bible', 'history', 'prophesy'],
  5223. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5224. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5225. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5226. 'channel': 'lex will',
  5227. 'channel_follower_count': int,
  5228. },
  5229. 'playlist_mincount': 975,
  5230. }, {
  5231. 'note': 'Videos tab, sorted by popular',
  5232. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
  5233. 'info_dict': {
  5234. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5235. 'title': 'lex will - Videos',
  5236. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5237. 'uploader': 'lex will',
  5238. 'uploader_id': '@lexwill718',
  5239. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5240. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5241. 'channel': 'lex will',
  5242. 'tags': ['bible', 'history', 'prophesy'],
  5243. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5244. 'channel_follower_count': int,
  5245. },
  5246. 'playlist_mincount': 199,
  5247. }, {
  5248. 'note': 'Playlists tab',
  5249. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
  5250. 'info_dict': {
  5251. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5252. 'title': 'lex will - Playlists',
  5253. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5254. 'uploader': 'lex will',
  5255. 'uploader_id': '@lexwill718',
  5256. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5257. 'channel': 'lex will',
  5258. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5259. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5260. 'tags': ['bible', 'history', 'prophesy'],
  5261. 'channel_follower_count': int,
  5262. },
  5263. 'playlist_mincount': 17,
  5264. }, {
  5265. 'note': 'Community tab',
  5266. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
  5267. 'info_dict': {
  5268. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5269. 'title': 'lex will - Community',
  5270. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5271. 'channel': 'lex will',
  5272. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5273. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5274. 'tags': ['bible', 'history', 'prophesy'],
  5275. 'channel_follower_count': int,
  5276. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5277. 'uploader_id': '@lexwill718',
  5278. 'uploader': 'lex will',
  5279. },
  5280. 'playlist_mincount': 18,
  5281. }, {
  5282. 'note': 'Channels tab',
  5283. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
  5284. 'info_dict': {
  5285. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5286. 'title': 'lex will - Channels',
  5287. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  5288. 'channel': 'lex will',
  5289. 'channel_url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  5290. 'channel_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  5291. 'tags': ['bible', 'history', 'prophesy'],
  5292. 'channel_follower_count': int,
  5293. 'uploader_url': 'https://www.youtube.com/@lexwill718',
  5294. 'uploader_id': '@lexwill718',
  5295. 'uploader': 'lex will',
  5296. },
  5297. 'playlist_mincount': 12,
  5298. }, {
  5299. 'note': 'Search tab',
  5300. 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
  5301. 'playlist_mincount': 40,
  5302. 'info_dict': {
  5303. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  5304. 'title': '3Blue1Brown - Search - linear algebra',
  5305. 'description': 'md5:4d1da95432004b7ba840ebc895b6b4c9',
  5306. 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
  5307. 'tags': ['Mathematics'],
  5308. 'channel': '3Blue1Brown',
  5309. 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
  5310. 'channel_follower_count': int,
  5311. 'uploader_url': 'https://www.youtube.com/@3blue1brown',
  5312. 'uploader_id': '@3blue1brown',
  5313. 'uploader': '3Blue1Brown',
  5314. 'channel_is_verified': True,
  5315. },
  5316. }, {
  5317. 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  5318. 'only_matching': True,
  5319. }, {
  5320. 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  5321. 'only_matching': True,
  5322. }, {
  5323. 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  5324. 'only_matching': True,
  5325. }, {
  5326. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  5327. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  5328. 'info_dict': {
  5329. 'title': '29C3: Not my department',
  5330. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  5331. 'description': 'md5:a14dc1a8ef8307a9807fe136a0660268',
  5332. 'tags': [],
  5333. 'view_count': int,
  5334. 'modified_date': '20150605',
  5335. 'channel_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
  5336. 'channel_url': 'https://www.youtube.com/channel/UCEPzS1rYsrkqzSLNp76nrcg',
  5337. 'channel': 'Christiaan008',
  5338. 'availability': 'public',
  5339. 'uploader_id': '@ChRiStIaAn008',
  5340. 'uploader': 'Christiaan008',
  5341. 'uploader_url': 'https://www.youtube.com/@ChRiStIaAn008',
  5342. },
  5343. 'playlist_count': 96,
  5344. }, {
  5345. 'note': 'Large playlist',
  5346. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  5347. 'info_dict': {
  5348. 'title': 'Uploads from Cauchemar',
  5349. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  5350. 'channel_url': 'https://www.youtube.com/channel/UCBABnxM4Ar9ten8Mdjj1j0Q',
  5351. 'tags': [],
  5352. 'modified_date': r're:\d{8}',
  5353. 'channel': 'Cauchemar',
  5354. 'view_count': int,
  5355. 'description': '',
  5356. 'channel_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
  5357. 'availability': 'public',
  5358. 'uploader_id': '@Cauchemar89',
  5359. 'uploader': 'Cauchemar',
  5360. 'uploader_url': 'https://www.youtube.com/@Cauchemar89',
  5361. },
  5362. 'playlist_mincount': 1123,
  5363. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
  5364. }, {
  5365. 'note': 'even larger playlist, 8832 videos',
  5366. 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
  5367. 'only_matching': True,
  5368. }, {
  5369. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  5370. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  5371. 'info_dict': {
  5372. 'title': 'Uploads from Interstellar Movie',
  5373. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  5374. 'tags': [],
  5375. 'view_count': int,
  5376. 'channel_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
  5377. 'channel_url': 'https://www.youtube.com/channel/UCXw-G3eDE9trcvY2sBMM_aA',
  5378. 'channel': 'Interstellar Movie',
  5379. 'description': '',
  5380. 'modified_date': r're:\d{8}',
  5381. 'availability': 'public',
  5382. 'uploader_id': '@InterstellarMovie',
  5383. 'uploader': 'Interstellar Movie',
  5384. 'uploader_url': 'https://www.youtube.com/@InterstellarMovie',
  5385. },
  5386. 'playlist_mincount': 21,
  5387. }, {
  5388. 'note': 'Playlist with "show unavailable videos" button',
  5389. 'url': 'https://www.youtube.com/playlist?list=UUTYLiWFZy8xtPwxFwX9rV7Q',
  5390. 'info_dict': {
  5391. 'title': 'Uploads from Phim Siêu Nhân Nhật Bản',
  5392. 'id': 'UUTYLiWFZy8xtPwxFwX9rV7Q',
  5393. 'view_count': int,
  5394. 'channel': 'Phim Siêu Nhân Nhật Bản',
  5395. 'tags': [],
  5396. 'description': '',
  5397. 'channel_url': 'https://www.youtube.com/channel/UCTYLiWFZy8xtPwxFwX9rV7Q',
  5398. 'channel_id': 'UCTYLiWFZy8xtPwxFwX9rV7Q',
  5399. 'modified_date': r're:\d{8}',
  5400. 'availability': 'public',
  5401. 'uploader_url': 'https://www.youtube.com/@phimsieunhannhatban',
  5402. 'uploader_id': '@phimsieunhannhatban',
  5403. 'uploader': 'Phim Siêu Nhân Nhật Bản',
  5404. },
  5405. 'playlist_mincount': 200,
  5406. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
  5407. }, {
  5408. 'note': 'Playlist with unavailable videos in page 7',
  5409. 'url': 'https://www.youtube.com/playlist?list=UU8l9frL61Yl5KFOl87nIm2w',
  5410. 'info_dict': {
  5411. 'title': 'Uploads from BlankTV',
  5412. 'id': 'UU8l9frL61Yl5KFOl87nIm2w',
  5413. 'channel': 'BlankTV',
  5414. 'channel_url': 'https://www.youtube.com/channel/UC8l9frL61Yl5KFOl87nIm2w',
  5415. 'channel_id': 'UC8l9frL61Yl5KFOl87nIm2w',
  5416. 'view_count': int,
  5417. 'tags': [],
  5418. 'modified_date': r're:\d{8}',
  5419. 'description': '',
  5420. 'availability': 'public',
  5421. 'uploader_id': '@blanktv',
  5422. 'uploader': 'BlankTV',
  5423. 'uploader_url': 'https://www.youtube.com/@blanktv',
  5424. },
  5425. 'playlist_mincount': 1000,
  5426. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
  5427. }, {
  5428. 'note': 'https://github.com/ytdl-org/youtube-dl/issues/21844',
  5429. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  5430. 'info_dict': {
  5431. 'title': 'Data Analysis with Dr Mike Pound',
  5432. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  5433. 'description': 'md5:7f567c574d13d3f8c0954d9ffee4e487',
  5434. 'tags': [],
  5435. 'view_count': int,
  5436. 'channel_id': 'UC9-y-6csu5WGm29I7JiwpnA',
  5437. 'channel_url': 'https://www.youtube.com/channel/UC9-y-6csu5WGm29I7JiwpnA',
  5438. 'channel': 'Computerphile',
  5439. 'availability': 'public',
  5440. 'modified_date': '20190712',
  5441. 'uploader_id': '@Computerphile',
  5442. 'uploader': 'Computerphile',
  5443. 'uploader_url': 'https://www.youtube.com/@Computerphile',
  5444. },
  5445. 'playlist_mincount': 11,
  5446. }, {
  5447. 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  5448. 'only_matching': True,
  5449. }, {
  5450. 'note': 'Playlist URL that does not actually serve a playlist',
  5451. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  5452. 'info_dict': {
  5453. 'id': 'FqZTN594JQw',
  5454. 'ext': 'webm',
  5455. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  5456. 'upload_date': '20150526',
  5457. 'license': 'Standard YouTube License',
  5458. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  5459. 'categories': ['People & Blogs'],
  5460. 'tags': list,
  5461. 'view_count': int,
  5462. 'like_count': int,
  5463. },
  5464. 'params': {
  5465. 'skip_download': True,
  5466. },
  5467. 'skip': 'This video is not available.',
  5468. 'add_ie': [YoutubeIE.ie_key()],
  5469. }, {
  5470. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  5471. 'only_matching': True,
  5472. }, {
  5473. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  5474. 'only_matching': True,
  5475. }, {
  5476. 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
  5477. 'info_dict': {
  5478. 'id': 'hGkQjiJLjWQ', # This will keep changing
  5479. 'ext': 'mp4',
  5480. 'title': str,
  5481. 'upload_date': r're:\d{8}',
  5482. 'description': str,
  5483. 'categories': ['News & Politics'],
  5484. 'tags': list,
  5485. 'like_count': int,
  5486. 'release_timestamp': int,
  5487. 'channel': 'Sky News',
  5488. 'channel_id': 'UCoMdktPbSTixAyNGwb-UYkQ',
  5489. 'age_limit': 0,
  5490. 'view_count': int,
  5491. 'thumbnail': r're:https?://i\.ytimg\.com/vi/[^/]+/maxresdefault(?:_live)?\.jpg',
  5492. 'playable_in_embed': True,
  5493. 'release_date': r're:\d+',
  5494. 'availability': 'public',
  5495. 'live_status': 'is_live',
  5496. 'channel_url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ',
  5497. 'channel_follower_count': int,
  5498. 'concurrent_view_count': int,
  5499. 'uploader_url': 'https://www.youtube.com/@SkyNews',
  5500. 'uploader_id': '@SkyNews',
  5501. 'uploader': 'Sky News',
  5502. 'channel_is_verified': True,
  5503. },
  5504. 'params': {
  5505. 'skip_download': True,
  5506. },
  5507. 'expected_warnings': ['Ignoring subtitle tracks found in '],
  5508. }, {
  5509. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  5510. 'info_dict': {
  5511. 'id': 'a48o2S1cPoo',
  5512. 'ext': 'mp4',
  5513. 'title': 'The Young Turks - Live Main Show',
  5514. 'upload_date': '20150715',
  5515. 'license': 'Standard YouTube License',
  5516. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  5517. 'categories': ['News & Politics'],
  5518. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  5519. 'like_count': int,
  5520. },
  5521. 'params': {
  5522. 'skip_download': True,
  5523. },
  5524. 'only_matching': True,
  5525. }, {
  5526. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  5527. 'only_matching': True,
  5528. }, {
  5529. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  5530. 'only_matching': True,
  5531. }, {
  5532. 'note': 'A channel that is not live. Should raise error',
  5533. 'url': 'https://www.youtube.com/user/numberphile/live',
  5534. 'only_matching': True,
  5535. }, {
  5536. 'url': 'https://www.youtube.com/feed/trending',
  5537. 'only_matching': True,
  5538. }, {
  5539. 'url': 'https://www.youtube.com/feed/library',
  5540. 'only_matching': True,
  5541. }, {
  5542. 'url': 'https://www.youtube.com/feed/history',
  5543. 'only_matching': True,
  5544. }, {
  5545. 'url': 'https://www.youtube.com/feed/subscriptions',
  5546. 'only_matching': True,
  5547. }, {
  5548. 'url': 'https://www.youtube.com/feed/watch_later',
  5549. 'only_matching': True,
  5550. }, {
  5551. 'note': 'Recommended - redirects to home page.',
  5552. 'url': 'https://www.youtube.com/feed/recommended',
  5553. 'only_matching': True,
  5554. }, {
  5555. 'note': 'inline playlist with not always working continuations',
  5556. 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
  5557. 'only_matching': True,
  5558. }, {
  5559. 'url': 'https://www.youtube.com/course',
  5560. 'only_matching': True,
  5561. }, {
  5562. 'url': 'https://www.youtube.com/zsecurity',
  5563. 'only_matching': True,
  5564. }, {
  5565. 'url': 'http://www.youtube.com/NASAgovVideo/videos',
  5566. 'only_matching': True,
  5567. }, {
  5568. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  5569. 'only_matching': True,
  5570. }, {
  5571. 'url': 'https://www.youtube.com/hashtag/cctv9',
  5572. 'info_dict': {
  5573. 'id': 'cctv9',
  5574. 'title': 'cctv9 - All',
  5575. 'tags': [],
  5576. },
  5577. 'playlist_mincount': 300, # not consistent but should be over 300
  5578. }, {
  5579. 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
  5580. 'only_matching': True,
  5581. }, {
  5582. 'note': 'Requires Premium: should request additional YTM-info webpage (and have format 141) for videos in playlist',
  5583. 'url': 'https://music.youtube.com/playlist?list=PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
  5584. 'only_matching': True,
  5585. }, {
  5586. 'note': '/browse/ should redirect to /channel/',
  5587. 'url': 'https://music.youtube.com/browse/UC1a8OFewdjuLq6KlF8M_8Ng',
  5588. 'only_matching': True,
  5589. }, {
  5590. 'note': 'VLPL, should redirect to playlist?list=PL...',
  5591. 'url': 'https://music.youtube.com/browse/VLPLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
  5592. 'info_dict': {
  5593. 'id': 'PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq',
  5594. 'description': 'Providing you with copyright free / safe music for gaming, live streaming, studying and more!',
  5595. 'title': 'NCS : All Releases 💿',
  5596. 'channel_url': 'https://www.youtube.com/channel/UC_aEa8K-EOJ3D6gOs7HcyNg',
  5597. 'modified_date': r're:\d{8}',
  5598. 'view_count': int,
  5599. 'channel_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg',
  5600. 'tags': [],
  5601. 'channel': 'NoCopyrightSounds',
  5602. 'availability': 'public',
  5603. 'uploader_url': 'https://www.youtube.com/@NoCopyrightSounds',
  5604. 'uploader': 'NoCopyrightSounds',
  5605. 'uploader_id': '@NoCopyrightSounds',
  5606. },
  5607. 'playlist_mincount': 166,
  5608. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden', 'YouTube Music is not directly supported'],
  5609. }, {
  5610. # TODO: fix 'unviewable' issue with this playlist when reloading with unavailable videos
  5611. 'note': 'Topic, should redirect to playlist?list=UU...',
  5612. 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
  5613. 'info_dict': {
  5614. 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
  5615. 'title': 'Uploads from Royalty Free Music - Topic',
  5616. 'tags': [],
  5617. 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
  5618. 'channel': 'Royalty Free Music - Topic',
  5619. 'view_count': int,
  5620. 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
  5621. 'modified_date': r're:\d{8}',
  5622. 'description': '',
  5623. 'availability': 'public',
  5624. 'uploader': 'Royalty Free Music - Topic',
  5625. },
  5626. 'playlist_mincount': 101,
  5627. 'expected_warnings': ['YouTube Music is not directly supported', r'[Uu]navailable videos (are|will be) hidden'],
  5628. }, {
  5629. # Destination channel with only a hidden self tab (tab id is UCtFRv9O2AHqOZjjynzrv-xg)
  5630. # Treat as a general feed
  5631. 'url': 'https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg',
  5632. 'info_dict': {
  5633. 'id': 'UCtFRv9O2AHqOZjjynzrv-xg',
  5634. 'title': 'UCtFRv9O2AHqOZjjynzrv-xg',
  5635. 'tags': [],
  5636. },
  5637. 'playlist_mincount': 9,
  5638. }, {
  5639. 'note': 'Youtube music Album',
  5640. 'url': 'https://music.youtube.com/browse/MPREb_gTAcphH99wE',
  5641. 'info_dict': {
  5642. 'id': 'OLAK5uy_l1m0thk3g31NmIIz_vMIbWtyv7eZixlH0',
  5643. 'title': 'Album - Royalty Free Music Library V2 (50 Songs)',
  5644. 'tags': [],
  5645. 'view_count': int,
  5646. 'description': '',
  5647. 'availability': 'unlisted',
  5648. 'modified_date': r're:\d{8}',
  5649. },
  5650. 'playlist_count': 50,
  5651. 'expected_warnings': ['YouTube Music is not directly supported'],
  5652. }, {
  5653. 'note': 'unlisted single video playlist',
  5654. 'url': 'https://www.youtube.com/playlist?list=PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
  5655. 'info_dict': {
  5656. 'id': 'PLwL24UFy54GrB3s2KMMfjZscDi1x5Dajf',
  5657. 'title': 'yt-dlp unlisted playlist test',
  5658. 'availability': 'unlisted',
  5659. 'tags': [],
  5660. 'modified_date': '20220418',
  5661. 'channel': 'colethedj',
  5662. 'view_count': int,
  5663. 'description': '',
  5664. 'channel_id': 'UC9zHu_mHU96r19o-wV5Qs1Q',
  5665. 'channel_url': 'https://www.youtube.com/channel/UC9zHu_mHU96r19o-wV5Qs1Q',
  5666. 'uploader_url': 'https://www.youtube.com/@colethedj1894',
  5667. 'uploader_id': '@colethedj1894',
  5668. 'uploader': 'colethedj',
  5669. },
  5670. 'playlist': [{
  5671. 'info_dict': {
  5672. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  5673. 'id': 'BaW_jenozKc',
  5674. '_type': 'url',
  5675. 'ie_key': 'Youtube',
  5676. 'duration': 10,
  5677. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  5678. 'channel_url': 'https://www.youtube.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  5679. 'view_count': int,
  5680. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc',
  5681. 'channel': 'Philipp Hagemeister',
  5682. 'uploader_id': '@PhilippHagemeister',
  5683. 'uploader_url': 'https://www.youtube.com/@PhilippHagemeister',
  5684. 'uploader': 'Philipp Hagemeister',
  5685. },
  5686. }],
  5687. 'playlist_count': 1,
  5688. 'params': {'extract_flat': True},
  5689. }, {
  5690. 'note': 'API Fallback: Recommended - redirects to home page. Requires visitorData',
  5691. 'url': 'https://www.youtube.com/feed/recommended',
  5692. 'info_dict': {
  5693. 'id': 'recommended',
  5694. 'title': 'recommended',
  5695. 'tags': [],
  5696. },
  5697. 'playlist_mincount': 50,
  5698. 'params': {
  5699. 'skip_download': True,
  5700. 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
  5701. },
  5702. }, {
  5703. 'note': 'API Fallback: /videos tab, sorted by oldest first',
  5704. 'url': 'https://www.youtube.com/user/theCodyReeder/videos?view=0&sort=da&flow=grid',
  5705. 'info_dict': {
  5706. 'id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
  5707. 'title': 'Cody\'sLab - Videos',
  5708. 'description': 'md5:d083b7c2f0c67ee7a6c74c3e9b4243fa',
  5709. 'channel': 'Cody\'sLab',
  5710. 'channel_id': 'UCu6mSoMNzHQiBIOCkHUa2Aw',
  5711. 'tags': [],
  5712. 'channel_url': 'https://www.youtube.com/channel/UCu6mSoMNzHQiBIOCkHUa2Aw',
  5713. 'channel_follower_count': int,
  5714. },
  5715. 'playlist_mincount': 650,
  5716. 'params': {
  5717. 'skip_download': True,
  5718. 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
  5719. },
  5720. 'skip': 'Query for sorting no longer works',
  5721. }, {
  5722. 'note': 'API Fallback: Topic, should redirect to playlist?list=UU...',
  5723. 'url': 'https://music.youtube.com/browse/UC9ALqqC4aIeG5iDs7i90Bfw',
  5724. 'info_dict': {
  5725. 'id': 'UU9ALqqC4aIeG5iDs7i90Bfw',
  5726. 'title': 'Uploads from Royalty Free Music - Topic',
  5727. 'modified_date': r're:\d{8}',
  5728. 'channel_id': 'UC9ALqqC4aIeG5iDs7i90Bfw',
  5729. 'description': '',
  5730. 'channel_url': 'https://www.youtube.com/channel/UC9ALqqC4aIeG5iDs7i90Bfw',
  5731. 'tags': [],
  5732. 'channel': 'Royalty Free Music - Topic',
  5733. 'view_count': int,
  5734. 'availability': 'public',
  5735. 'uploader': 'Royalty Free Music - Topic',
  5736. },
  5737. 'playlist_mincount': 101,
  5738. 'params': {
  5739. 'skip_download': True,
  5740. 'extractor_args': {'youtubetab': {'skip': ['webpage']}},
  5741. },
  5742. 'expected_warnings': ['YouTube Music is not directly supported', r'[Uu]navailable videos (are|will be) hidden'],
  5743. }, {
  5744. 'note': 'non-standard redirect to regional channel',
  5745. 'url': 'https://www.youtube.com/channel/UCwVVpHQ2Cs9iGJfpdFngePQ',
  5746. 'only_matching': True,
  5747. }, {
  5748. 'note': 'collaborative playlist (uploader name in the form "by <uploader> and x other(s)")',
  5749. 'url': 'https://www.youtube.com/playlist?list=PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
  5750. 'info_dict': {
  5751. 'id': 'PLx-_-Kk4c89oOHEDQAojOXzEzemXxoqx6',
  5752. 'modified_date': '20220407',
  5753. 'channel_url': 'https://www.youtube.com/channel/UCKcqXmCcyqnhgpA5P0oHH_Q',
  5754. 'tags': [],
  5755. 'availability': 'unlisted',
  5756. 'channel_id': 'UCKcqXmCcyqnhgpA5P0oHH_Q',
  5757. 'channel': 'pukkandan',
  5758. 'description': 'Test for collaborative playlist',
  5759. 'title': 'yt-dlp test - collaborative playlist',
  5760. 'view_count': int,
  5761. 'uploader_url': 'https://www.youtube.com/@pukkandan',
  5762. 'uploader_id': '@pukkandan',
  5763. 'uploader': 'pukkandan',
  5764. },
  5765. 'playlist_mincount': 2,
  5766. }, {
  5767. 'note': 'translated tab name',
  5768. 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/playlists',
  5769. 'info_dict': {
  5770. 'id': 'UCiu-3thuViMebBjw_5nWYrA',
  5771. 'tags': [],
  5772. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  5773. 'description': 'test description',
  5774. 'title': 'cole-dlp-test-acc - 再生リスト',
  5775. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  5776. 'channel': 'cole-dlp-test-acc',
  5777. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  5778. 'uploader_id': '@coletdjnz',
  5779. 'uploader': 'cole-dlp-test-acc',
  5780. },
  5781. 'playlist_mincount': 1,
  5782. 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
  5783. 'expected_warnings': ['Preferring "ja"'],
  5784. }, {
  5785. # XXX: this should really check flat playlist entries, but the test suite doesn't support that
  5786. 'note': 'preferred lang set with playlist with translated video titles',
  5787. 'url': 'https://www.youtube.com/playlist?list=PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
  5788. 'info_dict': {
  5789. 'id': 'PLt5yu3-wZAlQAaPZ5Z-rJoTdbT-45Q7c0',
  5790. 'tags': [],
  5791. 'view_count': int,
  5792. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  5793. 'channel': 'cole-dlp-test-acc',
  5794. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  5795. 'description': 'test',
  5796. 'title': 'dlp test playlist',
  5797. 'availability': 'public',
  5798. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  5799. 'uploader_id': '@coletdjnz',
  5800. 'uploader': 'cole-dlp-test-acc',
  5801. },
  5802. 'playlist_mincount': 1,
  5803. 'params': {'extractor_args': {'youtube': {'lang': ['ja']}}},
  5804. 'expected_warnings': ['Preferring "ja"'],
  5805. }, {
  5806. # shorts audio pivot for 2GtVksBMYFM.
  5807. 'url': 'https://www.youtube.com/feed/sfv_audio_pivot?bp=8gUrCikSJwoLMkd0VmtzQk1ZRk0SCzJHdFZrc0JNWUZNGgsyR3RWa3NCTVlGTQ==',
  5808. 'info_dict': {
  5809. 'id': 'sfv_audio_pivot',
  5810. 'title': 'sfv_audio_pivot',
  5811. 'tags': [],
  5812. },
  5813. 'playlist_mincount': 50,
  5814. }, {
  5815. # Channel with a real live tab (not to be mistaken with streams tab)
  5816. # Do not treat like it should redirect to live stream
  5817. 'url': 'https://www.youtube.com/channel/UCEH7P7kyJIkS_gJf93VYbmg/live',
  5818. 'info_dict': {
  5819. 'id': 'UCEH7P7kyJIkS_gJf93VYbmg',
  5820. 'title': 'UCEH7P7kyJIkS_gJf93VYbmg - Live',
  5821. 'tags': [],
  5822. },
  5823. 'playlist_mincount': 20,
  5824. }, {
  5825. # Tab name is not the same as tab id
  5826. 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/letsplay',
  5827. 'info_dict': {
  5828. 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
  5829. 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Let\'s play',
  5830. 'tags': [],
  5831. },
  5832. 'playlist_mincount': 8,
  5833. }, {
  5834. # Home tab id is literally home. Not to get mistaken with featured
  5835. 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/home',
  5836. 'info_dict': {
  5837. 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
  5838. 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Home',
  5839. 'tags': [],
  5840. },
  5841. 'playlist_mincount': 8,
  5842. }, {
  5843. # Should get three playlists for videos, shorts and streams tabs
  5844. 'url': 'https://www.youtube.com/channel/UCK9V2B22uJYu3N7eR_BT9QA',
  5845. 'info_dict': {
  5846. 'id': 'UCK9V2B22uJYu3N7eR_BT9QA',
  5847. 'title': 'Polka Ch. 尾丸ポルカ',
  5848. 'channel_follower_count': int,
  5849. 'channel_id': 'UCK9V2B22uJYu3N7eR_BT9QA',
  5850. 'channel_url': 'https://www.youtube.com/channel/UCK9V2B22uJYu3N7eR_BT9QA',
  5851. 'description': 'md5:49809d8bf9da539bc48ed5d1f83c33f2',
  5852. 'channel': 'Polka Ch. 尾丸ポルカ',
  5853. 'tags': 'count:35',
  5854. 'uploader_url': 'https://www.youtube.com/@OmaruPolka',
  5855. 'uploader': 'Polka Ch. 尾丸ポルカ',
  5856. 'uploader_id': '@OmaruPolka',
  5857. 'channel_is_verified': True,
  5858. },
  5859. 'playlist_count': 3,
  5860. }, {
  5861. # Shorts tab with channel with handle
  5862. # TODO: fix channel description
  5863. 'url': 'https://www.youtube.com/@NotJustBikes/shorts',
  5864. 'info_dict': {
  5865. 'id': 'UC0intLFzLaudFG-xAvUEO-A',
  5866. 'title': 'Not Just Bikes - Shorts',
  5867. 'tags': 'count:10',
  5868. 'channel_url': 'https://www.youtube.com/channel/UC0intLFzLaudFG-xAvUEO-A',
  5869. 'description': 'md5:5e82545b3a041345927a92d0585df247',
  5870. 'channel_follower_count': int,
  5871. 'channel_id': 'UC0intLFzLaudFG-xAvUEO-A',
  5872. 'channel': 'Not Just Bikes',
  5873. 'uploader_url': 'https://www.youtube.com/@NotJustBikes',
  5874. 'uploader': 'Not Just Bikes',
  5875. 'uploader_id': '@NotJustBikes',
  5876. 'channel_is_verified': True,
  5877. },
  5878. 'playlist_mincount': 10,
  5879. }, {
  5880. # Streams tab
  5881. 'url': 'https://www.youtube.com/channel/UC3eYAvjCVwNHgkaGbXX3sig/streams',
  5882. 'info_dict': {
  5883. 'id': 'UC3eYAvjCVwNHgkaGbXX3sig',
  5884. 'title': '中村悠一 - Live',
  5885. 'tags': 'count:7',
  5886. 'channel_id': 'UC3eYAvjCVwNHgkaGbXX3sig',
  5887. 'channel_url': 'https://www.youtube.com/channel/UC3eYAvjCVwNHgkaGbXX3sig',
  5888. 'channel': '中村悠一',
  5889. 'channel_follower_count': int,
  5890. 'description': 'md5:e744f6c93dafa7a03c0c6deecb157300',
  5891. 'uploader_url': 'https://www.youtube.com/@Yuichi-Nakamura',
  5892. 'uploader_id': '@Yuichi-Nakamura',
  5893. 'uploader': '中村悠一',
  5894. },
  5895. 'playlist_mincount': 60,
  5896. }, {
  5897. # Channel with no uploads and hence no videos, streams, shorts tabs or uploads playlist. This should fail.
  5898. # See test_youtube_lists
  5899. 'url': 'https://www.youtube.com/channel/UC2yXPzFejc422buOIzn_0CA',
  5900. 'only_matching': True,
  5901. }, {
  5902. # No uploads and no UCID given. Should fail with no uploads error
  5903. # See test_youtube_lists
  5904. 'url': 'https://www.youtube.com/news',
  5905. 'only_matching': True,
  5906. }, {
  5907. # No videos tab but has a shorts tab
  5908. 'url': 'https://www.youtube.com/c/TKFShorts',
  5909. 'info_dict': {
  5910. 'id': 'UCgJ5_1F6yJhYLnyMszUdmUg',
  5911. 'title': 'Shorts Break - Shorts',
  5912. 'tags': 'count:48',
  5913. 'channel_id': 'UCgJ5_1F6yJhYLnyMszUdmUg',
  5914. 'channel': 'Shorts Break',
  5915. 'description': 'md5:6de33c5e7ba686e5f3efd4e19c7ef499',
  5916. 'channel_follower_count': int,
  5917. 'channel_url': 'https://www.youtube.com/channel/UCgJ5_1F6yJhYLnyMszUdmUg',
  5918. 'uploader_url': 'https://www.youtube.com/@ShortsBreak_Official',
  5919. 'uploader': 'Shorts Break',
  5920. 'uploader_id': '@ShortsBreak_Official',
  5921. },
  5922. 'playlist_mincount': 30,
  5923. }, {
  5924. # Trending Now Tab. tab id is empty
  5925. 'url': 'https://www.youtube.com/feed/trending',
  5926. 'info_dict': {
  5927. 'id': 'trending',
  5928. 'title': 'trending - Now',
  5929. 'tags': [],
  5930. },
  5931. 'playlist_mincount': 30,
  5932. }, {
  5933. # Trending Gaming Tab. tab id is empty
  5934. 'url': 'https://www.youtube.com/feed/trending?bp=4gIcGhpnYW1pbmdfY29ycHVzX21vc3RfcG9wdWxhcg%3D%3D',
  5935. 'info_dict': {
  5936. 'id': 'trending',
  5937. 'title': 'trending - Gaming',
  5938. 'tags': [],
  5939. },
  5940. 'playlist_mincount': 30,
  5941. }, {
  5942. # Shorts url result in shorts tab
  5943. # TODO: Fix channel id extraction
  5944. 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/shorts',
  5945. 'info_dict': {
  5946. 'id': 'UCiu-3thuViMebBjw_5nWYrA',
  5947. 'title': 'cole-dlp-test-acc - Shorts',
  5948. 'channel': 'cole-dlp-test-acc',
  5949. 'description': 'test description',
  5950. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  5951. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  5952. 'tags': [],
  5953. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  5954. 'uploader_id': '@coletdjnz',
  5955. 'uploader': 'cole-dlp-test-acc',
  5956. },
  5957. 'playlist': [{
  5958. 'info_dict': {
  5959. # Channel data is not currently available for short renderers (as of 2023-03-01)
  5960. '_type': 'url',
  5961. 'ie_key': 'Youtube',
  5962. 'url': 'https://www.youtube.com/shorts/sSM9J5YH_60',
  5963. 'id': 'sSM9J5YH_60',
  5964. 'title': 'SHORT short',
  5965. 'view_count': int,
  5966. 'thumbnails': list,
  5967. },
  5968. }],
  5969. 'params': {'extract_flat': True},
  5970. }, {
  5971. # Live video status should be extracted
  5972. 'url': 'https://www.youtube.com/channel/UCQvWX73GQygcwXOTSf_VDVg/live',
  5973. 'info_dict': {
  5974. 'id': 'UCQvWX73GQygcwXOTSf_VDVg',
  5975. 'title': 'UCQvWX73GQygcwXOTSf_VDVg - Live', # TODO: should be Minecraft - Live or Minecraft - Topic - Live
  5976. 'tags': [],
  5977. },
  5978. 'playlist': [{
  5979. 'info_dict': {
  5980. '_type': 'url',
  5981. 'ie_key': 'Youtube',
  5982. 'url': 'startswith:https://www.youtube.com/watch?v=',
  5983. 'id': str,
  5984. 'title': str,
  5985. 'live_status': 'is_live',
  5986. 'channel_id': str,
  5987. 'channel_url': str,
  5988. 'concurrent_view_count': int,
  5989. 'channel': str,
  5990. 'uploader': str,
  5991. 'uploader_url': str,
  5992. 'uploader_id': str,
  5993. 'channel_is_verified': bool, # this will keep changing
  5994. },
  5995. }],
  5996. 'params': {'extract_flat': True, 'playlist_items': '1'},
  5997. 'playlist_mincount': 1,
  5998. }, {
  5999. # Channel renderer metadata. Contains number of videos on the channel
  6000. 'url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA/channels',
  6001. 'info_dict': {
  6002. 'id': 'UCiu-3thuViMebBjw_5nWYrA',
  6003. 'title': 'cole-dlp-test-acc - Channels',
  6004. 'channel': 'cole-dlp-test-acc',
  6005. 'description': 'test description',
  6006. 'channel_id': 'UCiu-3thuViMebBjw_5nWYrA',
  6007. 'channel_url': 'https://www.youtube.com/channel/UCiu-3thuViMebBjw_5nWYrA',
  6008. 'tags': [],
  6009. 'uploader_url': 'https://www.youtube.com/@coletdjnz',
  6010. 'uploader_id': '@coletdjnz',
  6011. 'uploader': 'cole-dlp-test-acc',
  6012. },
  6013. 'playlist': [{
  6014. 'info_dict': {
  6015. '_type': 'url',
  6016. 'ie_key': 'YoutubeTab',
  6017. 'url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
  6018. 'id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
  6019. 'channel_id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
  6020. 'title': 'PewDiePie',
  6021. 'channel': 'PewDiePie',
  6022. 'channel_url': 'https://www.youtube.com/channel/UC-lHJZR3Gqxm24_Vd_AJ5Yw',
  6023. 'thumbnails': list,
  6024. 'channel_follower_count': int,
  6025. 'playlist_count': int,
  6026. 'uploader': 'PewDiePie',
  6027. 'uploader_url': 'https://www.youtube.com/@PewDiePie',
  6028. 'uploader_id': '@PewDiePie',
  6029. 'channel_is_verified': True,
  6030. },
  6031. }],
  6032. 'params': {'extract_flat': True},
  6033. }, {
  6034. 'url': 'https://www.youtube.com/@3blue1brown/about',
  6035. 'info_dict': {
  6036. 'id': '@3blue1brown',
  6037. 'tags': ['Mathematics'],
  6038. 'title': '3Blue1Brown',
  6039. 'channel_follower_count': int,
  6040. 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
  6041. 'channel': '3Blue1Brown',
  6042. 'channel_url': 'https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw',
  6043. 'description': 'md5:4d1da95432004b7ba840ebc895b6b4c9',
  6044. 'uploader_url': 'https://www.youtube.com/@3blue1brown',
  6045. 'uploader_id': '@3blue1brown',
  6046. 'uploader': '3Blue1Brown',
  6047. 'channel_is_verified': True,
  6048. },
  6049. 'playlist_count': 0,
  6050. }, {
  6051. # Podcasts tab, with rich entry playlistRenderers
  6052. 'url': 'https://www.youtube.com/@99percentinvisiblepodcast/podcasts',
  6053. 'info_dict': {
  6054. 'id': 'UCVMF2HD4ZgC0QHpU9Yq5Xrw',
  6055. 'channel_id': 'UCVMF2HD4ZgC0QHpU9Yq5Xrw',
  6056. 'uploader_url': 'https://www.youtube.com/@99percentinvisiblepodcast',
  6057. 'description': 'md5:3a0ed38f1ad42a68ef0428c04a15695c',
  6058. 'title': '99 Percent Invisible - Podcasts',
  6059. 'uploader': '99 Percent Invisible',
  6060. 'channel_follower_count': int,
  6061. 'channel_url': 'https://www.youtube.com/channel/UCVMF2HD4ZgC0QHpU9Yq5Xrw',
  6062. 'tags': [],
  6063. 'channel': '99 Percent Invisible',
  6064. 'uploader_id': '@99percentinvisiblepodcast',
  6065. },
  6066. 'playlist_count': 0,
  6067. }, {
  6068. # Releases tab, with rich entry playlistRenderers (same as Podcasts tab)
  6069. 'url': 'https://www.youtube.com/@AHimitsu/releases',
  6070. 'info_dict': {
  6071. 'id': 'UCgFwu-j5-xNJml2FtTrrB3A',
  6072. 'channel': 'A Himitsu',
  6073. 'uploader_url': 'https://www.youtube.com/@AHimitsu',
  6074. 'title': 'A Himitsu - Releases',
  6075. 'uploader_id': '@AHimitsu',
  6076. 'uploader': 'A Himitsu',
  6077. 'channel_id': 'UCgFwu-j5-xNJml2FtTrrB3A',
  6078. 'tags': 'count:12',
  6079. 'description': 'I make music',
  6080. 'channel_url': 'https://www.youtube.com/channel/UCgFwu-j5-xNJml2FtTrrB3A',
  6081. 'channel_follower_count': int,
  6082. 'channel_is_verified': True,
  6083. },
  6084. 'playlist_mincount': 10,
  6085. }, {
  6086. # Playlist with only shorts, shown as reel renderers
  6087. # FIXME: future: YouTube currently doesn't give continuation for this,
  6088. # may do in future.
  6089. 'url': 'https://www.youtube.com/playlist?list=UUxqPAgubo4coVn9Lx1FuKcg',
  6090. 'info_dict': {
  6091. 'id': 'UUxqPAgubo4coVn9Lx1FuKcg',
  6092. 'channel_url': 'https://www.youtube.com/channel/UCxqPAgubo4coVn9Lx1FuKcg',
  6093. 'view_count': int,
  6094. 'uploader_id': '@BangyShorts',
  6095. 'description': '',
  6096. 'uploader_url': 'https://www.youtube.com/@BangyShorts',
  6097. 'channel_id': 'UCxqPAgubo4coVn9Lx1FuKcg',
  6098. 'channel': 'Bangy Shorts',
  6099. 'uploader': 'Bangy Shorts',
  6100. 'tags': [],
  6101. 'availability': 'public',
  6102. 'modified_date': r're:\d{8}',
  6103. 'title': 'Uploads from Bangy Shorts',
  6104. },
  6105. 'playlist_mincount': 100,
  6106. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
  6107. }, {
  6108. 'note': 'Tags containing spaces',
  6109. 'url': 'https://www.youtube.com/channel/UC7_YxT-KID8kRbqZo7MyscQ',
  6110. 'playlist_count': 3,
  6111. 'info_dict': {
  6112. 'id': 'UC7_YxT-KID8kRbqZo7MyscQ',
  6113. 'channel': 'Markiplier',
  6114. 'channel_id': 'UC7_YxT-KID8kRbqZo7MyscQ',
  6115. 'title': 'Markiplier',
  6116. 'channel_follower_count': int,
  6117. 'description': 'md5:0c010910558658824402809750dc5d97',
  6118. 'uploader_id': '@markiplier',
  6119. 'uploader_url': 'https://www.youtube.com/@markiplier',
  6120. 'uploader': 'Markiplier',
  6121. 'channel_url': 'https://www.youtube.com/channel/UC7_YxT-KID8kRbqZo7MyscQ',
  6122. 'channel_is_verified': True,
  6123. 'tags': ['markiplier', 'comedy', 'gaming', 'funny videos', 'funny moments',
  6124. 'sketch comedy', 'laughing', 'lets play', 'challenge videos', 'hilarious',
  6125. 'challenges', 'sketches', 'scary games', 'funny games', 'rage games',
  6126. 'mark fischbach'],
  6127. },
  6128. }]
  6129. @classmethod
  6130. def suitable(cls, url):
  6131. return False if YoutubeIE.suitable(url) else super().suitable(url)
  6132. _URL_RE = re.compile(rf'(?P<pre>{_VALID_URL})(?(not_channel)|(?P<tab>/[^?#/]+))?(?P<post>.*)$')
  6133. def _get_url_mobj(self, url):
  6134. mobj = self._URL_RE.match(url).groupdict()
  6135. mobj.update((k, '') for k, v in mobj.items() if v is None)
  6136. return mobj
  6137. def _extract_tab_id_and_name(self, tab, base_url='https://www.youtube.com'):
  6138. tab_name = (tab.get('title') or '').lower()
  6139. tab_url = urljoin(base_url, traverse_obj(
  6140. tab, ('endpoint', 'commandMetadata', 'webCommandMetadata', 'url')))
  6141. tab_id = (tab_url and self._get_url_mobj(tab_url)['tab'][1:]
  6142. or traverse_obj(tab, 'tabIdentifier', expected_type=str))
  6143. if tab_id:
  6144. return {
  6145. 'TAB_ID_SPONSORSHIPS': 'membership',
  6146. }.get(tab_id, tab_id), tab_name
  6147. # Fallback to tab name if we cannot get the tab id.
  6148. # XXX: should we strip non-ascii letters? e.g. in case of 'let's play' tab example on special gaming channel
  6149. # Note that in the case of translated tab name this may result in an empty string, which we don't want.
  6150. if tab_name:
  6151. self.write_debug(f'Falling back to selected tab name: {tab_name}')
  6152. return {
  6153. 'home': 'featured',
  6154. 'live': 'streams',
  6155. }.get(tab_name, tab_name), tab_name
  6156. def _has_tab(self, tabs, tab_id):
  6157. return any(self._extract_tab_id_and_name(tab)[0] == tab_id for tab in tabs)
  6158. def _empty_playlist(self, item_id, data):
  6159. return self.playlist_result([], item_id, **self._extract_metadata_from_tabs(item_id, data))
  6160. @YoutubeTabBaseInfoExtractor.passthrough_smuggled_data
  6161. def _real_extract(self, url, smuggled_data):
  6162. item_id = self._match_id(url)
  6163. url = urllib.parse.urlunparse(
  6164. urllib.parse.urlparse(url)._replace(netloc='www.youtube.com'))
  6165. compat_opts = self.get_param('compat_opts', [])
  6166. mobj = self._get_url_mobj(url)
  6167. pre, tab, post, is_channel = mobj['pre'], mobj['tab'], mobj['post'], not mobj['not_channel']
  6168. if is_channel and smuggled_data.get('is_music_url'):
  6169. if item_id[:2] == 'VL': # Youtube music VL channels have an equivalent playlist
  6170. return self.url_result(
  6171. f'https://music.youtube.com/playlist?list={item_id[2:]}', YoutubeTabIE, item_id[2:])
  6172. elif item_id[:2] == 'MP': # Resolve albums (/[channel/browse]/MP...) to their equivalent playlist
  6173. mdata = self._extract_tab_endpoint(
  6174. f'https://music.youtube.com/channel/{item_id}', item_id, default_client='web_music')
  6175. murl = traverse_obj(mdata, ('microformat', 'microformatDataRenderer', 'urlCanonical'),
  6176. get_all=False, expected_type=str)
  6177. if not murl:
  6178. raise ExtractorError('Failed to resolve album to playlist')
  6179. return self.url_result(murl, YoutubeTabIE)
  6180. elif mobj['channel_type'] == 'browse': # Youtube music /browse/ should be changed to /channel/
  6181. return self.url_result(
  6182. f'https://music.youtube.com/channel/{item_id}{tab}{post}', YoutubeTabIE, item_id)
  6183. original_tab_id, display_id = tab[1:], f'{item_id}{tab}'
  6184. if is_channel and not tab and 'no-youtube-channel-redirect' not in compat_opts:
  6185. url = f'{pre}/videos{post}'
  6186. if smuggled_data.get('is_music_url'):
  6187. self.report_warning(f'YouTube Music is not directly supported. Redirecting to {url}')
  6188. # Handle both video/playlist URLs
  6189. qs = parse_qs(url)
  6190. video_id, playlist_id = (traverse_obj(qs, (key, 0)) for key in ('v', 'list'))
  6191. if not video_id and mobj['not_channel'].startswith('watch'):
  6192. if not playlist_id:
  6193. # If there is neither video or playlist ids, youtube redirects to home page, which is undesirable
  6194. raise ExtractorError('A video URL was given without video ID', expected=True)
  6195. # Common mistake: https://www.youtube.com/watch?list=playlist_id
  6196. self.report_warning(f'A video URL was given without video ID. Trying to download playlist {playlist_id}')
  6197. return self.url_result(
  6198. f'https://www.youtube.com/playlist?list={playlist_id}', YoutubeTabIE, playlist_id)
  6199. if not self._yes_playlist(playlist_id, video_id):
  6200. return self.url_result(
  6201. f'https://www.youtube.com/watch?v={video_id}', YoutubeIE, video_id)
  6202. data, ytcfg = self._extract_data(url, display_id)
  6203. # YouTube may provide a non-standard redirect to the regional channel
  6204. # See: https://github.com/yt-dlp/yt-dlp/issues/2694
  6205. # https://support.google.com/youtube/answer/2976814#zippy=,conditional-redirects
  6206. redirect_url = traverse_obj(
  6207. data, ('onResponseReceivedActions', ..., 'navigateAction', 'endpoint', 'commandMetadata', 'webCommandMetadata', 'url'), get_all=False)
  6208. if redirect_url and 'no-youtube-channel-redirect' not in compat_opts:
  6209. redirect_url = ''.join((urljoin('https://www.youtube.com', redirect_url), tab, post))
  6210. self.to_screen(f'This playlist is likely not available in your region. Following conditional redirect to {redirect_url}')
  6211. return self.url_result(redirect_url, YoutubeTabIE)
  6212. tabs, extra_tabs = self._extract_tab_renderers(data), []
  6213. if is_channel and tabs and 'no-youtube-channel-redirect' not in compat_opts:
  6214. selected_tab = self._extract_selected_tab(tabs)
  6215. selected_tab_id, selected_tab_name = self._extract_tab_id_and_name(selected_tab, url) # NB: Name may be translated
  6216. self.write_debug(f'Selected tab: {selected_tab_id!r} ({selected_tab_name}), Requested tab: {original_tab_id!r}')
  6217. # /about is no longer a tab
  6218. if original_tab_id == 'about':
  6219. return self._empty_playlist(item_id, data)
  6220. if not original_tab_id and selected_tab_name:
  6221. self.to_screen('Downloading all uploads of the channel. '
  6222. 'To download only the videos in a specific tab, pass the tab\'s URL')
  6223. if self._has_tab(tabs, 'streams'):
  6224. extra_tabs.append(''.join((pre, '/streams', post)))
  6225. if self._has_tab(tabs, 'shorts'):
  6226. extra_tabs.append(''.join((pre, '/shorts', post)))
  6227. # XXX: Members-only tab should also be extracted
  6228. if not extra_tabs and selected_tab_id != 'videos':
  6229. # Channel does not have streams, shorts or videos tabs
  6230. if item_id[:2] != 'UC':
  6231. return self._empty_playlist(item_id, data)
  6232. # Topic channels don't have /videos. Use the equivalent playlist instead
  6233. pl_id = f'UU{item_id[2:]}'
  6234. pl_url = f'https://www.youtube.com/playlist?list={pl_id}'
  6235. try:
  6236. data, ytcfg = self._extract_data(pl_url, pl_id, ytcfg=ytcfg, fatal=True, webpage_fatal=True)
  6237. except ExtractorError:
  6238. return self._empty_playlist(item_id, data)
  6239. else:
  6240. item_id, url = pl_id, pl_url
  6241. self.to_screen(
  6242. f'The channel does not have a videos, shorts, or live tab. Redirecting to playlist {pl_id} instead')
  6243. elif extra_tabs and selected_tab_id != 'videos':
  6244. # When there are shorts/live tabs but not videos tab
  6245. url, data = f'{pre}{post}', None
  6246. elif (original_tab_id or 'videos') != selected_tab_id:
  6247. if original_tab_id == 'live':
  6248. # Live tab should have redirected to the video
  6249. # Except in the case the channel has an actual live tab
  6250. # Example: https://www.youtube.com/channel/UCEH7P7kyJIkS_gJf93VYbmg/live
  6251. raise UserNotLive(video_id=item_id)
  6252. elif selected_tab_name:
  6253. raise ExtractorError(f'This channel does not have a {original_tab_id} tab', expected=True)
  6254. # For channels such as https://www.youtube.com/channel/UCtFRv9O2AHqOZjjynzrv-xg
  6255. url = f'{pre}{post}'
  6256. # YouTube sometimes provides a button to reload playlist with unavailable videos.
  6257. if 'no-youtube-unavailable-videos' not in compat_opts:
  6258. data = self._reload_with_unavailable_videos(display_id, data, ytcfg) or data
  6259. self._extract_and_report_alerts(data, only_once=True)
  6260. tabs, entries = self._extract_tab_renderers(data), []
  6261. if tabs:
  6262. entries = [self._extract_from_tabs(item_id, ytcfg, data, tabs)]
  6263. entries[0].update({
  6264. 'extractor_key': YoutubeTabIE.ie_key(),
  6265. 'extractor': YoutubeTabIE.IE_NAME,
  6266. 'webpage_url': url,
  6267. })
  6268. if self.get_param('playlist_items') == '0':
  6269. entries.extend(self.url_result(u, YoutubeTabIE) for u in extra_tabs)
  6270. else: # Users expect to get all `video_id`s even with `--flat-playlist`. So don't return `url_result`
  6271. entries.extend(map(self._real_extract, extra_tabs))
  6272. if len(entries) == 1:
  6273. return entries[0]
  6274. elif entries:
  6275. metadata = self._extract_metadata_from_tabs(item_id, data)
  6276. uploads_url = 'the Uploads (UU) playlist URL'
  6277. if try_get(metadata, lambda x: x['channel_id'].startswith('UC')):
  6278. uploads_url = f'https://www.youtube.com/playlist?list=UU{metadata["channel_id"][2:]}'
  6279. self.to_screen(
  6280. 'Downloading as multiple playlists, separated by tabs. '
  6281. f'To download as a single playlist instead, pass {uploads_url}')
  6282. return self.playlist_result(entries, item_id, **metadata)
  6283. # Inline playlist
  6284. playlist = traverse_obj(
  6285. data, ('contents', 'twoColumnWatchNextResults', 'playlist', 'playlist'), expected_type=dict)
  6286. if playlist:
  6287. return self._extract_from_playlist(item_id, url, data, playlist, ytcfg)
  6288. video_id = traverse_obj(
  6289. data, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'), expected_type=str) or video_id
  6290. if video_id:
  6291. if tab != '/live': # live tab is expected to redirect to video
  6292. self.report_warning(f'Unable to recognize playlist. Downloading just video {video_id}')
  6293. return self.url_result(f'https://www.youtube.com/watch?v={video_id}', YoutubeIE, video_id)
  6294. raise ExtractorError('Unable to recognize tab page')
  6295. class YoutubePlaylistIE(InfoExtractor):
  6296. IE_DESC = 'YouTube playlists'
  6297. _VALID_URL = r'''(?x)(?:
  6298. (?:https?://)?
  6299. (?:\w+\.)?
  6300. (?:
  6301. (?:
  6302. youtube(?:kids)?\.com|
  6303. {invidious}
  6304. )
  6305. /.*?\?.*?\blist=
  6306. )?
  6307. (?P<id>{playlist_id})
  6308. )'''.format(
  6309. playlist_id=YoutubeBaseInfoExtractor._PLAYLIST_ID_RE,
  6310. invidious='|'.join(YoutubeBaseInfoExtractor._INVIDIOUS_SITES),
  6311. )
  6312. IE_NAME = 'youtube:playlist'
  6313. _TESTS = [{
  6314. 'note': 'issue #673',
  6315. 'url': 'PLBB231211A4F62143',
  6316. 'info_dict': {
  6317. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  6318. 'id': 'PLBB231211A4F62143',
  6319. 'uploader': 'Wickman',
  6320. 'uploader_id': '@WickmanVT',
  6321. 'description': 'md5:8fa6f52abb47a9552002fa3ddfc57fc2',
  6322. 'view_count': int,
  6323. 'uploader_url': 'https://www.youtube.com/@WickmanVT',
  6324. 'modified_date': r're:\d{8}',
  6325. 'channel_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
  6326. 'channel': 'Wickman',
  6327. 'tags': [],
  6328. 'channel_url': 'https://www.youtube.com/channel/UCKSpbfbl5kRQpTdL7kMc-1Q',
  6329. 'availability': 'public',
  6330. },
  6331. 'playlist_mincount': 29,
  6332. }, {
  6333. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  6334. 'info_dict': {
  6335. 'title': 'YDL_safe_search',
  6336. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  6337. },
  6338. 'playlist_count': 2,
  6339. 'skip': 'This playlist is private',
  6340. }, {
  6341. 'note': 'embedded',
  6342. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  6343. 'playlist_count': 4,
  6344. 'info_dict': {
  6345. 'title': 'JODA15',
  6346. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  6347. 'uploader': 'milan',
  6348. 'uploader_id': '@milan5503',
  6349. 'description': '',
  6350. 'channel_url': 'https://www.youtube.com/channel/UCEI1-PVPcYXjB73Hfelbmaw',
  6351. 'tags': [],
  6352. 'modified_date': '20140919',
  6353. 'view_count': int,
  6354. 'channel': 'milan',
  6355. 'channel_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  6356. 'uploader_url': 'https://www.youtube.com/@milan5503',
  6357. 'availability': 'public',
  6358. },
  6359. 'expected_warnings': [r'[Uu]navailable videos? (is|are|will be) hidden', 'Retrying', 'Giving up'],
  6360. }, {
  6361. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  6362. 'playlist_mincount': 455,
  6363. 'info_dict': {
  6364. 'title': '2018 Chinese New Singles (11/6 updated)',
  6365. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  6366. 'uploader': 'LBK',
  6367. 'uploader_id': '@music_king',
  6368. 'description': 'md5:da521864744d60a198e3a88af4db0d9d',
  6369. 'channel': 'LBK',
  6370. 'view_count': int,
  6371. 'channel_url': 'https://www.youtube.com/channel/UC21nz3_MesPLqtDqwdvnoxA',
  6372. 'tags': [],
  6373. 'uploader_url': 'https://www.youtube.com/@music_king',
  6374. 'channel_id': 'UC21nz3_MesPLqtDqwdvnoxA',
  6375. 'modified_date': r're:\d{8}',
  6376. 'availability': 'public',
  6377. },
  6378. 'expected_warnings': [r'[Uu]navailable videos (are|will be) hidden'],
  6379. }, {
  6380. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  6381. 'only_matching': True,
  6382. }, {
  6383. # music album playlist
  6384. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  6385. 'only_matching': True,
  6386. }]
  6387. @classmethod
  6388. def suitable(cls, url):
  6389. if YoutubeTabIE.suitable(url):
  6390. return False
  6391. from ..utils import parse_qs
  6392. qs = parse_qs(url)
  6393. if qs.get('v', [None])[0]:
  6394. return False
  6395. return super().suitable(url)
  6396. def _real_extract(self, url):
  6397. playlist_id = self._match_id(url)
  6398. is_music_url = YoutubeBaseInfoExtractor.is_music_url(url)
  6399. url = update_url_query(
  6400. 'https://www.youtube.com/playlist',
  6401. parse_qs(url) or {'list': playlist_id})
  6402. if is_music_url:
  6403. url = smuggle_url(url, {'is_music_url': True})
  6404. return self.url_result(url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  6405. class YoutubeYtBeIE(InfoExtractor):
  6406. IE_DESC = 'youtu.be'
  6407. _VALID_URL = rf'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{{11}})/*?.*?\blist=(?P<playlist_id>{YoutubeBaseInfoExtractor._PLAYLIST_ID_RE})'
  6408. _TESTS = [{
  6409. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  6410. 'info_dict': {
  6411. 'id': 'yeWKywCrFtk',
  6412. 'ext': 'mp4',
  6413. 'title': 'Small Scale Baler and Braiding Rugs',
  6414. 'uploader': 'Backus-Page House Museum',
  6415. 'uploader_id': '@backuspagemuseum',
  6416. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@backuspagemuseum',
  6417. 'upload_date': '20161008',
  6418. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  6419. 'categories': ['Nonprofits & Activism'],
  6420. 'tags': list,
  6421. 'like_count': int,
  6422. 'age_limit': 0,
  6423. 'playable_in_embed': True,
  6424. 'thumbnail': r're:^https?://.*\.webp',
  6425. 'channel': 'Backus-Page House Museum',
  6426. 'channel_id': 'UCEfMCQ9bs3tjvjy1s451zaw',
  6427. 'live_status': 'not_live',
  6428. 'view_count': int,
  6429. 'channel_url': 'https://www.youtube.com/channel/UCEfMCQ9bs3tjvjy1s451zaw',
  6430. 'availability': 'public',
  6431. 'duration': 59,
  6432. 'comment_count': int,
  6433. 'channel_follower_count': int,
  6434. },
  6435. 'params': {
  6436. 'noplaylist': True,
  6437. 'skip_download': True,
  6438. },
  6439. }, {
  6440. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  6441. 'only_matching': True,
  6442. }]
  6443. def _real_extract(self, url):
  6444. mobj = self._match_valid_url(url)
  6445. video_id = mobj.group('id')
  6446. playlist_id = mobj.group('playlist_id')
  6447. return self.url_result(
  6448. update_url_query('https://www.youtube.com/watch', {
  6449. 'v': video_id,
  6450. 'list': playlist_id,
  6451. 'feature': 'youtu.be',
  6452. }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  6453. class YoutubeLivestreamEmbedIE(InfoExtractor):
  6454. IE_DESC = 'YouTube livestream embeds'
  6455. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/embed/live_stream/?\?(?:[^#]+&)?channel=(?P<id>[^&#]+)'
  6456. _TESTS = [{
  6457. 'url': 'https://www.youtube.com/embed/live_stream?channel=UC2_KI6RB__jGdlnK6dvFEZA',
  6458. 'only_matching': True,
  6459. }]
  6460. def _real_extract(self, url):
  6461. channel_id = self._match_id(url)
  6462. return self.url_result(
  6463. f'https://www.youtube.com/channel/{channel_id}/live',
  6464. ie=YoutubeTabIE.ie_key(), video_id=channel_id)
  6465. class YoutubeYtUserIE(InfoExtractor):
  6466. IE_DESC = 'YouTube user videos; "ytuser:" prefix'
  6467. IE_NAME = 'youtube:user'
  6468. _VALID_URL = r'ytuser:(?P<id>.+)'
  6469. _TESTS = [{
  6470. 'url': 'ytuser:phihag',
  6471. 'only_matching': True,
  6472. }]
  6473. def _real_extract(self, url):
  6474. user_id = self._match_id(url)
  6475. return self.url_result(f'https://www.youtube.com/user/{user_id}', YoutubeTabIE, user_id)
  6476. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  6477. IE_NAME = 'youtube:favorites'
  6478. IE_DESC = 'YouTube liked videos; ":ytfav" keyword (requires cookies)'
  6479. _VALID_URL = r':ytfav(?:ou?rite)?s?'
  6480. _LOGIN_REQUIRED = True
  6481. _TESTS = [{
  6482. 'url': ':ytfav',
  6483. 'only_matching': True,
  6484. }, {
  6485. 'url': ':ytfavorites',
  6486. 'only_matching': True,
  6487. }]
  6488. def _real_extract(self, url):
  6489. return self.url_result(
  6490. 'https://www.youtube.com/playlist?list=LL',
  6491. ie=YoutubeTabIE.ie_key())
  6492. class YoutubeNotificationsIE(YoutubeTabBaseInfoExtractor):
  6493. IE_NAME = 'youtube:notif'
  6494. IE_DESC = 'YouTube notifications; ":ytnotif" keyword (requires cookies)'
  6495. _VALID_URL = r':ytnotif(?:ication)?s?'
  6496. _LOGIN_REQUIRED = True
  6497. _TESTS = [{
  6498. 'url': ':ytnotif',
  6499. 'only_matching': True,
  6500. }, {
  6501. 'url': ':ytnotifications',
  6502. 'only_matching': True,
  6503. }]
  6504. def _extract_notification_menu(self, response, continuation_list):
  6505. notification_list = traverse_obj(
  6506. response,
  6507. ('actions', 0, 'openPopupAction', 'popup', 'multiPageMenuRenderer', 'sections', 0, 'multiPageMenuNotificationSectionRenderer', 'items'),
  6508. ('actions', 0, 'appendContinuationItemsAction', 'continuationItems'),
  6509. expected_type=list) or []
  6510. continuation_list[0] = None
  6511. for item in notification_list:
  6512. entry = self._extract_notification_renderer(item.get('notificationRenderer'))
  6513. if entry:
  6514. yield entry
  6515. continuation = item.get('continuationItemRenderer')
  6516. if continuation:
  6517. continuation_list[0] = continuation
  6518. def _extract_notification_renderer(self, notification):
  6519. video_id = traverse_obj(
  6520. notification, ('navigationEndpoint', 'watchEndpoint', 'videoId'), expected_type=str)
  6521. url = f'https://www.youtube.com/watch?v={video_id}'
  6522. channel_id = None
  6523. if not video_id:
  6524. browse_ep = traverse_obj(
  6525. notification, ('navigationEndpoint', 'browseEndpoint'), expected_type=dict)
  6526. channel_id = self.ucid_or_none(traverse_obj(browse_ep, 'browseId', expected_type=str))
  6527. post_id = self._search_regex(
  6528. r'/post/(.+)', traverse_obj(browse_ep, 'canonicalBaseUrl', expected_type=str),
  6529. 'post id', default=None)
  6530. if not channel_id or not post_id:
  6531. return
  6532. # The direct /post url redirects to this in the browser
  6533. url = f'https://www.youtube.com/channel/{channel_id}/community?lb={post_id}'
  6534. channel = traverse_obj(
  6535. notification, ('contextualMenu', 'menuRenderer', 'items', 1, 'menuServiceItemRenderer', 'text', 'runs', 1, 'text'),
  6536. expected_type=str)
  6537. notification_title = self._get_text(notification, 'shortMessage')
  6538. if notification_title:
  6539. notification_title = notification_title.replace('\xad', '') # remove soft hyphens
  6540. # TODO: handle recommended videos
  6541. title = self._search_regex(
  6542. rf'{re.escape(channel or "")}[^:]+: (.+)', notification_title,
  6543. 'video title', default=None)
  6544. timestamp = (self._parse_time_text(self._get_text(notification, 'sentTimeText'))
  6545. if self._configuration_arg('approximate_date', ie_key=YoutubeTabIE)
  6546. else None)
  6547. return {
  6548. '_type': 'url',
  6549. 'url': url,
  6550. 'ie_key': (YoutubeIE if video_id else YoutubeTabIE).ie_key(),
  6551. 'video_id': video_id,
  6552. 'title': title,
  6553. 'channel_id': channel_id,
  6554. 'channel': channel,
  6555. 'uploader': channel,
  6556. 'thumbnails': self._extract_thumbnails(notification, 'videoThumbnail'),
  6557. 'timestamp': timestamp,
  6558. }
  6559. def _notification_menu_entries(self, ytcfg):
  6560. continuation_list = [None]
  6561. response = None
  6562. for page in itertools.count(1):
  6563. ctoken = traverse_obj(
  6564. continuation_list, (0, 'continuationEndpoint', 'getNotificationMenuEndpoint', 'ctoken'), expected_type=str)
  6565. response = self._extract_response(
  6566. item_id=f'page {page}', query={'ctoken': ctoken} if ctoken else {}, ytcfg=ytcfg,
  6567. ep='notification/get_notification_menu', check_get_keys='actions',
  6568. headers=self.generate_api_headers(ytcfg=ytcfg, visitor_data=self._extract_visitor_data(response)))
  6569. yield from self._extract_notification_menu(response, continuation_list)
  6570. if not continuation_list[0]:
  6571. break
  6572. def _real_extract(self, url):
  6573. display_id = 'notifications'
  6574. ytcfg = self._download_ytcfg('web', display_id) if not self.skip_webpage else {}
  6575. self._report_playlist_authcheck(ytcfg)
  6576. return self.playlist_result(self._notification_menu_entries(ytcfg), display_id, display_id)
  6577. class YoutubeSearchIE(YoutubeTabBaseInfoExtractor, SearchInfoExtractor):
  6578. IE_DESC = 'YouTube search'
  6579. IE_NAME = 'youtube:search'
  6580. _SEARCH_KEY = 'ytsearch'
  6581. _SEARCH_PARAMS = 'EgIQAfABAQ==' # Videos only
  6582. _TESTS = [{
  6583. 'url': 'ytsearch5:youtube-dl test video',
  6584. 'playlist_count': 5,
  6585. 'info_dict': {
  6586. 'id': 'youtube-dl test video',
  6587. 'title': 'youtube-dl test video',
  6588. },
  6589. }, {
  6590. 'note': 'Suicide/self-harm search warning',
  6591. 'url': 'ytsearch1:i hate myself and i wanna die',
  6592. 'playlist_count': 1,
  6593. 'info_dict': {
  6594. 'id': 'i hate myself and i wanna die',
  6595. 'title': 'i hate myself and i wanna die',
  6596. },
  6597. }]
  6598. class YoutubeSearchDateIE(YoutubeTabBaseInfoExtractor, SearchInfoExtractor):
  6599. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  6600. _SEARCH_KEY = 'ytsearchdate'
  6601. IE_DESC = 'YouTube search, newest videos first'
  6602. _SEARCH_PARAMS = 'CAISAhAB8AEB' # Videos only, sorted by date
  6603. _TESTS = [{
  6604. 'url': 'ytsearchdate5:youtube-dl test video',
  6605. 'playlist_count': 5,
  6606. 'info_dict': {
  6607. 'id': 'youtube-dl test video',
  6608. 'title': 'youtube-dl test video',
  6609. },
  6610. }]
  6611. class YoutubeSearchURLIE(YoutubeTabBaseInfoExtractor):
  6612. IE_DESC = 'YouTube search URLs with sorting and filter support'
  6613. IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
  6614. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:results|search)\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
  6615. _TESTS = [{
  6616. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  6617. 'playlist_mincount': 5,
  6618. 'info_dict': {
  6619. 'id': 'youtube-dl test video',
  6620. 'title': 'youtube-dl test video',
  6621. },
  6622. }, {
  6623. 'url': 'https://www.youtube.com/results?search_query=python&sp=EgIQAg%253D%253D',
  6624. 'playlist_mincount': 5,
  6625. 'info_dict': {
  6626. 'id': 'python',
  6627. 'title': 'python',
  6628. },
  6629. }, {
  6630. 'url': 'https://www.youtube.com/results?search_query=%23cats',
  6631. 'playlist_mincount': 1,
  6632. 'info_dict': {
  6633. 'id': '#cats',
  6634. 'title': '#cats',
  6635. # The test suite does not have support for nested playlists
  6636. # 'entries': [{
  6637. # 'url': r're:https://(www\.)?youtube\.com/hashtag/cats',
  6638. # 'title': '#cats',
  6639. # }],
  6640. },
  6641. }, {
  6642. # Channel results
  6643. 'url': 'https://www.youtube.com/results?search_query=kurzgesagt&sp=EgIQAg%253D%253D',
  6644. 'info_dict': {
  6645. 'id': 'kurzgesagt',
  6646. 'title': 'kurzgesagt',
  6647. },
  6648. 'playlist': [{
  6649. 'info_dict': {
  6650. '_type': 'url',
  6651. 'id': 'UCsXVk37bltHxD1rDPwtNM8Q',
  6652. 'url': 'https://www.youtube.com/channel/UCsXVk37bltHxD1rDPwtNM8Q',
  6653. 'ie_key': 'YoutubeTab',
  6654. 'channel': 'Kurzgesagt – In a Nutshell',
  6655. 'description': 'md5:4ae48dfa9505ffc307dad26342d06bfc',
  6656. 'title': 'Kurzgesagt – In a Nutshell',
  6657. 'channel_id': 'UCsXVk37bltHxD1rDPwtNM8Q',
  6658. # No longer available for search as it is set to the handle.
  6659. # 'playlist_count': int,
  6660. 'channel_url': 'https://www.youtube.com/channel/UCsXVk37bltHxD1rDPwtNM8Q',
  6661. 'thumbnails': list,
  6662. 'uploader_id': '@kurzgesagt',
  6663. 'uploader_url': 'https://www.youtube.com/@kurzgesagt',
  6664. 'uploader': 'Kurzgesagt – In a Nutshell',
  6665. 'channel_is_verified': True,
  6666. 'channel_follower_count': int,
  6667. },
  6668. }],
  6669. 'params': {'extract_flat': True, 'playlist_items': '1'},
  6670. 'playlist_mincount': 1,
  6671. }, {
  6672. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  6673. 'only_matching': True,
  6674. }]
  6675. def _real_extract(self, url):
  6676. qs = parse_qs(url)
  6677. query = (qs.get('search_query') or qs.get('q'))[0]
  6678. return self.playlist_result(self._search_results(query, qs.get('sp', (None,))[0]), query, query)
  6679. class YoutubeMusicSearchURLIE(YoutubeTabBaseInfoExtractor):
  6680. IE_DESC = 'YouTube music search URLs with selectable sections, e.g. #songs'
  6681. IE_NAME = 'youtube:music:search_url'
  6682. _VALID_URL = r'https?://music\.youtube\.com/search\?([^#]+&)?(?:search_query|q)=(?:[^&]+)(?:[&#]|$)'
  6683. _TESTS = [{
  6684. 'url': 'https://music.youtube.com/search?q=royalty+free+music',
  6685. 'playlist_count': 16,
  6686. 'info_dict': {
  6687. 'id': 'royalty free music',
  6688. 'title': 'royalty free music',
  6689. },
  6690. }, {
  6691. 'url': 'https://music.youtube.com/search?q=royalty+free+music&sp=EgWKAQIIAWoKEAoQAxAEEAkQBQ%3D%3D',
  6692. 'playlist_mincount': 30,
  6693. 'info_dict': {
  6694. 'id': 'royalty free music - songs',
  6695. 'title': 'royalty free music - songs',
  6696. },
  6697. 'params': {'extract_flat': 'in_playlist'},
  6698. }, {
  6699. 'url': 'https://music.youtube.com/search?q=royalty+free+music#community+playlists',
  6700. 'playlist_mincount': 30,
  6701. 'info_dict': {
  6702. 'id': 'royalty free music - community playlists',
  6703. 'title': 'royalty free music - community playlists',
  6704. },
  6705. 'params': {'extract_flat': 'in_playlist'},
  6706. }]
  6707. _SECTIONS = {
  6708. 'albums': 'EgWKAQIYAWoKEAoQAxAEEAkQBQ==',
  6709. 'artists': 'EgWKAQIgAWoKEAoQAxAEEAkQBQ==',
  6710. 'community playlists': 'EgeKAQQoAEABagoQChADEAQQCRAF',
  6711. 'featured playlists': 'EgeKAQQoADgBagwQAxAJEAQQDhAKEAU==',
  6712. 'songs': 'EgWKAQIIAWoKEAoQAxAEEAkQBQ==',
  6713. 'videos': 'EgWKAQIQAWoKEAoQAxAEEAkQBQ==',
  6714. }
  6715. def _real_extract(self, url):
  6716. qs = parse_qs(url)
  6717. query = (qs.get('search_query') or qs.get('q'))[0]
  6718. params = qs.get('sp', (None,))[0]
  6719. if params:
  6720. section = next((k for k, v in self._SECTIONS.items() if v == params), params)
  6721. else:
  6722. section = urllib.parse.unquote_plus(([*url.split('#'), ''])[1]).lower()
  6723. params = self._SECTIONS.get(section)
  6724. if not params:
  6725. section = None
  6726. title = join_nonempty(query, section, delim=' - ')
  6727. return self.playlist_result(self._search_results(query, params, default_client='web_music'), title, title)
  6728. class YoutubeFeedsInfoExtractor(InfoExtractor):
  6729. """
  6730. Base class for feed extractors
  6731. Subclasses must re-define the _FEED_NAME property.
  6732. """
  6733. _LOGIN_REQUIRED = True
  6734. _FEED_NAME = 'feeds'
  6735. def _real_initialize(self):
  6736. YoutubeBaseInfoExtractor._check_login_required(self)
  6737. @classproperty
  6738. def IE_NAME(cls):
  6739. return f'youtube:{cls._FEED_NAME}'
  6740. def _real_extract(self, url):
  6741. return self.url_result(
  6742. f'https://www.youtube.com/feed/{self._FEED_NAME}', ie=YoutubeTabIE.ie_key())
  6743. class YoutubeWatchLaterIE(InfoExtractor):
  6744. IE_NAME = 'youtube:watchlater'
  6745. IE_DESC = 'Youtube watch later list; ":ytwatchlater" keyword (requires cookies)'
  6746. _VALID_URL = r':ytwatchlater'
  6747. _TESTS = [{
  6748. 'url': ':ytwatchlater',
  6749. 'only_matching': True,
  6750. }]
  6751. def _real_extract(self, url):
  6752. return self.url_result(
  6753. 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
  6754. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  6755. IE_DESC = 'YouTube recommended videos; ":ytrec" keyword'
  6756. _VALID_URL = r'https?://(?:www\.)?youtube\.com/?(?:[?#]|$)|:ytrec(?:ommended)?'
  6757. _FEED_NAME = 'recommended'
  6758. _LOGIN_REQUIRED = False
  6759. _TESTS = [{
  6760. 'url': ':ytrec',
  6761. 'only_matching': True,
  6762. }, {
  6763. 'url': ':ytrecommended',
  6764. 'only_matching': True,
  6765. }, {
  6766. 'url': 'https://youtube.com',
  6767. 'only_matching': True,
  6768. }]
  6769. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  6770. IE_DESC = 'YouTube subscriptions feed; ":ytsubs" keyword (requires cookies)'
  6771. _VALID_URL = r':ytsub(?:scription)?s?'
  6772. _FEED_NAME = 'subscriptions'
  6773. _TESTS = [{
  6774. 'url': ':ytsubs',
  6775. 'only_matching': True,
  6776. }, {
  6777. 'url': ':ytsubscriptions',
  6778. 'only_matching': True,
  6779. }]
  6780. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  6781. IE_DESC = 'Youtube watch history; ":ythis" keyword (requires cookies)'
  6782. _VALID_URL = r':ythis(?:tory)?'
  6783. _FEED_NAME = 'history'
  6784. _TESTS = [{
  6785. 'url': ':ythistory',
  6786. 'only_matching': True,
  6787. }]
  6788. class YoutubeShortsAudioPivotIE(InfoExtractor):
  6789. IE_DESC = 'YouTube Shorts audio pivot (Shorts using audio of a given video)'
  6790. IE_NAME = 'youtube:shorts:pivot:audio'
  6791. _VALID_URL = r'https?://(?:www\.)?youtube\.com/source/(?P<id>[\w-]{11})/shorts'
  6792. _TESTS = [{
  6793. 'url': 'https://www.youtube.com/source/Lyj-MZSAA9o/shorts',
  6794. 'only_matching': True,
  6795. }]
  6796. @staticmethod
  6797. def _generate_audio_pivot_params(video_id):
  6798. """
  6799. Generates sfv_audio_pivot browse params for this video id
  6800. """
  6801. pb_params = b'\xf2\x05+\n)\x12\'\n\x0b%b\x12\x0b%b\x1a\x0b%b' % ((video_id.encode(),) * 3)
  6802. return urllib.parse.quote(base64.b64encode(pb_params).decode())
  6803. def _real_extract(self, url):
  6804. video_id = self._match_id(url)
  6805. return self.url_result(
  6806. f'https://www.youtube.com/feed/sfv_audio_pivot?bp={self._generate_audio_pivot_params(video_id)}',
  6807. ie=YoutubeTabIE)
  6808. class YoutubeTruncatedURLIE(InfoExtractor):
  6809. IE_NAME = 'youtube:truncated_url'
  6810. IE_DESC = False # Do not list
  6811. _VALID_URL = r'''(?x)
  6812. (?:https?://)?
  6813. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  6814. (?:watch\?(?:
  6815. feature=[a-z_]+|
  6816. annotation_id=annotation_[^&]+|
  6817. x-yt-cl=[0-9]+|
  6818. hl=[^&]*|
  6819. t=[0-9]+
  6820. )?
  6821. |
  6822. attribution_link\?a=[^&]+
  6823. )
  6824. $
  6825. '''
  6826. _TESTS = [{
  6827. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  6828. 'only_matching': True,
  6829. }, {
  6830. 'url': 'https://www.youtube.com/watch?',
  6831. 'only_matching': True,
  6832. }, {
  6833. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  6834. 'only_matching': True,
  6835. }, {
  6836. 'url': 'https://www.youtube.com/watch?feature=foo',
  6837. 'only_matching': True,
  6838. }, {
  6839. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  6840. 'only_matching': True,
  6841. }, {
  6842. 'url': 'https://www.youtube.com/watch?t=2372',
  6843. 'only_matching': True,
  6844. }]
  6845. def _real_extract(self, url):
  6846. raise ExtractorError(
  6847. 'Did you forget to quote the URL? Remember that & is a meta '
  6848. 'character in most shells, so you want to put the URL in quotes, '
  6849. 'like youtube-dl '
  6850. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  6851. ' or simply youtube-dl BaW_jenozKc .',
  6852. expected=True)
  6853. class YoutubeClipIE(YoutubeTabBaseInfoExtractor):
  6854. IE_NAME = 'youtube:clip'
  6855. _VALID_URL = r'https?://(?:www\.)?youtube\.com/clip/(?P<id>[^/?#]+)'
  6856. _TESTS = [{
  6857. # FIXME: Other metadata should be extracted from the clip, not from the base video
  6858. 'url': 'https://www.youtube.com/clip/UgytZKpehg-hEMBSn3F4AaABCQ',
  6859. 'info_dict': {
  6860. 'id': 'UgytZKpehg-hEMBSn3F4AaABCQ',
  6861. 'ext': 'mp4',
  6862. 'section_start': 29.0,
  6863. 'section_end': 39.7,
  6864. 'duration': 10.7,
  6865. 'age_limit': 0,
  6866. 'availability': 'public',
  6867. 'categories': ['Gaming'],
  6868. 'channel': 'Scott The Woz',
  6869. 'channel_id': 'UC4rqhyiTs7XyuODcECvuiiQ',
  6870. 'channel_url': 'https://www.youtube.com/channel/UC4rqhyiTs7XyuODcECvuiiQ',
  6871. 'description': 'md5:7a4517a17ea9b4bd98996399d8bb36e7',
  6872. 'like_count': int,
  6873. 'playable_in_embed': True,
  6874. 'tags': 'count:17',
  6875. 'thumbnail': 'https://i.ytimg.com/vi_webp/ScPX26pdQik/maxresdefault.webp',
  6876. 'title': 'Mobile Games on Console - Scott The Woz',
  6877. 'upload_date': '20210920',
  6878. 'uploader': 'Scott The Woz',
  6879. 'uploader_id': '@ScottTheWoz',
  6880. 'uploader_url': 'https://www.youtube.com/@ScottTheWoz',
  6881. 'view_count': int,
  6882. 'live_status': 'not_live',
  6883. 'channel_follower_count': int,
  6884. 'chapters': 'count:20',
  6885. 'comment_count': int,
  6886. 'heatmap': 'count:100',
  6887. },
  6888. }]
  6889. def _real_extract(self, url):
  6890. clip_id = self._match_id(url)
  6891. _, data = self._extract_webpage(url, clip_id)
  6892. video_id = traverse_obj(data, ('currentVideoEndpoint', 'watchEndpoint', 'videoId'))
  6893. if not video_id:
  6894. raise ExtractorError('Unable to find video ID')
  6895. clip_data = traverse_obj(data, (
  6896. 'engagementPanels', ..., 'engagementPanelSectionListRenderer', 'content', 'clipSectionRenderer',
  6897. 'contents', ..., 'clipAttributionRenderer', 'onScrubExit', 'commandExecutorCommand', 'commands', ...,
  6898. 'openPopupAction', 'popup', 'notificationActionRenderer', 'actionButton', 'buttonRenderer', 'command',
  6899. 'commandExecutorCommand', 'commands', ..., 'loopCommand'), get_all=False)
  6900. return {
  6901. '_type': 'url_transparent',
  6902. 'url': f'https://www.youtube.com/watch?v={video_id}',
  6903. 'ie_key': YoutubeIE.ie_key(),
  6904. 'id': clip_id,
  6905. 'section_start': int(clip_data['startTimeMs']) / 1000,
  6906. 'section_end': int(clip_data['endTimeMs']) / 1000,
  6907. }
  6908. class YoutubeConsentRedirectIE(YoutubeBaseInfoExtractor):
  6909. IE_NAME = 'youtube:consent'
  6910. IE_DESC = False # Do not list
  6911. _VALID_URL = r'https?://consent\.youtube\.com/m\?'
  6912. _TESTS = [{
  6913. 'url': 'https://consent.youtube.com/m?continue=https%3A%2F%2Fwww.youtube.com%2Flive%2FqVv6vCqciTM%3Fcbrd%3D1&gl=NL&m=0&pc=yt&hl=en&src=1',
  6914. 'info_dict': {
  6915. 'id': 'qVv6vCqciTM',
  6916. 'ext': 'mp4',
  6917. 'age_limit': 0,
  6918. 'uploader_id': '@sana_natori',
  6919. 'comment_count': int,
  6920. 'chapters': 'count:13',
  6921. 'upload_date': '20221223',
  6922. 'thumbnail': 'https://i.ytimg.com/vi/qVv6vCqciTM/maxresdefault.jpg',
  6923. 'channel_url': 'https://www.youtube.com/channel/UCIdEIHpS0TdkqRkHL5OkLtA',
  6924. 'uploader_url': 'https://www.youtube.com/@sana_natori',
  6925. 'like_count': int,
  6926. 'release_date': '20221223',
  6927. 'tags': ['Vtuber', '月ノ美兎', '名取さな', 'にじさんじ', 'クリスマス', '3D配信'],
  6928. 'title': '【 #インターネット女クリスマス 】3Dで歌ってはしゃぐインターネットの女たち【月ノ美兎/名取さな】',
  6929. 'view_count': int,
  6930. 'playable_in_embed': True,
  6931. 'duration': 4438,
  6932. 'availability': 'public',
  6933. 'channel_follower_count': int,
  6934. 'channel_id': 'UCIdEIHpS0TdkqRkHL5OkLtA',
  6935. 'categories': ['Entertainment'],
  6936. 'live_status': 'was_live',
  6937. 'release_timestamp': 1671793345,
  6938. 'channel': 'さなちゃんねる',
  6939. 'description': 'md5:6aebf95cc4a1d731aebc01ad6cc9806d',
  6940. 'uploader': 'さなちゃんねる',
  6941. 'channel_is_verified': True,
  6942. 'heatmap': 'count:100',
  6943. },
  6944. 'add_ie': ['Youtube'],
  6945. 'params': {'skip_download': 'Youtube'},
  6946. }]
  6947. def _real_extract(self, url):
  6948. redirect_url = url_or_none(parse_qs(url).get('continue', [None])[-1])
  6949. if not redirect_url:
  6950. raise ExtractorError('Invalid cookie consent redirect URL', expected=True)
  6951. return self.url_result(redirect_url)
  6952. class YoutubeTruncatedIDIE(InfoExtractor):
  6953. IE_NAME = 'youtube:truncated_id'
  6954. IE_DESC = False # Do not list
  6955. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  6956. _TESTS = [{
  6957. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  6958. 'only_matching': True,
  6959. }]
  6960. def _real_extract(self, url):
  6961. video_id = self._match_id(url)
  6962. raise ExtractorError(
  6963. f'Incomplete YouTube ID {video_id}. URL {url} looks truncated.',
  6964. expected=True)