youtube.py 275 KB

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