youtube.py 323 KB

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