youtube.py 294 KB

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