youtube.py 348 KB

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