utils.py 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. import base64
  5. import binascii
  6. import calendar
  7. import codecs
  8. import collections
  9. import contextlib
  10. import ctypes
  11. import datetime
  12. import email.utils
  13. import email.header
  14. import errno
  15. import functools
  16. import inspect
  17. import io
  18. import itertools
  19. import json
  20. import locale
  21. import math
  22. import operator
  23. import os
  24. import platform
  25. import random
  26. import re
  27. import socket
  28. import ssl
  29. import subprocess
  30. import sys
  31. import tempfile
  32. import time
  33. import traceback
  34. import unicodedata
  35. import xml.etree.ElementTree
  36. import zlib
  37. from .compat import (
  38. compat_HTMLParseError,
  39. compat_HTMLParser,
  40. compat_basestring,
  41. compat_brotli as brotli,
  42. compat_casefold,
  43. compat_chr,
  44. compat_collections_abc,
  45. compat_contextlib_suppress,
  46. compat_cookiejar,
  47. compat_ctypes_WINFUNCTYPE,
  48. compat_datetime_timedelta_total_seconds,
  49. compat_etree_Element,
  50. compat_etree_fromstring,
  51. compat_etree_iterfind,
  52. compat_expanduser,
  53. compat_filter as filter,
  54. compat_filter_fns,
  55. compat_html_entities,
  56. compat_html_entities_html5,
  57. compat_http_client,
  58. compat_http_cookies,
  59. compat_integer_types,
  60. compat_kwargs,
  61. compat_ncompress as ncompress,
  62. compat_os_name,
  63. compat_re_Match,
  64. compat_re_Pattern,
  65. compat_shlex_quote,
  66. compat_str,
  67. compat_struct_pack,
  68. compat_struct_unpack,
  69. compat_urllib_error,
  70. compat_urllib_HTTPError,
  71. compat_urllib_parse,
  72. compat_urllib_parse_parse_qs as compat_parse_qs,
  73. compat_urllib_parse_urlencode,
  74. compat_urllib_parse_urlparse,
  75. compat_urllib_parse_unquote_plus,
  76. compat_urllib_request,
  77. compat_xpath,
  78. )
  79. from .socks import (
  80. ProxyType,
  81. sockssocket,
  82. )
  83. def register_socks_protocols():
  84. # "Register" SOCKS protocols
  85. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  86. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  87. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  88. if scheme not in compat_urllib_parse.uses_netloc:
  89. compat_urllib_parse.uses_netloc.append(scheme)
  90. # Unfavoured alias
  91. compiled_regex_type = compat_re_Pattern
  92. def random_user_agent():
  93. _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
  94. _CHROME_VERSIONS = (
  95. '74.0.3729.129',
  96. '76.0.3780.3',
  97. '76.0.3780.2',
  98. '74.0.3729.128',
  99. '76.0.3780.1',
  100. '76.0.3780.0',
  101. '75.0.3770.15',
  102. '74.0.3729.127',
  103. '74.0.3729.126',
  104. '76.0.3779.1',
  105. '76.0.3779.0',
  106. '75.0.3770.14',
  107. '74.0.3729.125',
  108. '76.0.3778.1',
  109. '76.0.3778.0',
  110. '75.0.3770.13',
  111. '74.0.3729.124',
  112. '74.0.3729.123',
  113. '73.0.3683.121',
  114. '76.0.3777.1',
  115. '76.0.3777.0',
  116. '75.0.3770.12',
  117. '74.0.3729.122',
  118. '76.0.3776.4',
  119. '75.0.3770.11',
  120. '74.0.3729.121',
  121. '76.0.3776.3',
  122. '76.0.3776.2',
  123. '73.0.3683.120',
  124. '74.0.3729.120',
  125. '74.0.3729.119',
  126. '74.0.3729.118',
  127. '76.0.3776.1',
  128. '76.0.3776.0',
  129. '76.0.3775.5',
  130. '75.0.3770.10',
  131. '74.0.3729.117',
  132. '76.0.3775.4',
  133. '76.0.3775.3',
  134. '74.0.3729.116',
  135. '75.0.3770.9',
  136. '76.0.3775.2',
  137. '76.0.3775.1',
  138. '76.0.3775.0',
  139. '75.0.3770.8',
  140. '74.0.3729.115',
  141. '74.0.3729.114',
  142. '76.0.3774.1',
  143. '76.0.3774.0',
  144. '75.0.3770.7',
  145. '74.0.3729.113',
  146. '74.0.3729.112',
  147. '74.0.3729.111',
  148. '76.0.3773.1',
  149. '76.0.3773.0',
  150. '75.0.3770.6',
  151. '74.0.3729.110',
  152. '74.0.3729.109',
  153. '76.0.3772.1',
  154. '76.0.3772.0',
  155. '75.0.3770.5',
  156. '74.0.3729.108',
  157. '74.0.3729.107',
  158. '76.0.3771.1',
  159. '76.0.3771.0',
  160. '75.0.3770.4',
  161. '74.0.3729.106',
  162. '74.0.3729.105',
  163. '75.0.3770.3',
  164. '74.0.3729.104',
  165. '74.0.3729.103',
  166. '74.0.3729.102',
  167. '75.0.3770.2',
  168. '74.0.3729.101',
  169. '75.0.3770.1',
  170. '75.0.3770.0',
  171. '74.0.3729.100',
  172. '75.0.3769.5',
  173. '75.0.3769.4',
  174. '74.0.3729.99',
  175. '75.0.3769.3',
  176. '75.0.3769.2',
  177. '75.0.3768.6',
  178. '74.0.3729.98',
  179. '75.0.3769.1',
  180. '75.0.3769.0',
  181. '74.0.3729.97',
  182. '73.0.3683.119',
  183. '73.0.3683.118',
  184. '74.0.3729.96',
  185. '75.0.3768.5',
  186. '75.0.3768.4',
  187. '75.0.3768.3',
  188. '75.0.3768.2',
  189. '74.0.3729.95',
  190. '74.0.3729.94',
  191. '75.0.3768.1',
  192. '75.0.3768.0',
  193. '74.0.3729.93',
  194. '74.0.3729.92',
  195. '73.0.3683.117',
  196. '74.0.3729.91',
  197. '75.0.3766.3',
  198. '74.0.3729.90',
  199. '75.0.3767.2',
  200. '75.0.3767.1',
  201. '75.0.3767.0',
  202. '74.0.3729.89',
  203. '73.0.3683.116',
  204. '75.0.3766.2',
  205. '74.0.3729.88',
  206. '75.0.3766.1',
  207. '75.0.3766.0',
  208. '74.0.3729.87',
  209. '73.0.3683.115',
  210. '74.0.3729.86',
  211. '75.0.3765.1',
  212. '75.0.3765.0',
  213. '74.0.3729.85',
  214. '73.0.3683.114',
  215. '74.0.3729.84',
  216. '75.0.3764.1',
  217. '75.0.3764.0',
  218. '74.0.3729.83',
  219. '73.0.3683.113',
  220. '75.0.3763.2',
  221. '75.0.3761.4',
  222. '74.0.3729.82',
  223. '75.0.3763.1',
  224. '75.0.3763.0',
  225. '74.0.3729.81',
  226. '73.0.3683.112',
  227. '75.0.3762.1',
  228. '75.0.3762.0',
  229. '74.0.3729.80',
  230. '75.0.3761.3',
  231. '74.0.3729.79',
  232. '73.0.3683.111',
  233. '75.0.3761.2',
  234. '74.0.3729.78',
  235. '74.0.3729.77',
  236. '75.0.3761.1',
  237. '75.0.3761.0',
  238. '73.0.3683.110',
  239. '74.0.3729.76',
  240. '74.0.3729.75',
  241. '75.0.3760.0',
  242. '74.0.3729.74',
  243. '75.0.3759.8',
  244. '75.0.3759.7',
  245. '75.0.3759.6',
  246. '74.0.3729.73',
  247. '75.0.3759.5',
  248. '74.0.3729.72',
  249. '73.0.3683.109',
  250. '75.0.3759.4',
  251. '75.0.3759.3',
  252. '74.0.3729.71',
  253. '75.0.3759.2',
  254. '74.0.3729.70',
  255. '73.0.3683.108',
  256. '74.0.3729.69',
  257. '75.0.3759.1',
  258. '75.0.3759.0',
  259. '74.0.3729.68',
  260. '73.0.3683.107',
  261. '74.0.3729.67',
  262. '75.0.3758.1',
  263. '75.0.3758.0',
  264. '74.0.3729.66',
  265. '73.0.3683.106',
  266. '74.0.3729.65',
  267. '75.0.3757.1',
  268. '75.0.3757.0',
  269. '74.0.3729.64',
  270. '73.0.3683.105',
  271. '74.0.3729.63',
  272. '75.0.3756.1',
  273. '75.0.3756.0',
  274. '74.0.3729.62',
  275. '73.0.3683.104',
  276. '75.0.3755.3',
  277. '75.0.3755.2',
  278. '73.0.3683.103',
  279. '75.0.3755.1',
  280. '75.0.3755.0',
  281. '74.0.3729.61',
  282. '73.0.3683.102',
  283. '74.0.3729.60',
  284. '75.0.3754.2',
  285. '74.0.3729.59',
  286. '75.0.3753.4',
  287. '74.0.3729.58',
  288. '75.0.3754.1',
  289. '75.0.3754.0',
  290. '74.0.3729.57',
  291. '73.0.3683.101',
  292. '75.0.3753.3',
  293. '75.0.3752.2',
  294. '75.0.3753.2',
  295. '74.0.3729.56',
  296. '75.0.3753.1',
  297. '75.0.3753.0',
  298. '74.0.3729.55',
  299. '73.0.3683.100',
  300. '74.0.3729.54',
  301. '75.0.3752.1',
  302. '75.0.3752.0',
  303. '74.0.3729.53',
  304. '73.0.3683.99',
  305. '74.0.3729.52',
  306. '75.0.3751.1',
  307. '75.0.3751.0',
  308. '74.0.3729.51',
  309. '73.0.3683.98',
  310. '74.0.3729.50',
  311. '75.0.3750.0',
  312. '74.0.3729.49',
  313. '74.0.3729.48',
  314. '74.0.3729.47',
  315. '75.0.3749.3',
  316. '74.0.3729.46',
  317. '73.0.3683.97',
  318. '75.0.3749.2',
  319. '74.0.3729.45',
  320. '75.0.3749.1',
  321. '75.0.3749.0',
  322. '74.0.3729.44',
  323. '73.0.3683.96',
  324. '74.0.3729.43',
  325. '74.0.3729.42',
  326. '75.0.3748.1',
  327. '75.0.3748.0',
  328. '74.0.3729.41',
  329. '75.0.3747.1',
  330. '73.0.3683.95',
  331. '75.0.3746.4',
  332. '74.0.3729.40',
  333. '74.0.3729.39',
  334. '75.0.3747.0',
  335. '75.0.3746.3',
  336. '75.0.3746.2',
  337. '74.0.3729.38',
  338. '75.0.3746.1',
  339. '75.0.3746.0',
  340. '74.0.3729.37',
  341. '73.0.3683.94',
  342. '75.0.3745.5',
  343. '75.0.3745.4',
  344. '75.0.3745.3',
  345. '75.0.3745.2',
  346. '74.0.3729.36',
  347. '75.0.3745.1',
  348. '75.0.3745.0',
  349. '75.0.3744.2',
  350. '74.0.3729.35',
  351. '73.0.3683.93',
  352. '74.0.3729.34',
  353. '75.0.3744.1',
  354. '75.0.3744.0',
  355. '74.0.3729.33',
  356. '73.0.3683.92',
  357. '74.0.3729.32',
  358. '74.0.3729.31',
  359. '73.0.3683.91',
  360. '75.0.3741.2',
  361. '75.0.3740.5',
  362. '74.0.3729.30',
  363. '75.0.3741.1',
  364. '75.0.3741.0',
  365. '74.0.3729.29',
  366. '75.0.3740.4',
  367. '73.0.3683.90',
  368. '74.0.3729.28',
  369. '75.0.3740.3',
  370. '73.0.3683.89',
  371. '75.0.3740.2',
  372. '74.0.3729.27',
  373. '75.0.3740.1',
  374. '75.0.3740.0',
  375. '74.0.3729.26',
  376. '73.0.3683.88',
  377. '73.0.3683.87',
  378. '74.0.3729.25',
  379. '75.0.3739.1',
  380. '75.0.3739.0',
  381. '73.0.3683.86',
  382. '74.0.3729.24',
  383. '73.0.3683.85',
  384. '75.0.3738.4',
  385. '75.0.3738.3',
  386. '75.0.3738.2',
  387. '75.0.3738.1',
  388. '75.0.3738.0',
  389. '74.0.3729.23',
  390. '73.0.3683.84',
  391. '74.0.3729.22',
  392. '74.0.3729.21',
  393. '75.0.3737.1',
  394. '75.0.3737.0',
  395. '74.0.3729.20',
  396. '73.0.3683.83',
  397. '74.0.3729.19',
  398. '75.0.3736.1',
  399. '75.0.3736.0',
  400. '74.0.3729.18',
  401. '73.0.3683.82',
  402. '74.0.3729.17',
  403. '75.0.3735.1',
  404. '75.0.3735.0',
  405. '74.0.3729.16',
  406. '73.0.3683.81',
  407. '75.0.3734.1',
  408. '75.0.3734.0',
  409. '74.0.3729.15',
  410. '73.0.3683.80',
  411. '74.0.3729.14',
  412. '75.0.3733.1',
  413. '75.0.3733.0',
  414. '75.0.3732.1',
  415. '74.0.3729.13',
  416. '74.0.3729.12',
  417. '73.0.3683.79',
  418. '74.0.3729.11',
  419. '75.0.3732.0',
  420. '74.0.3729.10',
  421. '73.0.3683.78',
  422. '74.0.3729.9',
  423. '74.0.3729.8',
  424. '74.0.3729.7',
  425. '75.0.3731.3',
  426. '75.0.3731.2',
  427. '75.0.3731.0',
  428. '74.0.3729.6',
  429. '73.0.3683.77',
  430. '73.0.3683.76',
  431. '75.0.3730.5',
  432. '75.0.3730.4',
  433. '73.0.3683.75',
  434. '74.0.3729.5',
  435. '73.0.3683.74',
  436. '75.0.3730.3',
  437. '75.0.3730.2',
  438. '74.0.3729.4',
  439. '73.0.3683.73',
  440. '73.0.3683.72',
  441. '75.0.3730.1',
  442. '75.0.3730.0',
  443. '74.0.3729.3',
  444. '73.0.3683.71',
  445. '74.0.3729.2',
  446. '73.0.3683.70',
  447. '74.0.3729.1',
  448. '74.0.3729.0',
  449. '74.0.3726.4',
  450. '73.0.3683.69',
  451. '74.0.3726.3',
  452. '74.0.3728.0',
  453. '74.0.3726.2',
  454. '73.0.3683.68',
  455. '74.0.3726.1',
  456. '74.0.3726.0',
  457. '74.0.3725.4',
  458. '73.0.3683.67',
  459. '73.0.3683.66',
  460. '74.0.3725.3',
  461. '74.0.3725.2',
  462. '74.0.3725.1',
  463. '74.0.3724.8',
  464. '74.0.3725.0',
  465. '73.0.3683.65',
  466. '74.0.3724.7',
  467. '74.0.3724.6',
  468. '74.0.3724.5',
  469. '74.0.3724.4',
  470. '74.0.3724.3',
  471. '74.0.3724.2',
  472. '74.0.3724.1',
  473. '74.0.3724.0',
  474. '73.0.3683.64',
  475. '74.0.3723.1',
  476. '74.0.3723.0',
  477. '73.0.3683.63',
  478. '74.0.3722.1',
  479. '74.0.3722.0',
  480. '73.0.3683.62',
  481. '74.0.3718.9',
  482. '74.0.3702.3',
  483. '74.0.3721.3',
  484. '74.0.3721.2',
  485. '74.0.3721.1',
  486. '74.0.3721.0',
  487. '74.0.3720.6',
  488. '73.0.3683.61',
  489. '72.0.3626.122',
  490. '73.0.3683.60',
  491. '74.0.3720.5',
  492. '72.0.3626.121',
  493. '74.0.3718.8',
  494. '74.0.3720.4',
  495. '74.0.3720.3',
  496. '74.0.3718.7',
  497. '74.0.3720.2',
  498. '74.0.3720.1',
  499. '74.0.3720.0',
  500. '74.0.3718.6',
  501. '74.0.3719.5',
  502. '73.0.3683.59',
  503. '74.0.3718.5',
  504. '74.0.3718.4',
  505. '74.0.3719.4',
  506. '74.0.3719.3',
  507. '74.0.3719.2',
  508. '74.0.3719.1',
  509. '73.0.3683.58',
  510. '74.0.3719.0',
  511. '73.0.3683.57',
  512. '73.0.3683.56',
  513. '74.0.3718.3',
  514. '73.0.3683.55',
  515. '74.0.3718.2',
  516. '74.0.3718.1',
  517. '74.0.3718.0',
  518. '73.0.3683.54',
  519. '74.0.3717.2',
  520. '73.0.3683.53',
  521. '74.0.3717.1',
  522. '74.0.3717.0',
  523. '73.0.3683.52',
  524. '74.0.3716.1',
  525. '74.0.3716.0',
  526. '73.0.3683.51',
  527. '74.0.3715.1',
  528. '74.0.3715.0',
  529. '73.0.3683.50',
  530. '74.0.3711.2',
  531. '74.0.3714.2',
  532. '74.0.3713.3',
  533. '74.0.3714.1',
  534. '74.0.3714.0',
  535. '73.0.3683.49',
  536. '74.0.3713.1',
  537. '74.0.3713.0',
  538. '72.0.3626.120',
  539. '73.0.3683.48',
  540. '74.0.3712.2',
  541. '74.0.3712.1',
  542. '74.0.3712.0',
  543. '73.0.3683.47',
  544. '72.0.3626.119',
  545. '73.0.3683.46',
  546. '74.0.3710.2',
  547. '72.0.3626.118',
  548. '74.0.3711.1',
  549. '74.0.3711.0',
  550. '73.0.3683.45',
  551. '72.0.3626.117',
  552. '74.0.3710.1',
  553. '74.0.3710.0',
  554. '73.0.3683.44',
  555. '72.0.3626.116',
  556. '74.0.3709.1',
  557. '74.0.3709.0',
  558. '74.0.3704.9',
  559. '73.0.3683.43',
  560. '72.0.3626.115',
  561. '74.0.3704.8',
  562. '74.0.3704.7',
  563. '74.0.3708.0',
  564. '74.0.3706.7',
  565. '74.0.3704.6',
  566. '73.0.3683.42',
  567. '72.0.3626.114',
  568. '74.0.3706.6',
  569. '72.0.3626.113',
  570. '74.0.3704.5',
  571. '74.0.3706.5',
  572. '74.0.3706.4',
  573. '74.0.3706.3',
  574. '74.0.3706.2',
  575. '74.0.3706.1',
  576. '74.0.3706.0',
  577. '73.0.3683.41',
  578. '72.0.3626.112',
  579. '74.0.3705.1',
  580. '74.0.3705.0',
  581. '73.0.3683.40',
  582. '72.0.3626.111',
  583. '73.0.3683.39',
  584. '74.0.3704.4',
  585. '73.0.3683.38',
  586. '74.0.3704.3',
  587. '74.0.3704.2',
  588. '74.0.3704.1',
  589. '74.0.3704.0',
  590. '73.0.3683.37',
  591. '72.0.3626.110',
  592. '72.0.3626.109',
  593. '74.0.3703.3',
  594. '74.0.3703.2',
  595. '73.0.3683.36',
  596. '74.0.3703.1',
  597. '74.0.3703.0',
  598. '73.0.3683.35',
  599. '72.0.3626.108',
  600. '74.0.3702.2',
  601. '74.0.3699.3',
  602. '74.0.3702.1',
  603. '74.0.3702.0',
  604. '73.0.3683.34',
  605. '72.0.3626.107',
  606. '73.0.3683.33',
  607. '74.0.3701.1',
  608. '74.0.3701.0',
  609. '73.0.3683.32',
  610. '73.0.3683.31',
  611. '72.0.3626.105',
  612. '74.0.3700.1',
  613. '74.0.3700.0',
  614. '73.0.3683.29',
  615. '72.0.3626.103',
  616. '74.0.3699.2',
  617. '74.0.3699.1',
  618. '74.0.3699.0',
  619. '73.0.3683.28',
  620. '72.0.3626.102',
  621. '73.0.3683.27',
  622. '73.0.3683.26',
  623. '74.0.3698.0',
  624. '74.0.3696.2',
  625. '72.0.3626.101',
  626. '73.0.3683.25',
  627. '74.0.3696.1',
  628. '74.0.3696.0',
  629. '74.0.3694.8',
  630. '72.0.3626.100',
  631. '74.0.3694.7',
  632. '74.0.3694.6',
  633. '74.0.3694.5',
  634. '74.0.3694.4',
  635. '72.0.3626.99',
  636. '72.0.3626.98',
  637. '74.0.3694.3',
  638. '73.0.3683.24',
  639. '72.0.3626.97',
  640. '72.0.3626.96',
  641. '72.0.3626.95',
  642. '73.0.3683.23',
  643. '72.0.3626.94',
  644. '73.0.3683.22',
  645. '73.0.3683.21',
  646. '72.0.3626.93',
  647. '74.0.3694.2',
  648. '72.0.3626.92',
  649. '74.0.3694.1',
  650. '74.0.3694.0',
  651. '74.0.3693.6',
  652. '73.0.3683.20',
  653. '72.0.3626.91',
  654. '74.0.3693.5',
  655. '74.0.3693.4',
  656. '74.0.3693.3',
  657. '74.0.3693.2',
  658. '73.0.3683.19',
  659. '74.0.3693.1',
  660. '74.0.3693.0',
  661. '73.0.3683.18',
  662. '72.0.3626.90',
  663. '74.0.3692.1',
  664. '74.0.3692.0',
  665. '73.0.3683.17',
  666. '72.0.3626.89',
  667. '74.0.3687.3',
  668. '74.0.3691.1',
  669. '74.0.3691.0',
  670. '73.0.3683.16',
  671. '72.0.3626.88',
  672. '72.0.3626.87',
  673. '73.0.3683.15',
  674. '74.0.3690.1',
  675. '74.0.3690.0',
  676. '73.0.3683.14',
  677. '72.0.3626.86',
  678. '73.0.3683.13',
  679. '73.0.3683.12',
  680. '74.0.3689.1',
  681. '74.0.3689.0',
  682. '73.0.3683.11',
  683. '72.0.3626.85',
  684. '73.0.3683.10',
  685. '72.0.3626.84',
  686. '73.0.3683.9',
  687. '74.0.3688.1',
  688. '74.0.3688.0',
  689. '73.0.3683.8',
  690. '72.0.3626.83',
  691. '74.0.3687.2',
  692. '74.0.3687.1',
  693. '74.0.3687.0',
  694. '73.0.3683.7',
  695. '72.0.3626.82',
  696. '74.0.3686.4',
  697. '72.0.3626.81',
  698. '74.0.3686.3',
  699. '74.0.3686.2',
  700. '74.0.3686.1',
  701. '74.0.3686.0',
  702. '73.0.3683.6',
  703. '72.0.3626.80',
  704. '74.0.3685.1',
  705. '74.0.3685.0',
  706. '73.0.3683.5',
  707. '72.0.3626.79',
  708. '74.0.3684.1',
  709. '74.0.3684.0',
  710. '73.0.3683.4',
  711. '72.0.3626.78',
  712. '72.0.3626.77',
  713. '73.0.3683.3',
  714. '73.0.3683.2',
  715. '72.0.3626.76',
  716. '73.0.3683.1',
  717. '73.0.3683.0',
  718. '72.0.3626.75',
  719. '71.0.3578.141',
  720. '73.0.3682.1',
  721. '73.0.3682.0',
  722. '72.0.3626.74',
  723. '71.0.3578.140',
  724. '73.0.3681.4',
  725. '73.0.3681.3',
  726. '73.0.3681.2',
  727. '73.0.3681.1',
  728. '73.0.3681.0',
  729. '72.0.3626.73',
  730. '71.0.3578.139',
  731. '72.0.3626.72',
  732. '72.0.3626.71',
  733. '73.0.3680.1',
  734. '73.0.3680.0',
  735. '72.0.3626.70',
  736. '71.0.3578.138',
  737. '73.0.3678.2',
  738. '73.0.3679.1',
  739. '73.0.3679.0',
  740. '72.0.3626.69',
  741. '71.0.3578.137',
  742. '73.0.3678.1',
  743. '73.0.3678.0',
  744. '71.0.3578.136',
  745. '73.0.3677.1',
  746. '73.0.3677.0',
  747. '72.0.3626.68',
  748. '72.0.3626.67',
  749. '71.0.3578.135',
  750. '73.0.3676.1',
  751. '73.0.3676.0',
  752. '73.0.3674.2',
  753. '72.0.3626.66',
  754. '71.0.3578.134',
  755. '73.0.3674.1',
  756. '73.0.3674.0',
  757. '72.0.3626.65',
  758. '71.0.3578.133',
  759. '73.0.3673.2',
  760. '73.0.3673.1',
  761. '73.0.3673.0',
  762. '72.0.3626.64',
  763. '71.0.3578.132',
  764. '72.0.3626.63',
  765. '72.0.3626.62',
  766. '72.0.3626.61',
  767. '72.0.3626.60',
  768. '73.0.3672.1',
  769. '73.0.3672.0',
  770. '72.0.3626.59',
  771. '71.0.3578.131',
  772. '73.0.3671.3',
  773. '73.0.3671.2',
  774. '73.0.3671.1',
  775. '73.0.3671.0',
  776. '72.0.3626.58',
  777. '71.0.3578.130',
  778. '73.0.3670.1',
  779. '73.0.3670.0',
  780. '72.0.3626.57',
  781. '71.0.3578.129',
  782. '73.0.3669.1',
  783. '73.0.3669.0',
  784. '72.0.3626.56',
  785. '71.0.3578.128',
  786. '73.0.3668.2',
  787. '73.0.3668.1',
  788. '73.0.3668.0',
  789. '72.0.3626.55',
  790. '71.0.3578.127',
  791. '73.0.3667.2',
  792. '73.0.3667.1',
  793. '73.0.3667.0',
  794. '72.0.3626.54',
  795. '71.0.3578.126',
  796. '73.0.3666.1',
  797. '73.0.3666.0',
  798. '72.0.3626.53',
  799. '71.0.3578.125',
  800. '73.0.3665.4',
  801. '73.0.3665.3',
  802. '72.0.3626.52',
  803. '73.0.3665.2',
  804. '73.0.3664.4',
  805. '73.0.3665.1',
  806. '73.0.3665.0',
  807. '72.0.3626.51',
  808. '71.0.3578.124',
  809. '72.0.3626.50',
  810. '73.0.3664.3',
  811. '73.0.3664.2',
  812. '73.0.3664.1',
  813. '73.0.3664.0',
  814. '73.0.3663.2',
  815. '72.0.3626.49',
  816. '71.0.3578.123',
  817. '73.0.3663.1',
  818. '73.0.3663.0',
  819. '72.0.3626.48',
  820. '71.0.3578.122',
  821. '73.0.3662.1',
  822. '73.0.3662.0',
  823. '72.0.3626.47',
  824. '71.0.3578.121',
  825. '73.0.3661.1',
  826. '72.0.3626.46',
  827. '73.0.3661.0',
  828. '72.0.3626.45',
  829. '71.0.3578.120',
  830. '73.0.3660.2',
  831. '73.0.3660.1',
  832. '73.0.3660.0',
  833. '72.0.3626.44',
  834. '71.0.3578.119',
  835. '73.0.3659.1',
  836. '73.0.3659.0',
  837. '72.0.3626.43',
  838. '71.0.3578.118',
  839. '73.0.3658.1',
  840. '73.0.3658.0',
  841. '72.0.3626.42',
  842. '71.0.3578.117',
  843. '73.0.3657.1',
  844. '73.0.3657.0',
  845. '72.0.3626.41',
  846. '71.0.3578.116',
  847. '73.0.3656.1',
  848. '73.0.3656.0',
  849. '72.0.3626.40',
  850. '71.0.3578.115',
  851. '73.0.3655.1',
  852. '73.0.3655.0',
  853. '72.0.3626.39',
  854. '71.0.3578.114',
  855. '73.0.3654.1',
  856. '73.0.3654.0',
  857. '72.0.3626.38',
  858. '71.0.3578.113',
  859. '73.0.3653.1',
  860. '73.0.3653.0',
  861. '72.0.3626.37',
  862. '71.0.3578.112',
  863. '73.0.3652.1',
  864. '73.0.3652.0',
  865. '72.0.3626.36',
  866. '71.0.3578.111',
  867. '73.0.3651.1',
  868. '73.0.3651.0',
  869. '72.0.3626.35',
  870. '71.0.3578.110',
  871. '73.0.3650.1',
  872. '73.0.3650.0',
  873. '72.0.3626.34',
  874. '71.0.3578.109',
  875. '73.0.3649.1',
  876. '73.0.3649.0',
  877. '72.0.3626.33',
  878. '71.0.3578.108',
  879. '73.0.3648.2',
  880. '73.0.3648.1',
  881. '73.0.3648.0',
  882. '72.0.3626.32',
  883. '71.0.3578.107',
  884. '73.0.3647.2',
  885. '73.0.3647.1',
  886. '73.0.3647.0',
  887. '72.0.3626.31',
  888. '71.0.3578.106',
  889. '73.0.3635.3',
  890. '73.0.3646.2',
  891. '73.0.3646.1',
  892. '73.0.3646.0',
  893. '72.0.3626.30',
  894. '71.0.3578.105',
  895. '72.0.3626.29',
  896. '73.0.3645.2',
  897. '73.0.3645.1',
  898. '73.0.3645.0',
  899. '72.0.3626.28',
  900. '71.0.3578.104',
  901. '72.0.3626.27',
  902. '72.0.3626.26',
  903. '72.0.3626.25',
  904. '72.0.3626.24',
  905. '73.0.3644.0',
  906. '73.0.3643.2',
  907. '72.0.3626.23',
  908. '71.0.3578.103',
  909. '73.0.3643.1',
  910. '73.0.3643.0',
  911. '72.0.3626.22',
  912. '71.0.3578.102',
  913. '73.0.3642.1',
  914. '73.0.3642.0',
  915. '72.0.3626.21',
  916. '71.0.3578.101',
  917. '73.0.3641.1',
  918. '73.0.3641.0',
  919. '72.0.3626.20',
  920. '71.0.3578.100',
  921. '72.0.3626.19',
  922. '73.0.3640.1',
  923. '73.0.3640.0',
  924. '72.0.3626.18',
  925. '73.0.3639.1',
  926. '71.0.3578.99',
  927. '73.0.3639.0',
  928. '72.0.3626.17',
  929. '73.0.3638.2',
  930. '72.0.3626.16',
  931. '73.0.3638.1',
  932. '73.0.3638.0',
  933. '72.0.3626.15',
  934. '71.0.3578.98',
  935. '73.0.3635.2',
  936. '71.0.3578.97',
  937. '73.0.3637.1',
  938. '73.0.3637.0',
  939. '72.0.3626.14',
  940. '71.0.3578.96',
  941. '71.0.3578.95',
  942. '72.0.3626.13',
  943. '71.0.3578.94',
  944. '73.0.3636.2',
  945. '71.0.3578.93',
  946. '73.0.3636.1',
  947. '73.0.3636.0',
  948. '72.0.3626.12',
  949. '71.0.3578.92',
  950. '73.0.3635.1',
  951. '73.0.3635.0',
  952. '72.0.3626.11',
  953. '71.0.3578.91',
  954. '73.0.3634.2',
  955. '73.0.3634.1',
  956. '73.0.3634.0',
  957. '72.0.3626.10',
  958. '71.0.3578.90',
  959. '71.0.3578.89',
  960. '73.0.3633.2',
  961. '73.0.3633.1',
  962. '73.0.3633.0',
  963. '72.0.3610.4',
  964. '72.0.3626.9',
  965. '71.0.3578.88',
  966. '73.0.3632.5',
  967. '73.0.3632.4',
  968. '73.0.3632.3',
  969. '73.0.3632.2',
  970. '73.0.3632.1',
  971. '73.0.3632.0',
  972. '72.0.3626.8',
  973. '71.0.3578.87',
  974. '73.0.3631.2',
  975. '73.0.3631.1',
  976. '73.0.3631.0',
  977. '72.0.3626.7',
  978. '71.0.3578.86',
  979. '72.0.3626.6',
  980. '73.0.3630.1',
  981. '73.0.3630.0',
  982. '72.0.3626.5',
  983. '71.0.3578.85',
  984. '72.0.3626.4',
  985. '73.0.3628.3',
  986. '73.0.3628.2',
  987. '73.0.3629.1',
  988. '73.0.3629.0',
  989. '72.0.3626.3',
  990. '71.0.3578.84',
  991. '73.0.3628.1',
  992. '73.0.3628.0',
  993. '71.0.3578.83',
  994. '73.0.3627.1',
  995. '73.0.3627.0',
  996. '72.0.3626.2',
  997. '71.0.3578.82',
  998. '71.0.3578.81',
  999. '71.0.3578.80',
  1000. '72.0.3626.1',
  1001. '72.0.3626.0',
  1002. '71.0.3578.79',
  1003. '70.0.3538.124',
  1004. '71.0.3578.78',
  1005. '72.0.3623.4',
  1006. '72.0.3625.2',
  1007. '72.0.3625.1',
  1008. '72.0.3625.0',
  1009. '71.0.3578.77',
  1010. '70.0.3538.123',
  1011. '72.0.3624.4',
  1012. '72.0.3624.3',
  1013. '72.0.3624.2',
  1014. '71.0.3578.76',
  1015. '72.0.3624.1',
  1016. '72.0.3624.0',
  1017. '72.0.3623.3',
  1018. '71.0.3578.75',
  1019. '70.0.3538.122',
  1020. '71.0.3578.74',
  1021. '72.0.3623.2',
  1022. '72.0.3610.3',
  1023. '72.0.3623.1',
  1024. '72.0.3623.0',
  1025. '72.0.3622.3',
  1026. '72.0.3622.2',
  1027. '71.0.3578.73',
  1028. '70.0.3538.121',
  1029. '72.0.3622.1',
  1030. '72.0.3622.0',
  1031. '71.0.3578.72',
  1032. '70.0.3538.120',
  1033. '72.0.3621.1',
  1034. '72.0.3621.0',
  1035. '71.0.3578.71',
  1036. '70.0.3538.119',
  1037. '72.0.3620.1',
  1038. '72.0.3620.0',
  1039. '71.0.3578.70',
  1040. '70.0.3538.118',
  1041. '71.0.3578.69',
  1042. '72.0.3619.1',
  1043. '72.0.3619.0',
  1044. '71.0.3578.68',
  1045. '70.0.3538.117',
  1046. '71.0.3578.67',
  1047. '72.0.3618.1',
  1048. '72.0.3618.0',
  1049. '71.0.3578.66',
  1050. '70.0.3538.116',
  1051. '72.0.3617.1',
  1052. '72.0.3617.0',
  1053. '71.0.3578.65',
  1054. '70.0.3538.115',
  1055. '72.0.3602.3',
  1056. '71.0.3578.64',
  1057. '72.0.3616.1',
  1058. '72.0.3616.0',
  1059. '71.0.3578.63',
  1060. '70.0.3538.114',
  1061. '71.0.3578.62',
  1062. '72.0.3615.1',
  1063. '72.0.3615.0',
  1064. '71.0.3578.61',
  1065. '70.0.3538.113',
  1066. '72.0.3614.1',
  1067. '72.0.3614.0',
  1068. '71.0.3578.60',
  1069. '70.0.3538.112',
  1070. '72.0.3613.1',
  1071. '72.0.3613.0',
  1072. '71.0.3578.59',
  1073. '70.0.3538.111',
  1074. '72.0.3612.2',
  1075. '72.0.3612.1',
  1076. '72.0.3612.0',
  1077. '70.0.3538.110',
  1078. '71.0.3578.58',
  1079. '70.0.3538.109',
  1080. '72.0.3611.2',
  1081. '72.0.3611.1',
  1082. '72.0.3611.0',
  1083. '71.0.3578.57',
  1084. '70.0.3538.108',
  1085. '72.0.3610.2',
  1086. '71.0.3578.56',
  1087. '71.0.3578.55',
  1088. '72.0.3610.1',
  1089. '72.0.3610.0',
  1090. '71.0.3578.54',
  1091. '70.0.3538.107',
  1092. '71.0.3578.53',
  1093. '72.0.3609.3',
  1094. '71.0.3578.52',
  1095. '72.0.3609.2',
  1096. '71.0.3578.51',
  1097. '72.0.3608.5',
  1098. '72.0.3609.1',
  1099. '72.0.3609.0',
  1100. '71.0.3578.50',
  1101. '70.0.3538.106',
  1102. '72.0.3608.4',
  1103. '72.0.3608.3',
  1104. '72.0.3608.2',
  1105. '71.0.3578.49',
  1106. '72.0.3608.1',
  1107. '72.0.3608.0',
  1108. '70.0.3538.105',
  1109. '71.0.3578.48',
  1110. '72.0.3607.1',
  1111. '72.0.3607.0',
  1112. '71.0.3578.47',
  1113. '70.0.3538.104',
  1114. '72.0.3606.2',
  1115. '72.0.3606.1',
  1116. '72.0.3606.0',
  1117. '71.0.3578.46',
  1118. '70.0.3538.103',
  1119. '70.0.3538.102',
  1120. '72.0.3605.3',
  1121. '72.0.3605.2',
  1122. '72.0.3605.1',
  1123. '72.0.3605.0',
  1124. '71.0.3578.45',
  1125. '70.0.3538.101',
  1126. '71.0.3578.44',
  1127. '71.0.3578.43',
  1128. '70.0.3538.100',
  1129. '70.0.3538.99',
  1130. '71.0.3578.42',
  1131. '72.0.3604.1',
  1132. '72.0.3604.0',
  1133. '71.0.3578.41',
  1134. '70.0.3538.98',
  1135. '71.0.3578.40',
  1136. '72.0.3603.2',
  1137. '72.0.3603.1',
  1138. '72.0.3603.0',
  1139. '71.0.3578.39',
  1140. '70.0.3538.97',
  1141. '72.0.3602.2',
  1142. '71.0.3578.38',
  1143. '71.0.3578.37',
  1144. '72.0.3602.1',
  1145. '72.0.3602.0',
  1146. '71.0.3578.36',
  1147. '70.0.3538.96',
  1148. '72.0.3601.1',
  1149. '72.0.3601.0',
  1150. '71.0.3578.35',
  1151. '70.0.3538.95',
  1152. '72.0.3600.1',
  1153. '72.0.3600.0',
  1154. '71.0.3578.34',
  1155. '70.0.3538.94',
  1156. '72.0.3599.3',
  1157. '72.0.3599.2',
  1158. '72.0.3599.1',
  1159. '72.0.3599.0',
  1160. '71.0.3578.33',
  1161. '70.0.3538.93',
  1162. '72.0.3598.1',
  1163. '72.0.3598.0',
  1164. '71.0.3578.32',
  1165. '70.0.3538.87',
  1166. '72.0.3597.1',
  1167. '72.0.3597.0',
  1168. '72.0.3596.2',
  1169. '71.0.3578.31',
  1170. '70.0.3538.86',
  1171. '71.0.3578.30',
  1172. '71.0.3578.29',
  1173. '72.0.3596.1',
  1174. '72.0.3596.0',
  1175. '71.0.3578.28',
  1176. '70.0.3538.85',
  1177. '72.0.3595.2',
  1178. '72.0.3591.3',
  1179. '72.0.3595.1',
  1180. '72.0.3595.0',
  1181. '71.0.3578.27',
  1182. '70.0.3538.84',
  1183. '72.0.3594.1',
  1184. '72.0.3594.0',
  1185. '71.0.3578.26',
  1186. '70.0.3538.83',
  1187. '72.0.3593.2',
  1188. '72.0.3593.1',
  1189. '72.0.3593.0',
  1190. '71.0.3578.25',
  1191. '70.0.3538.82',
  1192. '72.0.3589.3',
  1193. '72.0.3592.2',
  1194. '72.0.3592.1',
  1195. '72.0.3592.0',
  1196. '71.0.3578.24',
  1197. '72.0.3589.2',
  1198. '70.0.3538.81',
  1199. '70.0.3538.80',
  1200. '72.0.3591.2',
  1201. '72.0.3591.1',
  1202. '72.0.3591.0',
  1203. '71.0.3578.23',
  1204. '70.0.3538.79',
  1205. '71.0.3578.22',
  1206. '72.0.3590.1',
  1207. '72.0.3590.0',
  1208. '71.0.3578.21',
  1209. '70.0.3538.78',
  1210. '70.0.3538.77',
  1211. '72.0.3589.1',
  1212. '72.0.3589.0',
  1213. '71.0.3578.20',
  1214. '70.0.3538.76',
  1215. '71.0.3578.19',
  1216. '70.0.3538.75',
  1217. '72.0.3588.1',
  1218. '72.0.3588.0',
  1219. '71.0.3578.18',
  1220. '70.0.3538.74',
  1221. '72.0.3586.2',
  1222. '72.0.3587.0',
  1223. '71.0.3578.17',
  1224. '70.0.3538.73',
  1225. '72.0.3586.1',
  1226. '72.0.3586.0',
  1227. '71.0.3578.16',
  1228. '70.0.3538.72',
  1229. '72.0.3585.1',
  1230. '72.0.3585.0',
  1231. '71.0.3578.15',
  1232. '70.0.3538.71',
  1233. '71.0.3578.14',
  1234. '72.0.3584.1',
  1235. '72.0.3584.0',
  1236. '71.0.3578.13',
  1237. '70.0.3538.70',
  1238. '72.0.3583.2',
  1239. '71.0.3578.12',
  1240. '72.0.3583.1',
  1241. '72.0.3583.0',
  1242. '71.0.3578.11',
  1243. '70.0.3538.69',
  1244. '71.0.3578.10',
  1245. '72.0.3582.0',
  1246. '72.0.3581.4',
  1247. '71.0.3578.9',
  1248. '70.0.3538.67',
  1249. '72.0.3581.3',
  1250. '72.0.3581.2',
  1251. '72.0.3581.1',
  1252. '72.0.3581.0',
  1253. '71.0.3578.8',
  1254. '70.0.3538.66',
  1255. '72.0.3580.1',
  1256. '72.0.3580.0',
  1257. '71.0.3578.7',
  1258. '70.0.3538.65',
  1259. '71.0.3578.6',
  1260. '72.0.3579.1',
  1261. '72.0.3579.0',
  1262. '71.0.3578.5',
  1263. '70.0.3538.64',
  1264. '71.0.3578.4',
  1265. '71.0.3578.3',
  1266. '71.0.3578.2',
  1267. '71.0.3578.1',
  1268. '71.0.3578.0',
  1269. '70.0.3538.63',
  1270. '69.0.3497.128',
  1271. '70.0.3538.62',
  1272. '70.0.3538.61',
  1273. '70.0.3538.60',
  1274. '70.0.3538.59',
  1275. '71.0.3577.1',
  1276. '71.0.3577.0',
  1277. '70.0.3538.58',
  1278. '69.0.3497.127',
  1279. '71.0.3576.2',
  1280. '71.0.3576.1',
  1281. '71.0.3576.0',
  1282. '70.0.3538.57',
  1283. '70.0.3538.56',
  1284. '71.0.3575.2',
  1285. '70.0.3538.55',
  1286. '69.0.3497.126',
  1287. '70.0.3538.54',
  1288. '71.0.3575.1',
  1289. '71.0.3575.0',
  1290. '71.0.3574.1',
  1291. '71.0.3574.0',
  1292. '70.0.3538.53',
  1293. '69.0.3497.125',
  1294. '70.0.3538.52',
  1295. '71.0.3573.1',
  1296. '71.0.3573.0',
  1297. '70.0.3538.51',
  1298. '69.0.3497.124',
  1299. '71.0.3572.1',
  1300. '71.0.3572.0',
  1301. '70.0.3538.50',
  1302. '69.0.3497.123',
  1303. '71.0.3571.2',
  1304. '70.0.3538.49',
  1305. '69.0.3497.122',
  1306. '71.0.3571.1',
  1307. '71.0.3571.0',
  1308. '70.0.3538.48',
  1309. '69.0.3497.121',
  1310. '71.0.3570.1',
  1311. '71.0.3570.0',
  1312. '70.0.3538.47',
  1313. '69.0.3497.120',
  1314. '71.0.3568.2',
  1315. '71.0.3569.1',
  1316. '71.0.3569.0',
  1317. '70.0.3538.46',
  1318. '69.0.3497.119',
  1319. '70.0.3538.45',
  1320. '71.0.3568.1',
  1321. '71.0.3568.0',
  1322. '70.0.3538.44',
  1323. '69.0.3497.118',
  1324. '70.0.3538.43',
  1325. '70.0.3538.42',
  1326. '71.0.3567.1',
  1327. '71.0.3567.0',
  1328. '70.0.3538.41',
  1329. '69.0.3497.117',
  1330. '71.0.3566.1',
  1331. '71.0.3566.0',
  1332. '70.0.3538.40',
  1333. '69.0.3497.116',
  1334. '71.0.3565.1',
  1335. '71.0.3565.0',
  1336. '70.0.3538.39',
  1337. '69.0.3497.115',
  1338. '71.0.3564.1',
  1339. '71.0.3564.0',
  1340. '70.0.3538.38',
  1341. '69.0.3497.114',
  1342. '71.0.3563.0',
  1343. '71.0.3562.2',
  1344. '70.0.3538.37',
  1345. '69.0.3497.113',
  1346. '70.0.3538.36',
  1347. '70.0.3538.35',
  1348. '71.0.3562.1',
  1349. '71.0.3562.0',
  1350. '70.0.3538.34',
  1351. '69.0.3497.112',
  1352. '70.0.3538.33',
  1353. '71.0.3561.1',
  1354. '71.0.3561.0',
  1355. '70.0.3538.32',
  1356. '69.0.3497.111',
  1357. '71.0.3559.6',
  1358. '71.0.3560.1',
  1359. '71.0.3560.0',
  1360. '71.0.3559.5',
  1361. '71.0.3559.4',
  1362. '70.0.3538.31',
  1363. '69.0.3497.110',
  1364. '71.0.3559.3',
  1365. '70.0.3538.30',
  1366. '69.0.3497.109',
  1367. '71.0.3559.2',
  1368. '71.0.3559.1',
  1369. '71.0.3559.0',
  1370. '70.0.3538.29',
  1371. '69.0.3497.108',
  1372. '71.0.3558.2',
  1373. '71.0.3558.1',
  1374. '71.0.3558.0',
  1375. '70.0.3538.28',
  1376. '69.0.3497.107',
  1377. '71.0.3557.2',
  1378. '71.0.3557.1',
  1379. '71.0.3557.0',
  1380. '70.0.3538.27',
  1381. '69.0.3497.106',
  1382. '71.0.3554.4',
  1383. '70.0.3538.26',
  1384. '71.0.3556.1',
  1385. '71.0.3556.0',
  1386. '70.0.3538.25',
  1387. '71.0.3554.3',
  1388. '69.0.3497.105',
  1389. '71.0.3554.2',
  1390. '70.0.3538.24',
  1391. '69.0.3497.104',
  1392. '71.0.3555.2',
  1393. '70.0.3538.23',
  1394. '71.0.3555.1',
  1395. '71.0.3555.0',
  1396. '70.0.3538.22',
  1397. '69.0.3497.103',
  1398. '71.0.3554.1',
  1399. '71.0.3554.0',
  1400. '70.0.3538.21',
  1401. '69.0.3497.102',
  1402. '71.0.3553.3',
  1403. '70.0.3538.20',
  1404. '69.0.3497.101',
  1405. '71.0.3553.2',
  1406. '69.0.3497.100',
  1407. '71.0.3553.1',
  1408. '71.0.3553.0',
  1409. '70.0.3538.19',
  1410. '69.0.3497.99',
  1411. '69.0.3497.98',
  1412. '69.0.3497.97',
  1413. '71.0.3552.6',
  1414. '71.0.3552.5',
  1415. '71.0.3552.4',
  1416. '71.0.3552.3',
  1417. '71.0.3552.2',
  1418. '71.0.3552.1',
  1419. '71.0.3552.0',
  1420. '70.0.3538.18',
  1421. '69.0.3497.96',
  1422. '71.0.3551.3',
  1423. '71.0.3551.2',
  1424. '71.0.3551.1',
  1425. '71.0.3551.0',
  1426. '70.0.3538.17',
  1427. '69.0.3497.95',
  1428. '71.0.3550.3',
  1429. '71.0.3550.2',
  1430. '71.0.3550.1',
  1431. '71.0.3550.0',
  1432. '70.0.3538.16',
  1433. '69.0.3497.94',
  1434. '71.0.3549.1',
  1435. '71.0.3549.0',
  1436. '70.0.3538.15',
  1437. '69.0.3497.93',
  1438. '69.0.3497.92',
  1439. '71.0.3548.1',
  1440. '71.0.3548.0',
  1441. '70.0.3538.14',
  1442. '69.0.3497.91',
  1443. '71.0.3547.1',
  1444. '71.0.3547.0',
  1445. '70.0.3538.13',
  1446. '69.0.3497.90',
  1447. '71.0.3546.2',
  1448. '69.0.3497.89',
  1449. '71.0.3546.1',
  1450. '71.0.3546.0',
  1451. '70.0.3538.12',
  1452. '69.0.3497.88',
  1453. '71.0.3545.4',
  1454. '71.0.3545.3',
  1455. '71.0.3545.2',
  1456. '71.0.3545.1',
  1457. '71.0.3545.0',
  1458. '70.0.3538.11',
  1459. '69.0.3497.87',
  1460. '71.0.3544.5',
  1461. '71.0.3544.4',
  1462. '71.0.3544.3',
  1463. '71.0.3544.2',
  1464. '71.0.3544.1',
  1465. '71.0.3544.0',
  1466. '69.0.3497.86',
  1467. '70.0.3538.10',
  1468. '69.0.3497.85',
  1469. '70.0.3538.9',
  1470. '69.0.3497.84',
  1471. '71.0.3543.4',
  1472. '70.0.3538.8',
  1473. '71.0.3543.3',
  1474. '71.0.3543.2',
  1475. '71.0.3543.1',
  1476. '71.0.3543.0',
  1477. '70.0.3538.7',
  1478. '69.0.3497.83',
  1479. '71.0.3542.2',
  1480. '71.0.3542.1',
  1481. '71.0.3542.0',
  1482. '70.0.3538.6',
  1483. '69.0.3497.82',
  1484. '69.0.3497.81',
  1485. '71.0.3541.1',
  1486. '71.0.3541.0',
  1487. '70.0.3538.5',
  1488. '69.0.3497.80',
  1489. '71.0.3540.1',
  1490. '71.0.3540.0',
  1491. '70.0.3538.4',
  1492. '69.0.3497.79',
  1493. '70.0.3538.3',
  1494. '71.0.3539.1',
  1495. '71.0.3539.0',
  1496. '69.0.3497.78',
  1497. '68.0.3440.134',
  1498. '69.0.3497.77',
  1499. '70.0.3538.2',
  1500. '70.0.3538.1',
  1501. '70.0.3538.0',
  1502. '69.0.3497.76',
  1503. '68.0.3440.133',
  1504. '69.0.3497.75',
  1505. '70.0.3537.2',
  1506. '70.0.3537.1',
  1507. '70.0.3537.0',
  1508. '69.0.3497.74',
  1509. '68.0.3440.132',
  1510. '70.0.3536.0',
  1511. '70.0.3535.5',
  1512. '70.0.3535.4',
  1513. '70.0.3535.3',
  1514. '69.0.3497.73',
  1515. '68.0.3440.131',
  1516. '70.0.3532.8',
  1517. '70.0.3532.7',
  1518. '69.0.3497.72',
  1519. '69.0.3497.71',
  1520. '70.0.3535.2',
  1521. '70.0.3535.1',
  1522. '70.0.3535.0',
  1523. '69.0.3497.70',
  1524. '68.0.3440.130',
  1525. '69.0.3497.69',
  1526. '68.0.3440.129',
  1527. '70.0.3534.4',
  1528. '70.0.3534.3',
  1529. '70.0.3534.2',
  1530. '70.0.3534.1',
  1531. '70.0.3534.0',
  1532. '69.0.3497.68',
  1533. '68.0.3440.128',
  1534. '70.0.3533.2',
  1535. '70.0.3533.1',
  1536. '70.0.3533.0',
  1537. '69.0.3497.67',
  1538. '68.0.3440.127',
  1539. '70.0.3532.6',
  1540. '70.0.3532.5',
  1541. '70.0.3532.4',
  1542. '69.0.3497.66',
  1543. '68.0.3440.126',
  1544. '70.0.3532.3',
  1545. '70.0.3532.2',
  1546. '70.0.3532.1',
  1547. '69.0.3497.60',
  1548. '69.0.3497.65',
  1549. '69.0.3497.64',
  1550. '70.0.3532.0',
  1551. '70.0.3531.0',
  1552. '70.0.3530.4',
  1553. '70.0.3530.3',
  1554. '70.0.3530.2',
  1555. '69.0.3497.58',
  1556. '68.0.3440.125',
  1557. '69.0.3497.57',
  1558. '69.0.3497.56',
  1559. '69.0.3497.55',
  1560. '69.0.3497.54',
  1561. '70.0.3530.1',
  1562. '70.0.3530.0',
  1563. '69.0.3497.53',
  1564. '68.0.3440.124',
  1565. '69.0.3497.52',
  1566. '70.0.3529.3',
  1567. '70.0.3529.2',
  1568. '70.0.3529.1',
  1569. '70.0.3529.0',
  1570. '69.0.3497.51',
  1571. '70.0.3528.4',
  1572. '68.0.3440.123',
  1573. '70.0.3528.3',
  1574. '70.0.3528.2',
  1575. '70.0.3528.1',
  1576. '70.0.3528.0',
  1577. '69.0.3497.50',
  1578. '68.0.3440.122',
  1579. '70.0.3527.1',
  1580. '70.0.3527.0',
  1581. '69.0.3497.49',
  1582. '68.0.3440.121',
  1583. '70.0.3526.1',
  1584. '70.0.3526.0',
  1585. '68.0.3440.120',
  1586. '69.0.3497.48',
  1587. '69.0.3497.47',
  1588. '68.0.3440.119',
  1589. '68.0.3440.118',
  1590. '70.0.3525.5',
  1591. '70.0.3525.4',
  1592. '70.0.3525.3',
  1593. '68.0.3440.117',
  1594. '69.0.3497.46',
  1595. '70.0.3525.2',
  1596. '70.0.3525.1',
  1597. '70.0.3525.0',
  1598. '69.0.3497.45',
  1599. '68.0.3440.116',
  1600. '70.0.3524.4',
  1601. '70.0.3524.3',
  1602. '69.0.3497.44',
  1603. '70.0.3524.2',
  1604. '70.0.3524.1',
  1605. '70.0.3524.0',
  1606. '70.0.3523.2',
  1607. '69.0.3497.43',
  1608. '68.0.3440.115',
  1609. '70.0.3505.9',
  1610. '69.0.3497.42',
  1611. '70.0.3505.8',
  1612. '70.0.3523.1',
  1613. '70.0.3523.0',
  1614. '69.0.3497.41',
  1615. '68.0.3440.114',
  1616. '70.0.3505.7',
  1617. '69.0.3497.40',
  1618. '70.0.3522.1',
  1619. '70.0.3522.0',
  1620. '70.0.3521.2',
  1621. '69.0.3497.39',
  1622. '68.0.3440.113',
  1623. '70.0.3505.6',
  1624. '70.0.3521.1',
  1625. '70.0.3521.0',
  1626. '69.0.3497.38',
  1627. '68.0.3440.112',
  1628. '70.0.3520.1',
  1629. '70.0.3520.0',
  1630. '69.0.3497.37',
  1631. '68.0.3440.111',
  1632. '70.0.3519.3',
  1633. '70.0.3519.2',
  1634. '70.0.3519.1',
  1635. '70.0.3519.0',
  1636. '69.0.3497.36',
  1637. '68.0.3440.110',
  1638. '70.0.3518.1',
  1639. '70.0.3518.0',
  1640. '69.0.3497.35',
  1641. '69.0.3497.34',
  1642. '68.0.3440.109',
  1643. '70.0.3517.1',
  1644. '70.0.3517.0',
  1645. '69.0.3497.33',
  1646. '68.0.3440.108',
  1647. '69.0.3497.32',
  1648. '70.0.3516.3',
  1649. '70.0.3516.2',
  1650. '70.0.3516.1',
  1651. '70.0.3516.0',
  1652. '69.0.3497.31',
  1653. '68.0.3440.107',
  1654. '70.0.3515.4',
  1655. '68.0.3440.106',
  1656. '70.0.3515.3',
  1657. '70.0.3515.2',
  1658. '70.0.3515.1',
  1659. '70.0.3515.0',
  1660. '69.0.3497.30',
  1661. '68.0.3440.105',
  1662. '68.0.3440.104',
  1663. '70.0.3514.2',
  1664. '70.0.3514.1',
  1665. '70.0.3514.0',
  1666. '69.0.3497.29',
  1667. '68.0.3440.103',
  1668. '70.0.3513.1',
  1669. '70.0.3513.0',
  1670. '69.0.3497.28',
  1671. )
  1672. return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
  1673. std_headers = {
  1674. 'User-Agent': random_user_agent(),
  1675. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  1676. 'Accept-Language': 'en-us,en;q=0.5',
  1677. }
  1678. USER_AGENTS = {
  1679. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  1680. }
  1681. NO_DEFAULT = object()
  1682. IDENTITY = lambda x: x
  1683. ENGLISH_MONTH_NAMES = [
  1684. 'January', 'February', 'March', 'April', 'May', 'June',
  1685. 'July', 'August', 'September', 'October', 'November', 'December']
  1686. MONTH_NAMES = {
  1687. 'en': ENGLISH_MONTH_NAMES,
  1688. 'fr': [
  1689. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  1690. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  1691. }
  1692. # Timezone names for RFC2822 obs-zone
  1693. # From https://github.com/python/cpython/blob/3.11/Lib/email/_parseaddr.py#L36-L42
  1694. TIMEZONE_NAMES = {
  1695. 'UT': 0, 'UTC': 0, 'GMT': 0, 'Z': 0,
  1696. 'AST': -4, 'ADT': -3, # Atlantic (used in Canada)
  1697. 'EST': -5, 'EDT': -4, # Eastern
  1698. 'CST': -6, 'CDT': -5, # Central
  1699. 'MST': -7, 'MDT': -6, # Mountain
  1700. 'PST': -8, 'PDT': -7 # Pacific
  1701. }
  1702. # needed for sanitizing filenames in restricted mode
  1703. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  1704. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  1705. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  1706. DATE_FORMATS = (
  1707. '%d %B %Y',
  1708. '%d %b %Y',
  1709. '%B %d %Y',
  1710. '%B %dst %Y',
  1711. '%B %dnd %Y',
  1712. '%B %drd %Y',
  1713. '%B %dth %Y',
  1714. '%b %d %Y',
  1715. '%b %dst %Y',
  1716. '%b %dnd %Y',
  1717. '%b %drd %Y',
  1718. '%b %dth %Y',
  1719. '%b %dst %Y %I:%M',
  1720. '%b %dnd %Y %I:%M',
  1721. '%b %drd %Y %I:%M',
  1722. '%b %dth %Y %I:%M',
  1723. '%Y %m %d',
  1724. '%Y-%m-%d',
  1725. '%Y.%m.%d.',
  1726. '%Y/%m/%d',
  1727. '%Y/%m/%d %H:%M',
  1728. '%Y/%m/%d %H:%M:%S',
  1729. '%Y%m%d%H%M',
  1730. '%Y%m%d%H%M%S',
  1731. '%Y%m%d',
  1732. '%Y-%m-%d %H:%M',
  1733. '%Y-%m-%d %H:%M:%S',
  1734. '%Y-%m-%d %H:%M:%S.%f',
  1735. '%Y-%m-%d %H:%M:%S:%f',
  1736. '%d.%m.%Y %H:%M',
  1737. '%d.%m.%Y %H.%M',
  1738. '%Y-%m-%dT%H:%M:%SZ',
  1739. '%Y-%m-%dT%H:%M:%S.%fZ',
  1740. '%Y-%m-%dT%H:%M:%S.%f0Z',
  1741. '%Y-%m-%dT%H:%M:%S',
  1742. '%Y-%m-%dT%H:%M:%S.%f',
  1743. '%Y-%m-%dT%H:%M',
  1744. '%b %d %Y at %H:%M',
  1745. '%b %d %Y at %H:%M:%S',
  1746. '%B %d %Y at %H:%M',
  1747. '%B %d %Y at %H:%M:%S',
  1748. '%H:%M %d-%b-%Y',
  1749. )
  1750. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  1751. DATE_FORMATS_DAY_FIRST.extend([
  1752. '%d-%m-%Y',
  1753. '%d.%m.%Y',
  1754. '%d.%m.%y',
  1755. '%d/%m/%Y',
  1756. '%d/%m/%y',
  1757. '%d/%m/%Y %H:%M:%S',
  1758. '%d-%m-%Y %H:%M',
  1759. ])
  1760. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  1761. DATE_FORMATS_MONTH_FIRST.extend([
  1762. '%m-%d-%Y',
  1763. '%m.%d.%Y',
  1764. '%m/%d/%Y',
  1765. '%m/%d/%y',
  1766. '%m/%d/%Y %H:%M:%S',
  1767. ])
  1768. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  1769. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  1770. def preferredencoding():
  1771. """Get preferred encoding.
  1772. Returns the best encoding scheme for the system, based on
  1773. locale.getpreferredencoding() and some further tweaks.
  1774. """
  1775. try:
  1776. pref = locale.getpreferredencoding()
  1777. 'TEST'.encode(pref)
  1778. except Exception:
  1779. pref = 'UTF-8'
  1780. return pref
  1781. def write_json_file(obj, fn):
  1782. """ Encode obj as JSON and write it to fn, atomically if possible """
  1783. fn = encodeFilename(fn)
  1784. if sys.version_info < (3, 0) and sys.platform != 'win32':
  1785. encoding = get_filesystem_encoding()
  1786. # os.path.basename returns a bytes object, but NamedTemporaryFile
  1787. # will fail if the filename contains non-ascii characters unless we
  1788. # use a unicode object
  1789. path_basename = lambda f: os.path.basename(f).decode(encoding)
  1790. # the same for os.path.dirname
  1791. path_dirname = lambda f: os.path.dirname(f).decode(encoding)
  1792. else:
  1793. path_basename = os.path.basename
  1794. path_dirname = os.path.dirname
  1795. args = {
  1796. 'suffix': '.tmp',
  1797. 'prefix': path_basename(fn) + '.',
  1798. 'dir': path_dirname(fn),
  1799. 'delete': False,
  1800. }
  1801. # In Python 2.x, json.dump expects a bytestream.
  1802. # In Python 3.x, it writes to a character stream
  1803. if sys.version_info < (3, 0):
  1804. args['mode'] = 'wb'
  1805. else:
  1806. args.update({
  1807. 'mode': 'w',
  1808. 'encoding': 'utf-8',
  1809. })
  1810. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  1811. try:
  1812. with tf:
  1813. json.dump(obj, tf)
  1814. with compat_contextlib_suppress(OSError):
  1815. if sys.platform == 'win32':
  1816. # Need to remove existing file on Windows, else os.rename raises
  1817. # WindowsError or FileExistsError.
  1818. os.unlink(fn)
  1819. mask = os.umask(0)
  1820. os.umask(mask)
  1821. os.chmod(tf.name, 0o666 & ~mask)
  1822. os.rename(tf.name, fn)
  1823. except Exception:
  1824. with compat_contextlib_suppress(OSError):
  1825. os.remove(tf.name)
  1826. raise
  1827. if sys.version_info >= (2, 7):
  1828. def find_xpath_attr(node, xpath, key, val=None):
  1829. """ Find the xpath xpath[@key=val] """
  1830. assert re.match(r'^[a-zA-Z_-]+$', key)
  1831. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  1832. return node.find(expr)
  1833. else:
  1834. def find_xpath_attr(node, xpath, key, val=None):
  1835. for f in node.findall(compat_xpath(xpath)):
  1836. if key not in f.attrib:
  1837. continue
  1838. if val is None or f.attrib.get(key) == val:
  1839. return f
  1840. return None
  1841. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  1842. # the namespace parameter
  1843. def xpath_with_ns(path, ns_map):
  1844. components = [c.split(':') for c in path.split('/')]
  1845. replaced = []
  1846. for c in components:
  1847. if len(c) == 1:
  1848. replaced.append(c[0])
  1849. else:
  1850. ns, tag = c
  1851. replaced.append('{%s}%s' % (ns_map[ns], tag))
  1852. return '/'.join(replaced)
  1853. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1854. def _find_xpath(xpath):
  1855. return node.find(compat_xpath(xpath))
  1856. if isinstance(xpath, compat_basestring):
  1857. n = _find_xpath(xpath)
  1858. else:
  1859. for xp in xpath:
  1860. n = _find_xpath(xp)
  1861. if n is not None:
  1862. break
  1863. if n is None:
  1864. if default is not NO_DEFAULT:
  1865. return default
  1866. elif fatal:
  1867. name = xpath if name is None else name
  1868. raise ExtractorError('Could not find XML element %s' % name)
  1869. else:
  1870. return None
  1871. return n
  1872. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1873. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  1874. if n is None or n == default:
  1875. return n
  1876. if n.text is None:
  1877. if default is not NO_DEFAULT:
  1878. return default
  1879. elif fatal:
  1880. name = xpath if name is None else name
  1881. raise ExtractorError('Could not find XML element\'s text %s' % name)
  1882. else:
  1883. return None
  1884. return n.text
  1885. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  1886. n = find_xpath_attr(node, xpath, key)
  1887. if n is None:
  1888. if default is not NO_DEFAULT:
  1889. return default
  1890. elif fatal:
  1891. name = '%s[@%s]' % (xpath, key) if name is None else name
  1892. raise ExtractorError('Could not find XML attribute %s' % name)
  1893. else:
  1894. return None
  1895. return n.attrib[key]
  1896. def get_element_by_id(id, html):
  1897. """Return the content of the tag with the specified ID in the passed HTML document"""
  1898. return get_element_by_attribute('id', id, html)
  1899. def get_element_by_class(class_name, html):
  1900. """Return the content of the first tag with the specified class in the passed HTML document"""
  1901. retval = get_elements_by_class(class_name, html)
  1902. return retval[0] if retval else None
  1903. def get_element_by_attribute(attribute, value, html, escape_value=True):
  1904. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  1905. return retval[0] if retval else None
  1906. def get_elements_by_class(class_name, html):
  1907. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  1908. return get_elements_by_attribute(
  1909. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  1910. html, escape_value=False)
  1911. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  1912. """Return the content of the tag with the specified attribute in the passed HTML document"""
  1913. value = re.escape(value) if escape_value else value
  1914. retlist = []
  1915. for m in re.finditer(r'''(?xs)
  1916. <([a-zA-Z0-9:._-]+)
  1917. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1918. \s+%s=['"]?%s['"]?
  1919. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1920. \s*>
  1921. (?P<content>.*?)
  1922. </\1>
  1923. ''' % (re.escape(attribute), value), html):
  1924. res = m.group('content')
  1925. if res.startswith('"') or res.startswith("'"):
  1926. res = res[1:-1]
  1927. retlist.append(unescapeHTML(res))
  1928. return retlist
  1929. class HTMLAttributeParser(compat_HTMLParser):
  1930. """Trivial HTML parser to gather the attributes for a single element"""
  1931. def __init__(self):
  1932. self.attrs = {}
  1933. compat_HTMLParser.__init__(self)
  1934. def handle_starttag(self, tag, attrs):
  1935. self.attrs = dict(attrs)
  1936. def extract_attributes(html_element):
  1937. """Given a string for an HTML element such as
  1938. <el
  1939. a="foo" B="bar" c="&98;az" d=boz
  1940. empty= noval entity="&amp;"
  1941. sq='"' dq="'"
  1942. >
  1943. Decode and return a dictionary of attributes.
  1944. {
  1945. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  1946. 'empty': '', 'noval': None, 'entity': '&',
  1947. 'sq': '"', 'dq': '\''
  1948. }.
  1949. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  1950. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  1951. """
  1952. ret = None
  1953. # Older Python may throw HTMLParseError in case of malformed HTML (and on .close()!)
  1954. with compat_contextlib_suppress(compat_HTMLParseError):
  1955. with contextlib.closing(HTMLAttributeParser()) as parser:
  1956. parser.feed(html_element)
  1957. ret = parser.attrs
  1958. return ret or {}
  1959. def clean_html(html):
  1960. """Clean an HTML snippet into a readable string"""
  1961. if html is None: # Convenience for sanitizing descriptions etc.
  1962. return html
  1963. # Newline vs <br />
  1964. html = html.replace('\n', ' ')
  1965. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  1966. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  1967. # Strip html tags
  1968. html = re.sub('<.*?>', '', html)
  1969. # Replace html entities
  1970. html = unescapeHTML(html)
  1971. return html.strip()
  1972. def sanitize_open(filename, open_mode):
  1973. """Try to open the given filename, and slightly tweak it if this fails.
  1974. Attempts to open the given filename. If this fails, it tries to change
  1975. the filename slightly, step by step, until it's either able to open it
  1976. or it fails and raises a final exception, like the standard open()
  1977. function.
  1978. It returns the tuple (stream, definitive_file_name).
  1979. """
  1980. try:
  1981. if filename == '-':
  1982. if sys.platform == 'win32':
  1983. import msvcrt
  1984. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  1985. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  1986. stream = open(encodeFilename(filename), open_mode)
  1987. return (stream, filename)
  1988. except (IOError, OSError) as err:
  1989. if err.errno in (errno.EACCES,):
  1990. raise
  1991. # In case of error, try to remove win32 forbidden chars
  1992. alt_filename = sanitize_path(filename)
  1993. if alt_filename == filename:
  1994. raise
  1995. else:
  1996. # An exception here should be caught in the caller
  1997. stream = open(encodeFilename(alt_filename), open_mode)
  1998. return (stream, alt_filename)
  1999. def timeconvert(timestr):
  2000. """Convert RFC 2822 defined time string into system timestamp"""
  2001. timestamp = None
  2002. timetuple = email.utils.parsedate_tz(timestr)
  2003. if timetuple is not None:
  2004. timestamp = email.utils.mktime_tz(timetuple)
  2005. return timestamp
  2006. def sanitize_filename(s, restricted=False, is_id=False):
  2007. """Sanitizes a string so it could be used as part of a filename.
  2008. If restricted is set, use a stricter subset of allowed characters.
  2009. Set is_id if this is not an arbitrary string, but an ID that should be kept
  2010. if possible.
  2011. """
  2012. def replace_insane(char):
  2013. if restricted and char in ACCENT_CHARS:
  2014. return ACCENT_CHARS[char]
  2015. if char == '?' or ord(char) < 32 or ord(char) == 127:
  2016. return ''
  2017. elif char == '"':
  2018. return '' if restricted else '\''
  2019. elif char == ':':
  2020. return '_-' if restricted else ' -'
  2021. elif char in '\\/|*<>':
  2022. return '_'
  2023. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  2024. return '_'
  2025. if restricted and ord(char) > 127:
  2026. return '' if unicodedata.category(char)[0] in 'CM' else '_'
  2027. return char
  2028. # Replace look-alike Unicode glyphs
  2029. if restricted and not is_id:
  2030. s = unicodedata.normalize('NFKC', s)
  2031. # Handle timestamps
  2032. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  2033. result = ''.join(map(replace_insane, s))
  2034. if not is_id:
  2035. while '__' in result:
  2036. result = result.replace('__', '_')
  2037. result = result.strip('_')
  2038. # Common case of "Foreign band name - English song title"
  2039. if restricted and result.startswith('-_'):
  2040. result = result[2:]
  2041. if result.startswith('-'):
  2042. result = '_' + result[len('-'):]
  2043. result = result.lstrip('.')
  2044. if not result:
  2045. result = '_'
  2046. return result
  2047. def sanitize_path(s):
  2048. """Sanitizes and normalizes path on Windows"""
  2049. if sys.platform != 'win32':
  2050. return s
  2051. drive_or_unc, _ = os.path.splitdrive(s)
  2052. if sys.version_info < (2, 7) and not drive_or_unc:
  2053. drive_or_unc, _ = os.path.splitunc(s)
  2054. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  2055. if drive_or_unc:
  2056. norm_path.pop(0)
  2057. sanitized_path = [
  2058. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  2059. for path_part in norm_path]
  2060. if drive_or_unc:
  2061. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  2062. return os.path.join(*sanitized_path)
  2063. def sanitize_url(url):
  2064. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  2065. # the number of unwanted failures due to missing protocol
  2066. if url.startswith('//'):
  2067. return 'http:%s' % url
  2068. # Fix some common typos seen so far
  2069. COMMON_TYPOS = (
  2070. # https://github.com/ytdl-org/youtube-dl/issues/15649
  2071. (r'^httpss://', r'https://'),
  2072. # https://bx1.be/lives/direct-tv/
  2073. (r'^rmtp([es]?)://', r'rtmp\1://'),
  2074. )
  2075. for mistake, fixup in COMMON_TYPOS:
  2076. if re.match(mistake, url):
  2077. return re.sub(mistake, fixup, url)
  2078. return url
  2079. def extract_basic_auth(url):
  2080. parts = compat_urllib_parse.urlsplit(url)
  2081. if parts.username is None:
  2082. return url, None
  2083. url = compat_urllib_parse.urlunsplit(parts._replace(netloc=(
  2084. parts.hostname if parts.port is None
  2085. else '%s:%d' % (parts.hostname, parts.port))))
  2086. auth_payload = base64.b64encode(
  2087. ('%s:%s' % (parts.username, parts.password or '')).encode('utf-8'))
  2088. return url, 'Basic {0}'.format(auth_payload.decode('ascii'))
  2089. def sanitized_Request(url, *args, **kwargs):
  2090. url, auth_header = extract_basic_auth(escape_url(sanitize_url(url)))
  2091. if auth_header is not None:
  2092. headers = args[1] if len(args) > 1 else kwargs.get('headers')
  2093. headers = headers or {}
  2094. headers['Authorization'] = auth_header
  2095. if len(args) <= 1 and kwargs.get('headers') is None:
  2096. kwargs['headers'] = headers
  2097. kwargs = compat_kwargs(kwargs)
  2098. return compat_urllib_request.Request(url, *args, **kwargs)
  2099. def expand_path(s):
  2100. """Expand shell variables and ~"""
  2101. return os.path.expandvars(compat_expanduser(s))
  2102. def orderedSet(iterable):
  2103. """ Remove all duplicates from the input iterable """
  2104. res = []
  2105. for el in iterable:
  2106. if el not in res:
  2107. res.append(el)
  2108. return res
  2109. def _htmlentity_transform(entity_with_semicolon):
  2110. """Transforms an HTML entity to a character."""
  2111. entity = entity_with_semicolon[:-1]
  2112. # Known non-numeric HTML entity
  2113. if entity in compat_html_entities.name2codepoint:
  2114. return compat_chr(compat_html_entities.name2codepoint[entity])
  2115. # TODO: HTML5 allows entities without a semicolon. For example,
  2116. # '&Eacuteric' should be decoded as 'Éric'.
  2117. if entity_with_semicolon in compat_html_entities_html5:
  2118. return compat_html_entities_html5[entity_with_semicolon]
  2119. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  2120. if mobj is not None:
  2121. numstr = mobj.group(1)
  2122. if numstr.startswith('x'):
  2123. base = 16
  2124. numstr = '0%s' % numstr
  2125. else:
  2126. base = 10
  2127. # See https://github.com/ytdl-org/youtube-dl/issues/7518\
  2128. # Also, weirdly, compat_contextlib_suppress fails here in 2.6
  2129. try:
  2130. return compat_chr(int(numstr, base))
  2131. except ValueError:
  2132. pass
  2133. # Unknown entity in name, return its literal representation
  2134. return '&%s;' % entity
  2135. def unescapeHTML(s):
  2136. if s is None:
  2137. return None
  2138. assert isinstance(s, compat_str)
  2139. return re.sub(
  2140. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  2141. def process_communicate_or_kill(p, *args, **kwargs):
  2142. try:
  2143. return p.communicate(*args, **kwargs)
  2144. except BaseException: # Including KeyboardInterrupt
  2145. p.kill()
  2146. p.wait()
  2147. raise
  2148. def get_subprocess_encoding():
  2149. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2150. # For subprocess calls, encode with locale encoding
  2151. # Refer to http://stackoverflow.com/a/9951851/35070
  2152. encoding = preferredencoding()
  2153. else:
  2154. encoding = sys.getfilesystemencoding()
  2155. if encoding is None:
  2156. encoding = 'utf-8'
  2157. return encoding
  2158. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  2159. if sys.version_info < (3, 0) and not sys.platform.startswith('java'):
  2160. def encodeFilename(s, for_subprocess=False):
  2161. """
  2162. @param s The name of the file
  2163. """
  2164. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  2165. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  2166. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  2167. if (not for_subprocess
  2168. and sys.platform == 'win32'
  2169. and sys.getwindowsversion()[0] >= 5
  2170. and isinstance(s, compat_str)):
  2171. return s
  2172. return _encode_compat_str(s, get_subprocess_encoding(), 'ignore')
  2173. def decodeFilename(b, for_subprocess=False):
  2174. return _decode_compat_str(b, get_subprocess_encoding(), 'ignore')
  2175. else:
  2176. # Python 3 has a Unicode API
  2177. encodeFilename = decodeFilename = lambda *s, **k: s[0]
  2178. def encodeArgument(s):
  2179. if not isinstance(s, compat_str):
  2180. # Legacy code that uses byte strings
  2181. # Uncomment the following line after fixing all post processors
  2182. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  2183. s = s.decode('ascii')
  2184. return encodeFilename(s, True)
  2185. def decodeArgument(b):
  2186. return decodeFilename(b, True)
  2187. def decodeOption(optval):
  2188. if optval is None:
  2189. return optval
  2190. return _decode_compat_str(optval)
  2191. def formatSeconds(secs):
  2192. if secs > 3600:
  2193. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  2194. elif secs > 60:
  2195. return '%d:%02d' % (secs // 60, secs % 60)
  2196. else:
  2197. return '%d' % secs
  2198. def make_HTTPS_handler(params, **kwargs):
  2199. # https://www.rfc-editor.org/info/rfc7301
  2200. ALPN_PROTOCOLS = ['http/1.1']
  2201. def set_alpn_protocols(ctx):
  2202. # From https://github.com/yt-dlp/yt-dlp/commit/2c6dcb65fb612fc5bc5c61937bf438d3c473d8d0
  2203. # Thanks @coletdjnz
  2204. # Some servers may (wrongly) reject requests if ALPN extension is not sent. See:
  2205. # https://github.com/python/cpython/issues/85140
  2206. # https://github.com/yt-dlp/yt-dlp/issues/3878
  2207. with compat_contextlib_suppress(AttributeError, NotImplementedError):
  2208. # fails for Python < 2.7.10, not ssl.HAS_ALPN
  2209. ctx.set_alpn_protocols(ALPN_PROTOCOLS)
  2210. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2211. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2212. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2213. set_alpn_protocols(context)
  2214. if opts_no_check_certificate:
  2215. context.check_hostname = False
  2216. context.verify_mode = ssl.CERT_NONE
  2217. with compat_contextlib_suppress(TypeError):
  2218. # Fails with Python 2.7.8 (create_default_context present
  2219. # but HTTPSHandler has no context=)
  2220. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2221. if sys.version_info < (3, 2):
  2222. return YoutubeDLHTTPSHandler(params, **kwargs)
  2223. else: # Python3 < 3.4
  2224. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2225. context.verify_mode = (ssl.CERT_NONE
  2226. if opts_no_check_certificate
  2227. else ssl.CERT_REQUIRED)
  2228. context.set_default_verify_paths()
  2229. set_alpn_protocols(context)
  2230. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2231. def bug_reports_message(before=';'):
  2232. if ytdl_is_updateable():
  2233. update_cmd = 'type youtube-dl -U to update'
  2234. else:
  2235. update_cmd = 'see https://github.com/ytdl-org/youtube-dl/#user-content-installation on how to update'
  2236. msg = (
  2237. 'please report this issue on https://github.com/ytdl-org/youtube-dl/issues ,'
  2238. ' using the appropriate issue template.'
  2239. ' Make sure you are using the latest version; %s.'
  2240. ' Be sure to call youtube-dl with the --verbose option and include the complete output.'
  2241. ) % update_cmd
  2242. before = (before or '').rstrip()
  2243. if not before or before.endswith(('.', '!', '?')):
  2244. msg = msg[0].title() + msg[1:]
  2245. return (before + ' ' if before else '') + msg
  2246. class YoutubeDLError(Exception):
  2247. """Base exception for YoutubeDL errors."""
  2248. pass
  2249. class ExtractorError(YoutubeDLError):
  2250. """Error during info extraction."""
  2251. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2252. """ tb, if given, is the original traceback (so that it can be printed out).
  2253. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2254. """
  2255. self.orig_msg = msg
  2256. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2257. expected = True
  2258. if video_id is not None:
  2259. msg = video_id + ': ' + msg
  2260. if cause:
  2261. msg += ' (caused by %r)' % cause
  2262. if not expected:
  2263. msg += bug_reports_message()
  2264. super(ExtractorError, self).__init__(msg)
  2265. self.traceback = tb
  2266. self.exc_info = sys.exc_info() # preserve original exception
  2267. self.cause = cause
  2268. self.video_id = video_id
  2269. def format_traceback(self):
  2270. if self.traceback is None:
  2271. return None
  2272. return ''.join(traceback.format_tb(self.traceback))
  2273. class UnsupportedError(ExtractorError):
  2274. def __init__(self, url):
  2275. super(UnsupportedError, self).__init__(
  2276. 'Unsupported URL: %s' % url, expected=True)
  2277. self.url = url
  2278. class RegexNotFoundError(ExtractorError):
  2279. """Error when a regex didn't match"""
  2280. pass
  2281. class GeoRestrictedError(ExtractorError):
  2282. """Geographic restriction Error exception.
  2283. This exception may be thrown when a video is not available from your
  2284. geographic location due to geographic restrictions imposed by a website.
  2285. """
  2286. def __init__(self, msg, countries=None):
  2287. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2288. self.msg = msg
  2289. self.countries = countries
  2290. class DownloadError(YoutubeDLError):
  2291. """Download Error exception.
  2292. This exception may be thrown by FileDownloader objects if they are not
  2293. configured to continue on errors. They will contain the appropriate
  2294. error message.
  2295. """
  2296. def __init__(self, msg, exc_info=None):
  2297. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2298. super(DownloadError, self).__init__(msg)
  2299. self.exc_info = exc_info
  2300. class SameFileError(YoutubeDLError):
  2301. """Same File exception.
  2302. This exception will be thrown by FileDownloader objects if they detect
  2303. multiple files would have to be downloaded to the same file on disk.
  2304. """
  2305. pass
  2306. class PostProcessingError(YoutubeDLError):
  2307. """Post Processing exception.
  2308. This exception may be raised by PostProcessor's .run() method to
  2309. indicate an error in the postprocessing task.
  2310. """
  2311. def __init__(self, msg):
  2312. super(PostProcessingError, self).__init__(msg)
  2313. self.msg = msg
  2314. class MaxDownloadsReached(YoutubeDLError):
  2315. """ --max-downloads limit has been reached. """
  2316. pass
  2317. class UnavailableVideoError(YoutubeDLError):
  2318. """Unavailable Format exception.
  2319. This exception will be thrown when a video is requested
  2320. in a format that is not available for that video.
  2321. """
  2322. pass
  2323. class ContentTooShortError(YoutubeDLError):
  2324. """Content Too Short exception.
  2325. This exception may be raised by FileDownloader objects when a file they
  2326. download is too small for what the server announced first, indicating
  2327. the connection was probably interrupted.
  2328. """
  2329. def __init__(self, downloaded, expected):
  2330. super(ContentTooShortError, self).__init__(
  2331. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2332. )
  2333. # Both in bytes
  2334. self.downloaded = downloaded
  2335. self.expected = expected
  2336. class XAttrMetadataError(YoutubeDLError):
  2337. def __init__(self, code=None, msg='Unknown error'):
  2338. super(XAttrMetadataError, self).__init__(msg)
  2339. self.code = code
  2340. self.msg = msg
  2341. # Parsing code and msg
  2342. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2343. or 'No space left' in self.msg or 'Disk quota exceeded' in self.msg):
  2344. self.reason = 'NO_SPACE'
  2345. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2346. self.reason = 'VALUE_TOO_LONG'
  2347. else:
  2348. self.reason = 'NOT_SUPPORTED'
  2349. class XAttrUnavailableError(YoutubeDLError):
  2350. pass
  2351. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2352. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2353. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2354. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2355. if sys.version_info < (3, 0):
  2356. kwargs['strict'] = True
  2357. hc = http_class(*args, **compat_kwargs(kwargs))
  2358. source_address = ydl_handler._params.get('source_address')
  2359. if source_address is not None:
  2360. # This is to workaround _create_connection() from socket where it will try all
  2361. # address data from getaddrinfo() including IPv6. This filters the result from
  2362. # getaddrinfo() based on the source_address value.
  2363. # This is based on the cpython socket.create_connection() function.
  2364. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2365. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2366. host, port = address
  2367. err = None
  2368. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2369. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2370. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2371. if addrs and not ip_addrs:
  2372. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2373. raise socket.error(
  2374. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2375. % (ip_version, source_address[0]))
  2376. for res in ip_addrs:
  2377. af, socktype, proto, canonname, sa = res
  2378. sock = None
  2379. try:
  2380. sock = socket.socket(af, socktype, proto)
  2381. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2382. sock.settimeout(timeout)
  2383. sock.bind(source_address)
  2384. sock.connect(sa)
  2385. err = None # Explicitly break reference cycle
  2386. return sock
  2387. except socket.error as _:
  2388. err = _
  2389. if sock is not None:
  2390. sock.close()
  2391. if err is not None:
  2392. raise err
  2393. else:
  2394. raise socket.error('getaddrinfo returns an empty list')
  2395. if hasattr(hc, '_create_connection'):
  2396. hc._create_connection = _create_connection
  2397. sa = (source_address, 0)
  2398. if hasattr(hc, 'source_address'): # Python 2.7+
  2399. hc.source_address = sa
  2400. else: # Python 2.6
  2401. def _hc_connect(self, *args, **kwargs):
  2402. sock = _create_connection(
  2403. (self.host, self.port), self.timeout, sa)
  2404. if is_https:
  2405. self.sock = ssl.wrap_socket(
  2406. sock, self.key_file, self.cert_file,
  2407. ssl_version=ssl.PROTOCOL_TLSv1)
  2408. else:
  2409. self.sock = sock
  2410. hc.connect = functools.partial(_hc_connect, hc)
  2411. return hc
  2412. def handle_youtubedl_headers(headers):
  2413. filtered_headers = headers
  2414. if 'Youtubedl-no-compression' in filtered_headers:
  2415. filtered_headers = filter_dict(filtered_headers, cndn=lambda k, _: k.lower() != 'accept-encoding')
  2416. del filtered_headers['Youtubedl-no-compression']
  2417. return filtered_headers
  2418. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2419. """Handler for HTTP requests and responses.
  2420. This class, when installed with an OpenerDirector, automatically adds
  2421. the standard headers to every HTTP request and handles gzipped and
  2422. deflated responses from web servers. If compression is to be avoided in
  2423. a particular request, the original request in the program code only has
  2424. to include the HTTP header "Youtubedl-no-compression", which will be
  2425. removed before making the real request.
  2426. Part of this code was copied from:
  2427. http://techknack.net/python-urllib2-handlers/, archived at
  2428. https://web.archive.org/web/20130527205558/http://techknack.net/python-urllib2-handlers/
  2429. Andrew Rowls, the author of that code, agreed to release it to the
  2430. public domain.
  2431. """
  2432. def __init__(self, params, *args, **kwargs):
  2433. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2434. self._params = params
  2435. def http_open(self, req):
  2436. conn_class = compat_http_client.HTTPConnection
  2437. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2438. if socks_proxy:
  2439. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2440. del req.headers['Ytdl-socks-proxy']
  2441. return self.do_open(functools.partial(
  2442. _create_http_connection, self, conn_class, False),
  2443. req)
  2444. @staticmethod
  2445. def deflate_gz(data):
  2446. try:
  2447. # format:zlib,gzip + windowsize:32768
  2448. return data and zlib.decompress(data, 32 + zlib.MAX_WBITS)
  2449. except zlib.error:
  2450. # raw zlib * windowsize:32768 (RFC 9110: "non-conformant")
  2451. return zlib.decompress(data, -zlib.MAX_WBITS)
  2452. @staticmethod
  2453. def gzip(data):
  2454. from gzip import GzipFile
  2455. def _gzip(data):
  2456. with io.BytesIO(data) as data_buf:
  2457. gz = GzipFile(fileobj=data_buf, mode='rb')
  2458. return gz.read()
  2459. try:
  2460. return _gzip(data)
  2461. except IOError as original_ioerror:
  2462. # There may be junk at the end of the file
  2463. # See http://stackoverflow.com/q/4928560/35070 for details
  2464. for i in range(1, 1024):
  2465. try:
  2466. return _gzip(data[:-i])
  2467. except IOError:
  2468. continue
  2469. else:
  2470. raise original_ioerror
  2471. @staticmethod
  2472. def brotli(data):
  2473. return data and brotli.decompress(data)
  2474. @staticmethod
  2475. def compress(data):
  2476. return data and ncompress.decompress(data)
  2477. @staticmethod
  2478. def _fix_path(url):
  2479. # an embedded /../ or /./ sequence is not automatically handled by urllib2
  2480. # see https://github.com/yt-dlp/yt-dlp/issues/3355
  2481. parsed_url = compat_urllib_parse.urlsplit(url)
  2482. path = parsed_url.path
  2483. if not path.endswith('/'):
  2484. path += '/'
  2485. parts = path.partition('/./')
  2486. if not parts[1]:
  2487. parts = path.partition('/../')
  2488. if parts[1]:
  2489. path = compat_urllib_parse.urljoin(
  2490. parts[0] + parts[1][:1],
  2491. parts[1][1:] + (parts[2] if parsed_url.path.endswith('/') else parts[2][:-1]))
  2492. url = parsed_url._replace(path=path).geturl()
  2493. if '/.' in url:
  2494. # worse, URL path may have initial /../ against RFCs: work-around
  2495. # by stripping such prefixes, like eg Firefox
  2496. path = parsed_url.path + '/'
  2497. while path.startswith('/.'):
  2498. if path.startswith('/../'):
  2499. path = path[3:]
  2500. elif path.startswith('/./'):
  2501. path = path[2:]
  2502. else:
  2503. break
  2504. path = path[:-1]
  2505. if not path.startswith('/') and parsed_url.path.startswith('/'):
  2506. path = '/' + path
  2507. url = parsed_url._replace(path=path).geturl()
  2508. return url
  2509. def http_request(self, req):
  2510. url = req.get_full_url()
  2511. # resolve embedded . and ..
  2512. url_fixed = self._fix_path(url)
  2513. # According to RFC 3986, URLs can not contain non-ASCII characters; however this is not
  2514. # always respected by websites: some tend to give out URLs with non percent-encoded
  2515. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2516. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2517. # To work around aforementioned issue we will replace request's original URL with
  2518. # percent-encoded one
  2519. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2520. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2521. url_escaped = escape_url(url_fixed)
  2522. # Substitute URL if any change after escaping
  2523. if url != url_escaped:
  2524. req = update_Request(req, url=url_escaped)
  2525. for h, v in std_headers.items():
  2526. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2527. # The dict keys are capitalized because of this bug by urllib
  2528. if h.capitalize() not in req.headers:
  2529. req.add_header(h, v)
  2530. # Similarly, 'Accept-encoding'
  2531. if 'Accept-encoding' not in req.headers:
  2532. req.add_header(
  2533. 'Accept-Encoding', join_nonempty(
  2534. 'gzip', 'deflate', brotli and 'br', ncompress and 'compress',
  2535. delim=', '))
  2536. req.headers = handle_youtubedl_headers(req.headers)
  2537. if sys.version_info < (2, 7):
  2538. # avoid possible race where __r_type may be unset
  2539. req.get_type()
  2540. if '#' in req.get_full_url():
  2541. # Python 2.6 is brain-dead when it comes to fragments
  2542. req._Request__original = req._Request__original.partition('#')[0]
  2543. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2544. # Use the totally undocumented AbstractHTTPHandler per
  2545. # https://github.com/yt-dlp/yt-dlp/pull/4158
  2546. return compat_urllib_request.AbstractHTTPHandler.do_request_(self, req)
  2547. def http_response(self, req, resp):
  2548. old_resp = resp
  2549. # Content-Encoding header lists the encodings in order that they were applied [1].
  2550. # To decompress, we simply do the reverse.
  2551. # [1]: https://datatracker.ietf.org/doc/html/rfc9110#name-content-encoding
  2552. decoded_response = None
  2553. decoders = {
  2554. 'gzip': self.deflate_gz,
  2555. 'deflate': self.deflate_gz,
  2556. }
  2557. if brotli:
  2558. decoders['br'] = self.brotli
  2559. if ncompress:
  2560. decoders['compress'] = self.compress
  2561. if sys.platform.startswith('java'):
  2562. # Jython zlib implementation misses gzip
  2563. decoders['gzip'] = self.gzip
  2564. def encodings(hdrs):
  2565. # A header field that allows multiple values can have multiple instances [2].
  2566. # [2]: https://datatracker.ietf.org/doc/html/rfc9110#name-fields
  2567. for e in reversed(','.join(hdrs).split(',')):
  2568. if e:
  2569. yield e.strip()
  2570. encodings_left = []
  2571. try:
  2572. resp.headers.get_all
  2573. hdrs = resp.headers
  2574. except AttributeError:
  2575. # Py2 has no get_all() method: headers are rfc822.Message
  2576. from email.message import Message
  2577. hdrs = Message()
  2578. for k, v in resp.headers.items():
  2579. hdrs[k] = v
  2580. decoder, decoded_response = True, None
  2581. for encoding in encodings(hdrs.get_all('Content-Encoding', [])):
  2582. # "SHOULD consider" x-compress, x-gzip as compress, gzip
  2583. decoder = decoder and decoders.get(remove_start(encoding, 'x-'))
  2584. if not decoder:
  2585. encodings_left.insert(0, encoding)
  2586. continue
  2587. decoded_response = decoder(decoded_response or resp.read())
  2588. if decoded_response is not None:
  2589. resp = compat_urllib_request.addinfourl(
  2590. io.BytesIO(decoded_response), old_resp.headers, old_resp.url, old_resp.code)
  2591. resp.msg = old_resp.msg
  2592. del resp.headers['Content-Length']
  2593. resp.headers['Content-Length'] = '%d' % len(decoded_response)
  2594. del resp.headers['Content-Encoding']
  2595. if encodings_left:
  2596. resp.headers['Content-Encoding'] = ', '.join(encodings_left)
  2597. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2598. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2599. if 300 <= resp.code < 400:
  2600. location = resp.headers.get('Location')
  2601. if location:
  2602. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2603. if sys.version_info >= (3, 0):
  2604. location = location.encode('iso-8859-1')
  2605. location = location.decode('utf-8')
  2606. # resolve embedded . and ..
  2607. location_fixed = self._fix_path(location)
  2608. location_escaped = escape_url(location_fixed)
  2609. if location != location_escaped:
  2610. del resp.headers['Location']
  2611. if not isinstance(location_escaped, str): # Py 2 case
  2612. location_escaped = location_escaped.encode('utf-8')
  2613. resp.headers['Location'] = location_escaped
  2614. return resp
  2615. https_request = http_request
  2616. https_response = http_response
  2617. def make_socks_conn_class(base_class, socks_proxy):
  2618. assert issubclass(base_class, (
  2619. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2620. url_components = compat_urllib_parse.urlparse(socks_proxy)
  2621. if url_components.scheme.lower() == 'socks5':
  2622. socks_type = ProxyType.SOCKS5
  2623. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2624. socks_type = ProxyType.SOCKS4
  2625. elif url_components.scheme.lower() == 'socks4a':
  2626. socks_type = ProxyType.SOCKS4A
  2627. def unquote_if_non_empty(s):
  2628. if not s:
  2629. return s
  2630. return compat_urllib_parse_unquote_plus(s)
  2631. proxy_args = (
  2632. socks_type,
  2633. url_components.hostname, url_components.port or 1080,
  2634. True, # Remote DNS
  2635. unquote_if_non_empty(url_components.username),
  2636. unquote_if_non_empty(url_components.password),
  2637. )
  2638. class SocksConnection(base_class):
  2639. def connect(self):
  2640. self.sock = sockssocket()
  2641. self.sock.setproxy(*proxy_args)
  2642. if type(self.timeout) in (int, float):
  2643. self.sock.settimeout(self.timeout)
  2644. self.sock.connect((self.host, self.port))
  2645. if isinstance(self, compat_http_client.HTTPSConnection):
  2646. if hasattr(self, '_context'): # Python > 2.6
  2647. self.sock = self._context.wrap_socket(
  2648. self.sock, server_hostname=self.host)
  2649. else:
  2650. self.sock = ssl.wrap_socket(self.sock)
  2651. return SocksConnection
  2652. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2653. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2654. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2655. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2656. self._params = params
  2657. def https_open(self, req):
  2658. kwargs = {}
  2659. conn_class = self._https_conn_class
  2660. if hasattr(self, '_context'): # python > 2.6
  2661. kwargs['context'] = self._context
  2662. if hasattr(self, '_check_hostname'): # python 3.x
  2663. kwargs['check_hostname'] = self._check_hostname
  2664. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2665. if socks_proxy:
  2666. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2667. del req.headers['Ytdl-socks-proxy']
  2668. return self.do_open(functools.partial(
  2669. _create_http_connection, self, conn_class, True),
  2670. req, **kwargs)
  2671. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2672. """
  2673. See [1] for cookie file format.
  2674. 1. https://curl.haxx.se/docs/http-cookies.html
  2675. """
  2676. _HTTPONLY_PREFIX = '#HttpOnly_'
  2677. _ENTRY_LEN = 7
  2678. _HEADER = '''# Netscape HTTP Cookie File
  2679. # This file is generated by youtube-dl. Do not edit.
  2680. '''
  2681. _CookieFileEntry = collections.namedtuple(
  2682. 'CookieFileEntry',
  2683. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  2684. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2685. """
  2686. Save cookies to a file.
  2687. Most of the code is taken from CPython 3.8 and slightly adapted
  2688. to support cookie files with UTF-8 in both python 2 and 3.
  2689. """
  2690. if filename is None:
  2691. if self.filename is not None:
  2692. filename = self.filename
  2693. else:
  2694. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2695. # Store session cookies with `expires` set to 0 instead of an empty
  2696. # string
  2697. for cookie in self:
  2698. if cookie.expires is None:
  2699. cookie.expires = 0
  2700. with io.open(filename, 'w', encoding='utf-8') as f:
  2701. f.write(self._HEADER)
  2702. now = time.time()
  2703. for cookie in self:
  2704. if not ignore_discard and cookie.discard:
  2705. continue
  2706. if not ignore_expires and cookie.is_expired(now):
  2707. continue
  2708. if cookie.secure:
  2709. secure = 'TRUE'
  2710. else:
  2711. secure = 'FALSE'
  2712. if cookie.domain.startswith('.'):
  2713. initial_dot = 'TRUE'
  2714. else:
  2715. initial_dot = 'FALSE'
  2716. if cookie.expires is not None:
  2717. expires = compat_str(cookie.expires)
  2718. else:
  2719. expires = ''
  2720. if cookie.value is None:
  2721. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  2722. # with no name, whereas http.cookiejar regards it as a
  2723. # cookie with no value.
  2724. name = ''
  2725. value = cookie.name
  2726. else:
  2727. name = cookie.name
  2728. value = cookie.value
  2729. f.write(
  2730. '\t'.join([cookie.domain, initial_dot, cookie.path,
  2731. secure, expires, name, value]) + '\n')
  2732. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2733. """Load cookies from a file."""
  2734. if filename is None:
  2735. if self.filename is not None:
  2736. filename = self.filename
  2737. else:
  2738. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2739. def prepare_line(line):
  2740. if line.startswith(self._HTTPONLY_PREFIX):
  2741. line = line[len(self._HTTPONLY_PREFIX):]
  2742. # comments and empty lines are fine
  2743. if line.startswith('#') or not line.strip():
  2744. return line
  2745. cookie_list = line.split('\t')
  2746. if len(cookie_list) != self._ENTRY_LEN:
  2747. raise compat_cookiejar.LoadError('invalid length %d' % len(cookie_list))
  2748. cookie = self._CookieFileEntry(*cookie_list)
  2749. if cookie.expires_at and not cookie.expires_at.isdigit():
  2750. raise compat_cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
  2751. return line
  2752. cf = io.StringIO()
  2753. with io.open(filename, encoding='utf-8') as f:
  2754. for line in f:
  2755. try:
  2756. cf.write(prepare_line(line))
  2757. except compat_cookiejar.LoadError as e:
  2758. write_string(
  2759. 'WARNING: skipping cookie file entry due to %s: %r\n'
  2760. % (e, line), sys.stderr)
  2761. continue
  2762. cf.seek(0)
  2763. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2764. # Session cookies are denoted by either `expires` field set to
  2765. # an empty string or 0. MozillaCookieJar only recognizes the former
  2766. # (see [1]). So we need force the latter to be recognized as session
  2767. # cookies on our own.
  2768. # Session cookies may be important for cookies-based authentication,
  2769. # e.g. usually, when user does not check 'Remember me' check box while
  2770. # logging in on a site, some important cookies are stored as session
  2771. # cookies so that not recognizing them will result in failed login.
  2772. # 1. https://bugs.python.org/issue17164
  2773. for cookie in self:
  2774. # Treat `expires=0` cookies as session cookies
  2775. if cookie.expires == 0:
  2776. cookie.expires = None
  2777. cookie.discard = True
  2778. def get_cookie_header(self, url):
  2779. """Generate a Cookie HTTP header for a given url"""
  2780. cookie_req = sanitized_Request(url)
  2781. self.add_cookie_header(cookie_req)
  2782. return cookie_req.get_header('Cookie')
  2783. def get_cookies_for_url(self, url):
  2784. """Generate a list of Cookie objects for a given url"""
  2785. # Policy `_now` attribute must be set before calling `_cookies_for_request`
  2786. # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360
  2787. self._policy._now = self._now = int(time.time())
  2788. return self._cookies_for_request(sanitized_Request(url))
  2789. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2790. def __init__(self, cookiejar=None):
  2791. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2792. def http_response(self, request, response):
  2793. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2794. # characters in Set-Cookie HTTP header of last response (see
  2795. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2796. # In order to at least prevent crashing we will percent encode Set-Cookie
  2797. # header before HTTPCookieProcessor starts processing it.
  2798. # if sys.version_info < (3, 0) and response.headers:
  2799. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2800. # set_cookie = response.headers.get(set_cookie_header)
  2801. # if set_cookie:
  2802. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2803. # if set_cookie != set_cookie_escaped:
  2804. # del response.headers[set_cookie_header]
  2805. # response.headers[set_cookie_header] = set_cookie_escaped
  2806. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2807. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2808. https_response = http_response
  2809. class YoutubeDLRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  2810. """YoutubeDL redirect handler
  2811. The code is based on HTTPRedirectHandler implementation from CPython [1].
  2812. This redirect handler fixes and improves the logic to better align with RFC7261
  2813. and what browsers tend to do [2][3]
  2814. 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
  2815. 2. https://datatracker.ietf.org/doc/html/rfc7231
  2816. 3. https://github.com/python/cpython/issues/91306
  2817. """
  2818. # Supply possibly missing alias
  2819. http_error_308 = compat_urllib_request.HTTPRedirectHandler.http_error_302
  2820. def redirect_request(self, req, fp, code, msg, headers, newurl):
  2821. """Return a Request or None in response to a redirect.
  2822. This is called by the http_error_30x methods when a
  2823. redirection response is received. If a redirection should
  2824. take place, return a new Request to allow http_error_30x to
  2825. perform the redirect. Otherwise, raise HTTPError if no-one
  2826. else should try to handle this url. Return None if you can't
  2827. but another Handler might.
  2828. """
  2829. if code not in (301, 302, 303, 307, 308):
  2830. raise compat_urllib_HTTPError(req.full_url, code, msg, headers, fp)
  2831. new_method = req.get_method()
  2832. new_data = req.data
  2833. # On python 2 urlh.geturl() may sometimes return redirect URL
  2834. # as a byte string instead of unicode. This workaround forces
  2835. # it to return unicode.
  2836. newurl = _decode_compat_str(newurl)
  2837. # Be conciliant with URIs containing a space. This is mainly
  2838. # redundant with the more complete encoding done in http_error_302(),
  2839. # but it is kept for compatibility with other callers.
  2840. newurl = newurl.replace(' ', '%20')
  2841. # Technically the Cookie header should be in unredirected_hdrs;
  2842. # however in practice some may set it in normal headers anyway.
  2843. # We will remove it here to prevent any leaks.
  2844. remove_headers = ['Cookie']
  2845. # A 303 must either use GET or HEAD for subsequent request
  2846. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.4
  2847. if code == 303 and req.get_method() != 'HEAD':
  2848. new_method = 'GET'
  2849. # 301 and 302 redirects are commonly turned into a GET from a POST
  2850. # for subsequent requests by browsers, so we'll do the same.
  2851. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.2
  2852. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.3
  2853. elif code in (301, 302) and req.get_method() == 'POST':
  2854. new_method = 'GET'
  2855. # only remove payload if method changed (e.g. POST to GET)
  2856. if new_method != req.get_method():
  2857. new_data = None
  2858. remove_headers.extend(['Content-Length', 'Content-Type'])
  2859. new_headers = filter_dict(req.headers, cndn=lambda k, _: k.title() not in remove_headers)
  2860. return compat_urllib_request.Request(
  2861. newurl, headers=new_headers, origin_req_host=req.origin_req_host,
  2862. unverifiable=True, method=new_method, data=new_data)
  2863. def extract_timezone(date_str):
  2864. m = re.search(
  2865. r'''(?x)
  2866. ^.{8,}? # >=8 char non-TZ prefix, if present
  2867. (?P<tz>Z| # just the UTC Z, or
  2868. (?:(?<=.\b\d{4}|\b\d{2}:\d\d)| # preceded by 4 digits or hh:mm or
  2869. (?<!.\b[a-zA-Z]{3}|[a-zA-Z]{4}|..\b\d\d)) # not preceded by 3 alpha word or >= 4 alpha or 2 digits
  2870. [ ]? # optional space
  2871. (?P<sign>\+|-) # +/-
  2872. (?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2}) # hh[:]mm
  2873. $)
  2874. ''', date_str)
  2875. if not m:
  2876. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2877. timezone = TIMEZONE_NAMES.get(m and m.group('tz').strip())
  2878. if timezone is not None:
  2879. date_str = date_str[:-len(m.group('tz'))]
  2880. timezone = datetime.timedelta(hours=timezone or 0)
  2881. else:
  2882. date_str = date_str[:-len(m.group('tz'))]
  2883. if not m.group('sign'):
  2884. timezone = datetime.timedelta()
  2885. else:
  2886. sign = 1 if m.group('sign') == '+' else -1
  2887. timezone = datetime.timedelta(
  2888. hours=sign * int(m.group('hours')),
  2889. minutes=sign * int(m.group('minutes')))
  2890. return timezone, date_str
  2891. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2892. """ Return a UNIX timestamp from the given date """
  2893. if date_str is None:
  2894. return None
  2895. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2896. if timezone is None:
  2897. timezone, date_str = extract_timezone(date_str)
  2898. with compat_contextlib_suppress(ValueError):
  2899. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2900. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2901. return calendar.timegm(dt.timetuple())
  2902. def date_formats(day_first=True):
  2903. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2904. def unified_strdate(date_str, day_first=True):
  2905. """Return a string with the date in the format YYYYMMDD"""
  2906. if date_str is None:
  2907. return None
  2908. upload_date = None
  2909. # Replace commas
  2910. date_str = date_str.replace(',', ' ')
  2911. # Remove AM/PM + timezone
  2912. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2913. _, date_str = extract_timezone(date_str)
  2914. for expression in date_formats(day_first):
  2915. with compat_contextlib_suppress(ValueError):
  2916. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2917. if upload_date is None:
  2918. timetuple = email.utils.parsedate_tz(date_str)
  2919. if timetuple:
  2920. with compat_contextlib_suppress(ValueError):
  2921. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2922. if upload_date is not None:
  2923. return compat_str(upload_date)
  2924. def unified_timestamp(date_str, day_first=True):
  2925. if date_str is None:
  2926. return None
  2927. date_str = re.sub(r'\s+', ' ', re.sub(
  2928. r'(?i)[,|]|(mon|tues?|wed(nes)?|thu(rs)?|fri|sat(ur)?)(day)?', '', date_str))
  2929. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2930. timezone, date_str = extract_timezone(date_str)
  2931. # Remove AM/PM + timezone
  2932. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2933. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2934. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2935. if m:
  2936. date_str = date_str[:-len(m.group('tz'))]
  2937. # Python only supports microseconds, so remove nanoseconds
  2938. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  2939. if m:
  2940. date_str = m.group(1)
  2941. for expression in date_formats(day_first):
  2942. with compat_contextlib_suppress(ValueError):
  2943. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2944. return calendar.timegm(dt.timetuple())
  2945. timetuple = email.utils.parsedate_tz(date_str)
  2946. if timetuple:
  2947. return calendar.timegm(timetuple) + pm_delta * 3600 - compat_datetime_timedelta_total_seconds(timezone)
  2948. def determine_ext(url, default_ext='unknown_video'):
  2949. if url is None or '.' not in url:
  2950. return default_ext
  2951. guess = url.partition('?')[0].rpartition('.')[2]
  2952. if re.match(r'^[A-Za-z0-9]+$', guess):
  2953. return guess
  2954. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2955. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2956. return guess.rstrip('/')
  2957. else:
  2958. return default_ext
  2959. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2960. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2961. def date_from_str(date_str):
  2962. """
  2963. Return a datetime object from a string in the format YYYYMMDD or
  2964. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2965. today = datetime.date.today()
  2966. if date_str in ('now', 'today'):
  2967. return today
  2968. if date_str == 'yesterday':
  2969. return today - datetime.timedelta(days=1)
  2970. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2971. if match is not None:
  2972. sign = match.group('sign')
  2973. time = int(match.group('time'))
  2974. if sign == '-':
  2975. time = -time
  2976. unit = match.group('unit')
  2977. # A bad approximation?
  2978. if unit == 'month':
  2979. unit = 'day'
  2980. time *= 30
  2981. elif unit == 'year':
  2982. unit = 'day'
  2983. time *= 365
  2984. unit += 's'
  2985. delta = datetime.timedelta(**{unit: time})
  2986. return today + delta
  2987. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2988. def hyphenate_date(date_str):
  2989. """
  2990. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  2991. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  2992. if match is not None:
  2993. return '-'.join(match.groups())
  2994. else:
  2995. return date_str
  2996. class DateRange(object):
  2997. """Represents a time interval between two dates"""
  2998. def __init__(self, start=None, end=None):
  2999. """start and end must be strings in the format accepted by date"""
  3000. if start is not None:
  3001. self.start = date_from_str(start)
  3002. else:
  3003. self.start = datetime.datetime.min.date()
  3004. if end is not None:
  3005. self.end = date_from_str(end)
  3006. else:
  3007. self.end = datetime.datetime.max.date()
  3008. if self.start > self.end:
  3009. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  3010. @classmethod
  3011. def day(cls, day):
  3012. """Returns a range that only contains the given day"""
  3013. return cls(day, day)
  3014. def __contains__(self, date):
  3015. """Check if the date is in the range"""
  3016. if not isinstance(date, datetime.date):
  3017. date = date_from_str(date)
  3018. return self.start <= date <= self.end
  3019. def __str__(self):
  3020. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  3021. def __eq__(self, other):
  3022. return (isinstance(other, DateRange)
  3023. and self.start == other.start and self.end == other.end)
  3024. def platform_name():
  3025. """ Returns the platform name as a compat_str """
  3026. res = platform.platform()
  3027. return _decode_compat_str(res)
  3028. def _windows_write_string(s, out):
  3029. """ Returns True if the string was written using special methods,
  3030. False if it has yet to be written out."""
  3031. # Adapted from http://stackoverflow.com/a/3259271/35070
  3032. import ctypes
  3033. import ctypes.wintypes
  3034. WIN_OUTPUT_IDS = {
  3035. 1: -11,
  3036. 2: -12,
  3037. }
  3038. try:
  3039. fileno = out.fileno()
  3040. except AttributeError:
  3041. # If the output stream doesn't have a fileno, it's virtual
  3042. return False
  3043. except io.UnsupportedOperation:
  3044. # Some strange Windows pseudo files?
  3045. return False
  3046. if fileno not in WIN_OUTPUT_IDS:
  3047. return False
  3048. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  3049. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  3050. ('GetStdHandle', ctypes.windll.kernel32))
  3051. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  3052. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  3053. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  3054. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  3055. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  3056. written = ctypes.wintypes.DWORD(0)
  3057. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  3058. FILE_TYPE_CHAR = 0x0002
  3059. FILE_TYPE_REMOTE = 0x8000
  3060. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  3061. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  3062. ctypes.POINTER(ctypes.wintypes.DWORD))(
  3063. ('GetConsoleMode', ctypes.windll.kernel32))
  3064. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  3065. def not_a_console(handle):
  3066. if handle == INVALID_HANDLE_VALUE or handle is None:
  3067. return True
  3068. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  3069. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  3070. if not_a_console(h):
  3071. return False
  3072. def next_nonbmp_pos(s):
  3073. try:
  3074. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  3075. except StopIteration:
  3076. return len(s)
  3077. while s:
  3078. count = min(next_nonbmp_pos(s), 1024)
  3079. ret = WriteConsoleW(
  3080. h, s, count if count else 2, ctypes.byref(written), None)
  3081. if ret == 0:
  3082. raise OSError('Failed to write string')
  3083. if not count: # We just wrote a non-BMP character
  3084. assert written.value == 2
  3085. s = s[1:]
  3086. else:
  3087. assert written.value > 0
  3088. s = s[written.value:]
  3089. return True
  3090. def write_string(s, out=None, encoding=None):
  3091. if out is None:
  3092. out = sys.stderr
  3093. assert isinstance(s, compat_str)
  3094. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  3095. if _windows_write_string(s, out):
  3096. return
  3097. if ('b' in getattr(out, 'mode', '')
  3098. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  3099. byt = s.encode(encoding or preferredencoding(), 'ignore')
  3100. out.write(byt)
  3101. elif hasattr(out, 'buffer'):
  3102. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  3103. byt = s.encode(enc, 'ignore')
  3104. out.buffer.write(byt)
  3105. else:
  3106. out.write(s)
  3107. out.flush()
  3108. def bytes_to_intlist(bs):
  3109. if not bs:
  3110. return []
  3111. if isinstance(bs[0], int): # Python 3
  3112. return list(bs)
  3113. else:
  3114. return [ord(c) for c in bs]
  3115. def intlist_to_bytes(xs):
  3116. if not xs:
  3117. return b''
  3118. return compat_struct_pack('%dB' % len(xs), *xs)
  3119. # Cross-platform file locking
  3120. if sys.platform == 'win32':
  3121. import ctypes.wintypes
  3122. import msvcrt
  3123. class OVERLAPPED(ctypes.Structure):
  3124. _fields_ = [
  3125. ('Internal', ctypes.wintypes.LPVOID),
  3126. ('InternalHigh', ctypes.wintypes.LPVOID),
  3127. ('Offset', ctypes.wintypes.DWORD),
  3128. ('OffsetHigh', ctypes.wintypes.DWORD),
  3129. ('hEvent', ctypes.wintypes.HANDLE),
  3130. ]
  3131. kernel32 = ctypes.windll.kernel32
  3132. LockFileEx = kernel32.LockFileEx
  3133. LockFileEx.argtypes = [
  3134. ctypes.wintypes.HANDLE, # hFile
  3135. ctypes.wintypes.DWORD, # dwFlags
  3136. ctypes.wintypes.DWORD, # dwReserved
  3137. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  3138. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  3139. ctypes.POINTER(OVERLAPPED) # Overlapped
  3140. ]
  3141. LockFileEx.restype = ctypes.wintypes.BOOL
  3142. UnlockFileEx = kernel32.UnlockFileEx
  3143. UnlockFileEx.argtypes = [
  3144. ctypes.wintypes.HANDLE, # hFile
  3145. ctypes.wintypes.DWORD, # dwReserved
  3146. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  3147. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  3148. ctypes.POINTER(OVERLAPPED) # Overlapped
  3149. ]
  3150. UnlockFileEx.restype = ctypes.wintypes.BOOL
  3151. whole_low = 0xffffffff
  3152. whole_high = 0x7fffffff
  3153. def _lock_file(f, exclusive):
  3154. overlapped = OVERLAPPED()
  3155. overlapped.Offset = 0
  3156. overlapped.OffsetHigh = 0
  3157. overlapped.hEvent = 0
  3158. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  3159. handle = msvcrt.get_osfhandle(f.fileno())
  3160. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  3161. whole_low, whole_high, f._lock_file_overlapped_p):
  3162. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  3163. def _unlock_file(f):
  3164. assert f._lock_file_overlapped_p
  3165. handle = msvcrt.get_osfhandle(f.fileno())
  3166. if not UnlockFileEx(handle, 0,
  3167. whole_low, whole_high, f._lock_file_overlapped_p):
  3168. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  3169. else:
  3170. # Some platforms, such as Jython, is missing fcntl
  3171. try:
  3172. import fcntl
  3173. def _lock_file(f, exclusive):
  3174. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  3175. def _unlock_file(f):
  3176. fcntl.flock(f, fcntl.LOCK_UN)
  3177. except ImportError:
  3178. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  3179. def _lock_file(f, exclusive):
  3180. raise IOError(UNSUPPORTED_MSG)
  3181. def _unlock_file(f):
  3182. raise IOError(UNSUPPORTED_MSG)
  3183. class locked_file(object):
  3184. def __init__(self, filename, mode, encoding=None):
  3185. assert mode in ['r', 'a', 'w']
  3186. self.f = io.open(filename, mode, encoding=encoding)
  3187. self.mode = mode
  3188. def __enter__(self):
  3189. exclusive = self.mode != 'r'
  3190. try:
  3191. _lock_file(self.f, exclusive)
  3192. except IOError:
  3193. self.f.close()
  3194. raise
  3195. return self
  3196. def __exit__(self, etype, value, traceback):
  3197. try:
  3198. _unlock_file(self.f)
  3199. finally:
  3200. self.f.close()
  3201. def __iter__(self):
  3202. return iter(self.f)
  3203. def write(self, *args):
  3204. return self.f.write(*args)
  3205. def read(self, *args):
  3206. return self.f.read(*args)
  3207. def get_filesystem_encoding():
  3208. encoding = sys.getfilesystemencoding()
  3209. return encoding if encoding is not None else 'utf-8'
  3210. def shell_quote(args):
  3211. quoted_args = []
  3212. encoding = get_filesystem_encoding()
  3213. for a in args:
  3214. # We may get a filename encoded with 'encodeFilename'
  3215. a = _decode_compat_str(a, encoding)
  3216. quoted_args.append(compat_shlex_quote(a))
  3217. return ' '.join(quoted_args)
  3218. def smuggle_url(url, data):
  3219. """ Pass additional data in a URL for internal use. """
  3220. url, idata = unsmuggle_url(url, {})
  3221. data.update(idata)
  3222. sdata = compat_urllib_parse_urlencode(
  3223. {'__youtubedl_smuggle': json.dumps(data)})
  3224. return url + '#' + sdata
  3225. def unsmuggle_url(smug_url, default=None):
  3226. if '#__youtubedl_smuggle' not in smug_url:
  3227. return smug_url, default
  3228. url, _, sdata = smug_url.rpartition('#')
  3229. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  3230. data = json.loads(jsond)
  3231. return url, data
  3232. def format_bytes(bytes):
  3233. if bytes is None:
  3234. return 'N/A'
  3235. if type(bytes) is str:
  3236. bytes = float(bytes)
  3237. if bytes == 0.0:
  3238. exponent = 0
  3239. else:
  3240. exponent = int(math.log(bytes, 1024.0))
  3241. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  3242. converted = float(bytes) / float(1024 ** exponent)
  3243. return '%.2f%s' % (converted, suffix)
  3244. def lookup_unit_table(unit_table, s):
  3245. units_re = '|'.join(re.escape(u) for u in unit_table)
  3246. m = re.match(
  3247. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  3248. if not m:
  3249. return None
  3250. num_str = m.group('num').replace(',', '.')
  3251. mult = unit_table[m.group('unit')]
  3252. return int(float(num_str) * mult)
  3253. def parse_filesize(s):
  3254. if s is None:
  3255. return None
  3256. # The lower-case forms are of course incorrect and unofficial,
  3257. # but we support those too
  3258. _UNIT_TABLE = {
  3259. 'B': 1,
  3260. 'b': 1,
  3261. 'bytes': 1,
  3262. 'KiB': 1024,
  3263. 'KB': 1000,
  3264. 'kB': 1024,
  3265. 'Kb': 1000,
  3266. 'kb': 1000,
  3267. 'kilobytes': 1000,
  3268. 'kibibytes': 1024,
  3269. 'MiB': 1024 ** 2,
  3270. 'MB': 1000 ** 2,
  3271. 'mB': 1024 ** 2,
  3272. 'Mb': 1000 ** 2,
  3273. 'mb': 1000 ** 2,
  3274. 'megabytes': 1000 ** 2,
  3275. 'mebibytes': 1024 ** 2,
  3276. 'GiB': 1024 ** 3,
  3277. 'GB': 1000 ** 3,
  3278. 'gB': 1024 ** 3,
  3279. 'Gb': 1000 ** 3,
  3280. 'gb': 1000 ** 3,
  3281. 'gigabytes': 1000 ** 3,
  3282. 'gibibytes': 1024 ** 3,
  3283. 'TiB': 1024 ** 4,
  3284. 'TB': 1000 ** 4,
  3285. 'tB': 1024 ** 4,
  3286. 'Tb': 1000 ** 4,
  3287. 'tb': 1000 ** 4,
  3288. 'terabytes': 1000 ** 4,
  3289. 'tebibytes': 1024 ** 4,
  3290. 'PiB': 1024 ** 5,
  3291. 'PB': 1000 ** 5,
  3292. 'pB': 1024 ** 5,
  3293. 'Pb': 1000 ** 5,
  3294. 'pb': 1000 ** 5,
  3295. 'petabytes': 1000 ** 5,
  3296. 'pebibytes': 1024 ** 5,
  3297. 'EiB': 1024 ** 6,
  3298. 'EB': 1000 ** 6,
  3299. 'eB': 1024 ** 6,
  3300. 'Eb': 1000 ** 6,
  3301. 'eb': 1000 ** 6,
  3302. 'exabytes': 1000 ** 6,
  3303. 'exbibytes': 1024 ** 6,
  3304. 'ZiB': 1024 ** 7,
  3305. 'ZB': 1000 ** 7,
  3306. 'zB': 1024 ** 7,
  3307. 'Zb': 1000 ** 7,
  3308. 'zb': 1000 ** 7,
  3309. 'zettabytes': 1000 ** 7,
  3310. 'zebibytes': 1024 ** 7,
  3311. 'YiB': 1024 ** 8,
  3312. 'YB': 1000 ** 8,
  3313. 'yB': 1024 ** 8,
  3314. 'Yb': 1000 ** 8,
  3315. 'yb': 1000 ** 8,
  3316. 'yottabytes': 1000 ** 8,
  3317. 'yobibytes': 1024 ** 8,
  3318. }
  3319. return lookup_unit_table(_UNIT_TABLE, s)
  3320. def parse_count(s):
  3321. if s is None:
  3322. return None
  3323. s = s.strip()
  3324. if re.match(r'^[\d,.]+$', s):
  3325. return str_to_int(s)
  3326. _UNIT_TABLE = {
  3327. 'k': 1000,
  3328. 'K': 1000,
  3329. 'm': 1000 ** 2,
  3330. 'M': 1000 ** 2,
  3331. 'kk': 1000 ** 2,
  3332. 'KK': 1000 ** 2,
  3333. }
  3334. return lookup_unit_table(_UNIT_TABLE, s)
  3335. def parse_resolution(s):
  3336. if s is None:
  3337. return {}
  3338. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3339. if mobj:
  3340. return {
  3341. 'width': int(mobj.group('w')),
  3342. 'height': int(mobj.group('h')),
  3343. }
  3344. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3345. if mobj:
  3346. return {'height': int(mobj.group(1))}
  3347. mobj = re.search(r'\b([48])[kK]\b', s)
  3348. if mobj:
  3349. return {'height': int(mobj.group(1)) * 540}
  3350. return {}
  3351. def parse_bitrate(s):
  3352. s = txt_or_none(s)
  3353. if not s:
  3354. return None
  3355. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3356. if mobj:
  3357. return int(mobj.group(1))
  3358. def month_by_name(name, lang='en'):
  3359. """ Return the number of a month by (locale-independently) English name """
  3360. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3361. try:
  3362. return month_names.index(name) + 1
  3363. except ValueError:
  3364. return None
  3365. def month_by_abbreviation(abbrev):
  3366. """ Return the number of a month by (locale-independently) English
  3367. abbreviations """
  3368. try:
  3369. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3370. except ValueError:
  3371. return None
  3372. def fix_xml_ampersands(xml_str):
  3373. """Replace all the '&' by '&amp;' in XML"""
  3374. return re.sub(
  3375. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3376. '&amp;',
  3377. xml_str)
  3378. def setproctitle(title):
  3379. assert isinstance(title, compat_str)
  3380. # ctypes in Jython is not complete
  3381. # http://bugs.jython.org/issue2148
  3382. if sys.platform.startswith('java'):
  3383. return
  3384. try:
  3385. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3386. except OSError:
  3387. return
  3388. except TypeError:
  3389. # LoadLibrary in Windows Python 2.7.13 only expects
  3390. # a bytestring, but since unicode_literals turns
  3391. # every string into a unicode string, it fails.
  3392. return
  3393. title_bytes = title.encode('utf-8')
  3394. buf = ctypes.create_string_buffer(len(title_bytes))
  3395. buf.value = title_bytes
  3396. try:
  3397. libc.prctl(15, buf, 0, 0, 0)
  3398. except AttributeError:
  3399. return # Strange libc, just skip this
  3400. def remove_start(s, start):
  3401. return s[len(start):] if s is not None and s.startswith(start) else s
  3402. def remove_end(s, end):
  3403. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3404. def remove_quotes(s):
  3405. if s is None or len(s) < 2:
  3406. return s
  3407. for quote in ('"', "'", ):
  3408. if s[0] == quote and s[-1] == quote:
  3409. return s[1:-1]
  3410. return s
  3411. def url_basename(url):
  3412. path = compat_urllib_parse.urlparse(url).path
  3413. return path.strip('/').split('/')[-1]
  3414. def base_url(url):
  3415. return re.match(r'https?://[^?#&]+/', url).group()
  3416. def urljoin(base, path):
  3417. path = _decode_compat_str(path, encoding='utf-8', or_none=True)
  3418. if not path:
  3419. return None
  3420. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3421. return path
  3422. base = _decode_compat_str(base, encoding='utf-8', or_none=True)
  3423. if not base:
  3424. return None
  3425. return (
  3426. re.match(r'^(?:https?:)?//', base)
  3427. and compat_urllib_parse.urljoin(base, path))
  3428. class HEADRequest(compat_urllib_request.Request):
  3429. def get_method(self):
  3430. return 'HEAD'
  3431. class PUTRequest(compat_urllib_request.Request):
  3432. def get_method(self):
  3433. return 'PUT'
  3434. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1, base=None):
  3435. if get_attr:
  3436. if v is not None:
  3437. v = getattr(v, get_attr, None)
  3438. if v in (None, ''):
  3439. return default
  3440. try:
  3441. # like int, raise if base is specified and v is not a string
  3442. return (int(v) if base is None else int(v, base=base)) * invscale // scale
  3443. except (ValueError, TypeError, OverflowError):
  3444. return default
  3445. def str_or_none(v, default=None):
  3446. return default if v is None else compat_str(v)
  3447. def str_to_int(int_str):
  3448. """ A more relaxed version of int_or_none """
  3449. if isinstance(int_str, compat_integer_types):
  3450. return int_str
  3451. elif isinstance(int_str, compat_str):
  3452. int_str = re.sub(r'[,\.\+]', '', int_str)
  3453. return int_or_none(int_str)
  3454. def float_or_none(v, scale=1, invscale=1, default=None):
  3455. if v is None:
  3456. return default
  3457. try:
  3458. return float(v) * invscale / scale
  3459. except (ValueError, TypeError):
  3460. return default
  3461. def bool_or_none(v, default=None):
  3462. return v if isinstance(v, bool) else default
  3463. def strip_or_none(v, default=None):
  3464. return v.strip() if isinstance(v, compat_str) else default
  3465. def txt_or_none(v, default=None):
  3466. """ Combine str/strip_or_none, disallow blank value (for traverse_obj) """
  3467. return default if v is None else (compat_str(v).strip() or default)
  3468. def url_or_none(url):
  3469. if not url or not isinstance(url, compat_str):
  3470. return None
  3471. url = url.strip()
  3472. return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None
  3473. def parse_duration(s):
  3474. if not isinstance(s, compat_basestring):
  3475. return None
  3476. s = s.strip()
  3477. days, hours, mins, secs, ms = [None] * 5
  3478. m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s)
  3479. if m:
  3480. days, hours, mins, secs, ms = m.groups()
  3481. else:
  3482. m = re.match(
  3483. r'''(?ix)(?:P?
  3484. (?:
  3485. [0-9]+\s*y(?:ears?)?\s*
  3486. )?
  3487. (?:
  3488. [0-9]+\s*m(?:onths?)?\s*
  3489. )?
  3490. (?:
  3491. [0-9]+\s*w(?:eeks?)?\s*
  3492. )?
  3493. (?:
  3494. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3495. )?
  3496. T)?
  3497. (?:
  3498. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3499. )?
  3500. (?:
  3501. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3502. )?
  3503. (?:
  3504. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3505. )?Z?$''', s)
  3506. if m:
  3507. days, hours, mins, secs, ms = m.groups()
  3508. else:
  3509. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3510. if m:
  3511. hours, mins = m.groups()
  3512. else:
  3513. return None
  3514. duration = 0
  3515. if secs:
  3516. duration += float(secs)
  3517. if mins:
  3518. duration += float(mins) * 60
  3519. if hours:
  3520. duration += float(hours) * 60 * 60
  3521. if days:
  3522. duration += float(days) * 24 * 60 * 60
  3523. if ms:
  3524. duration += float(ms)
  3525. return duration
  3526. def _change_extension(prepend, filename, ext, expected_real_ext=None):
  3527. name, real_ext = os.path.splitext(filename)
  3528. sanitize_extension = _UnsafeExtensionError.sanitize_extension
  3529. if not expected_real_ext or real_ext.partition('.')[0::2] == ('', expected_real_ext):
  3530. filename = name
  3531. if prepend and real_ext:
  3532. sanitize_extension(ext, prepend=prepend)
  3533. return ''.join((filename, '.', ext, real_ext))
  3534. # Mitigate path traversal and file impersonation attacks
  3535. return '.'.join((filename, sanitize_extension(ext)))
  3536. prepend_extension = functools.partial(_change_extension, True)
  3537. replace_extension = functools.partial(_change_extension, False)
  3538. def check_executable(exe, args=[]):
  3539. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3540. args can be a list of arguments for a short output (like -version) """
  3541. try:
  3542. process_communicate_or_kill(subprocess.Popen(
  3543. [exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
  3544. except OSError:
  3545. return False
  3546. return exe
  3547. def get_exe_version(exe, args=['--version'],
  3548. version_re=None, unrecognized='present'):
  3549. """ Returns the version of the specified executable,
  3550. or False if the executable is not present """
  3551. try:
  3552. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3553. # SIGTTOU if youtube-dl is run in the background.
  3554. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3555. out, _ = process_communicate_or_kill(subprocess.Popen(
  3556. [encodeArgument(exe)] + args,
  3557. stdin=subprocess.PIPE,
  3558. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  3559. except OSError:
  3560. return False
  3561. out = _decode_compat_str(out, 'ascii', 'ignore')
  3562. return detect_exe_version(out, version_re, unrecognized)
  3563. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3564. assert isinstance(output, compat_str)
  3565. if version_re is None:
  3566. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3567. m = re.search(version_re, output)
  3568. if m:
  3569. return m.group(1)
  3570. else:
  3571. return unrecognized
  3572. class LazyList(compat_collections_abc.Iterable):
  3573. """Lazy immutable list from an iterable
  3574. Note that slices of a LazyList are lists and not LazyList"""
  3575. class IndexError(IndexError):
  3576. def __init__(self, cause=None):
  3577. if cause:
  3578. # reproduce `raise from`
  3579. self.__cause__ = cause
  3580. super(IndexError, self).__init__()
  3581. def __init__(self, iterable, **kwargs):
  3582. # kwarg-only
  3583. reverse = kwargs.get('reverse', False)
  3584. _cache = kwargs.get('_cache')
  3585. self._iterable = iter(iterable)
  3586. self._cache = [] if _cache is None else _cache
  3587. self._reversed = reverse
  3588. def __iter__(self):
  3589. if self._reversed:
  3590. # We need to consume the entire iterable to iterate in reverse
  3591. for item in self.exhaust():
  3592. yield item
  3593. return
  3594. for item in self._cache:
  3595. yield item
  3596. for item in self._iterable:
  3597. self._cache.append(item)
  3598. yield item
  3599. def _exhaust(self):
  3600. self._cache.extend(self._iterable)
  3601. self._iterable = [] # Discard the emptied iterable to make it pickle-able
  3602. return self._cache
  3603. def exhaust(self):
  3604. """Evaluate the entire iterable"""
  3605. return self._exhaust()[::-1 if self._reversed else 1]
  3606. @staticmethod
  3607. def _reverse_index(x):
  3608. return None if x is None else ~x
  3609. def __getitem__(self, idx):
  3610. if isinstance(idx, slice):
  3611. if self._reversed:
  3612. idx = slice(self._reverse_index(idx.start), self._reverse_index(idx.stop), -(idx.step or 1))
  3613. start, stop, step = idx.start, idx.stop, idx.step or 1
  3614. elif isinstance(idx, int):
  3615. if self._reversed:
  3616. idx = self._reverse_index(idx)
  3617. start, stop, step = idx, idx, 0
  3618. else:
  3619. raise TypeError('indices must be integers or slices')
  3620. if ((start or 0) < 0 or (stop or 0) < 0
  3621. or (start is None and step < 0)
  3622. or (stop is None and step > 0)):
  3623. # We need to consume the entire iterable to be able to slice from the end
  3624. # Obviously, never use this with infinite iterables
  3625. self._exhaust()
  3626. try:
  3627. return self._cache[idx]
  3628. except IndexError as e:
  3629. raise self.IndexError(e)
  3630. n = max(start or 0, stop or 0) - len(self._cache) + 1
  3631. if n > 0:
  3632. self._cache.extend(itertools.islice(self._iterable, n))
  3633. try:
  3634. return self._cache[idx]
  3635. except IndexError as e:
  3636. raise self.IndexError(e)
  3637. def __bool__(self):
  3638. try:
  3639. self[-1] if self._reversed else self[0]
  3640. except self.IndexError:
  3641. return False
  3642. return True
  3643. def __len__(self):
  3644. self._exhaust()
  3645. return len(self._cache)
  3646. def __reversed__(self):
  3647. return type(self)(self._iterable, reverse=not self._reversed, _cache=self._cache)
  3648. def __copy__(self):
  3649. return type(self)(self._iterable, reverse=self._reversed, _cache=self._cache)
  3650. def __repr__(self):
  3651. # repr and str should mimic a list. So we exhaust the iterable
  3652. return repr(self.exhaust())
  3653. def __str__(self):
  3654. return repr(self.exhaust())
  3655. class PagedList(object):
  3656. def __len__(self):
  3657. # This is only useful for tests
  3658. return len(self.getslice())
  3659. class OnDemandPagedList(PagedList):
  3660. def __init__(self, pagefunc, pagesize, use_cache=True):
  3661. self._pagefunc = pagefunc
  3662. self._pagesize = pagesize
  3663. self._use_cache = use_cache
  3664. if use_cache:
  3665. self._cache = {}
  3666. def getslice(self, start=0, end=None):
  3667. res = []
  3668. for pagenum in itertools.count(start // self._pagesize):
  3669. firstid = pagenum * self._pagesize
  3670. nextfirstid = pagenum * self._pagesize + self._pagesize
  3671. if start >= nextfirstid:
  3672. continue
  3673. page_results = None
  3674. if self._use_cache:
  3675. page_results = self._cache.get(pagenum)
  3676. if page_results is None:
  3677. page_results = list(self._pagefunc(pagenum))
  3678. if self._use_cache:
  3679. self._cache[pagenum] = page_results
  3680. startv = (
  3681. start % self._pagesize
  3682. if firstid <= start < nextfirstid
  3683. else 0)
  3684. endv = (
  3685. ((end - 1) % self._pagesize) + 1
  3686. if (end is not None and firstid <= end <= nextfirstid)
  3687. else None)
  3688. if startv != 0 or endv is not None:
  3689. page_results = page_results[startv:endv]
  3690. res.extend(page_results)
  3691. # A little optimization - if current page is not "full", ie. does
  3692. # not contain page_size videos then we can assume that this page
  3693. # is the last one - there are no more ids on further pages -
  3694. # i.e. no need to query again.
  3695. if len(page_results) + startv < self._pagesize:
  3696. break
  3697. # If we got the whole page, but the next page is not interesting,
  3698. # break out early as well
  3699. if end == nextfirstid:
  3700. break
  3701. return res
  3702. class InAdvancePagedList(PagedList):
  3703. def __init__(self, pagefunc, pagecount, pagesize):
  3704. self._pagefunc = pagefunc
  3705. self._pagecount = pagecount
  3706. self._pagesize = pagesize
  3707. def getslice(self, start=0, end=None):
  3708. res = []
  3709. start_page = start // self._pagesize
  3710. end_page = (
  3711. self._pagecount if end is None else (end // self._pagesize + 1))
  3712. skip_elems = start - start_page * self._pagesize
  3713. only_more = None if end is None else end - start
  3714. for pagenum in range(start_page, end_page):
  3715. page = list(self._pagefunc(pagenum))
  3716. if skip_elems:
  3717. page = page[skip_elems:]
  3718. skip_elems = None
  3719. if only_more is not None:
  3720. if len(page) < only_more:
  3721. only_more -= len(page)
  3722. else:
  3723. page = page[:only_more]
  3724. res.extend(page)
  3725. break
  3726. res.extend(page)
  3727. return res
  3728. def uppercase_escape(s):
  3729. unicode_escape = codecs.getdecoder('unicode_escape')
  3730. return re.sub(
  3731. r'\\U[0-9a-fA-F]{8}',
  3732. lambda m: unicode_escape(m.group(0))[0],
  3733. s)
  3734. def lowercase_escape(s):
  3735. unicode_escape = codecs.getdecoder('unicode_escape')
  3736. return re.sub(
  3737. r'\\u[0-9a-fA-F]{4}',
  3738. lambda m: unicode_escape(m.group(0))[0],
  3739. s)
  3740. def escape_rfc3986(s, safe=None):
  3741. """Escape non-ASCII characters as suggested by RFC 3986"""
  3742. if sys.version_info < (3, 0):
  3743. s = _encode_compat_str(s, 'utf-8')
  3744. if safe is not None:
  3745. safe = _encode_compat_str(safe, 'utf-8')
  3746. if safe is None:
  3747. safe = b"%/;:@&=+$,!~*'()?#[]"
  3748. # ensure unicode: after quoting, it can always be converted
  3749. return compat_str(compat_urllib_parse.quote(s, safe))
  3750. def escape_url(url):
  3751. """Escape URL as suggested by RFC 3986"""
  3752. url_parsed = compat_urllib_parse_urlparse(url)
  3753. return url_parsed._replace(
  3754. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3755. path=escape_rfc3986(url_parsed.path),
  3756. params=escape_rfc3986(url_parsed.params),
  3757. query=escape_rfc3986(url_parsed.query),
  3758. fragment=escape_rfc3986(url_parsed.fragment)
  3759. ).geturl()
  3760. def parse_qs(url, **kwargs):
  3761. return compat_parse_qs(compat_urllib_parse.urlparse(url).query, **kwargs)
  3762. def read_batch_urls(batch_fd):
  3763. def fixup(url):
  3764. url = _decode_compat_str(url, 'utf-8', 'replace')
  3765. BOM_UTF8 = '\xef\xbb\xbf'
  3766. if url.startswith(BOM_UTF8):
  3767. url = url[len(BOM_UTF8):]
  3768. url = url.strip()
  3769. if url.startswith(('#', ';', ']')):
  3770. return False
  3771. return url
  3772. with contextlib.closing(batch_fd) as fd:
  3773. return [url for url in map(fixup, fd) if url]
  3774. def urlencode_postdata(*args, **kargs):
  3775. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3776. def update_url(url, **kwargs):
  3777. """Replace URL components specified by kwargs
  3778. url: compat_str or parsed URL tuple
  3779. if query_update is in kwargs, update query with
  3780. its value instead of replacing (overrides any `query`)
  3781. NB: query_update expects parse_qs() format: [key: value_list, ...]
  3782. returns: compat_str
  3783. """
  3784. if not kwargs:
  3785. return compat_urllib_parse.urlunparse(url) if isinstance(url, tuple) else url
  3786. if not isinstance(url, tuple):
  3787. url = compat_urllib_parse.urlparse(url)
  3788. query = kwargs.pop('query_update', None)
  3789. if query:
  3790. qs = compat_parse_qs(url.query)
  3791. qs.update(query)
  3792. kwargs['query'] = compat_urllib_parse_urlencode(qs, True)
  3793. kwargs = compat_kwargs(kwargs)
  3794. return compat_urllib_parse.urlunparse(url._replace(**kwargs))
  3795. def update_url_query(url, query):
  3796. return update_url(url, query_update=query)
  3797. def update_Request(req, url=None, data=None, headers={}, query={}):
  3798. req_headers = req.headers.copy()
  3799. req_headers.update(headers)
  3800. req_data = data if data is not None else req.data
  3801. req_url = update_url_query(url or req.get_full_url(), query)
  3802. req_type = {'HEAD': HEADRequest, 'PUT': PUTRequest}.get(
  3803. req.get_method(), compat_urllib_request.Request)
  3804. new_req = req_type(
  3805. req_url, data=req_data, headers=req_headers,
  3806. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3807. if hasattr(req, 'timeout'):
  3808. new_req.timeout = req.timeout
  3809. return new_req
  3810. def _multipart_encode_impl(data, boundary):
  3811. content_type = 'multipart/form-data; boundary=%s' % boundary
  3812. out = b''
  3813. for k, v in data.items():
  3814. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3815. k = _encode_compat_str(k, 'utf-8')
  3816. v = _encode_compat_str(v, 'utf-8')
  3817. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3818. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3819. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3820. if boundary.encode('ascii') in content:
  3821. raise ValueError('Boundary overlaps with data')
  3822. out += content
  3823. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3824. return out, content_type
  3825. def multipart_encode(data, boundary=None):
  3826. '''
  3827. Encode a dict to RFC 7578-compliant form-data
  3828. data:
  3829. A dict where keys and values can be either Unicode or bytes-like
  3830. objects.
  3831. boundary:
  3832. If specified a Unicode object, it's used as the boundary. Otherwise
  3833. a random boundary is generated.
  3834. Reference: https://tools.ietf.org/html/rfc7578
  3835. '''
  3836. has_specified_boundary = boundary is not None
  3837. while True:
  3838. if boundary is None:
  3839. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3840. try:
  3841. out, content_type = _multipart_encode_impl(data, boundary)
  3842. break
  3843. except ValueError:
  3844. if has_specified_boundary:
  3845. raise
  3846. boundary = None
  3847. return out, content_type
  3848. def is_iterable_like(x, allowed_types=compat_collections_abc.Iterable, blocked_types=NO_DEFAULT):
  3849. if blocked_types is NO_DEFAULT:
  3850. blocked_types = (compat_str, bytes, compat_collections_abc.Mapping)
  3851. return isinstance(x, allowed_types) and not isinstance(x, blocked_types)
  3852. def variadic(x, allowed_types=NO_DEFAULT):
  3853. if isinstance(allowed_types, compat_collections_abc.Iterable):
  3854. allowed_types = tuple(allowed_types)
  3855. return x if is_iterable_like(x, blocked_types=allowed_types) else (x,)
  3856. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3857. exp = (lambda x: x or None) if skip_false_values else IDENTITY
  3858. return traverse_obj(d, *variadic(key_or_keys), expected_type=exp,
  3859. default=default, get_all=False)
  3860. def try_call(*funcs, **kwargs):
  3861. # parameter defaults
  3862. expected_type = kwargs.get('expected_type')
  3863. fargs = kwargs.get('args', [])
  3864. fkwargs = kwargs.get('kwargs', {})
  3865. for f in funcs:
  3866. try:
  3867. val = f(*fargs, **fkwargs)
  3868. except (AttributeError, KeyError, TypeError, IndexError, ZeroDivisionError):
  3869. pass
  3870. else:
  3871. if expected_type is None or isinstance(val, expected_type):
  3872. return val
  3873. def try_get(src, getter, expected_type=None):
  3874. if not isinstance(getter, (list, tuple)):
  3875. getter = [getter]
  3876. for get in getter:
  3877. try:
  3878. v = get(src)
  3879. except (AttributeError, KeyError, TypeError, IndexError):
  3880. pass
  3881. else:
  3882. if expected_type is None or isinstance(v, expected_type):
  3883. return v
  3884. def filter_dict(dct, cndn=lambda _, v: v is not None):
  3885. # NB: don't use dict comprehension for python 2.6 compatibility
  3886. return dict((k, v) for k, v in dct.items() if cndn(k, v))
  3887. def merge_dicts(*dicts, **kwargs):
  3888. """
  3889. Merge the `dict`s in `dicts` using the first valid value for each key.
  3890. Normally valid: not None and not an empty string
  3891. Keyword-only args:
  3892. unblank: allow empty string if False (default True)
  3893. rev: merge dicts in reverse order (default False)
  3894. merge_dicts(dct1, dct2, ..., unblank=False, rev=True)
  3895. matches {**dct1, **dct2, ...}
  3896. However, merge_dicts(dct1, dct2, ..., rev=True) may often be better.
  3897. """
  3898. unblank = kwargs.get('unblank', True)
  3899. rev = kwargs.get('rev', False)
  3900. if unblank:
  3901. def can_merge_str(k, v, to_dict):
  3902. return (isinstance(v, compat_str) and v
  3903. and isinstance(to_dict[k], compat_str)
  3904. and not to_dict[k])
  3905. else:
  3906. can_merge_str = lambda k, v, to_dict: False
  3907. merged = {}
  3908. for a_dict in reversed(dicts) if rev else dicts:
  3909. for k, v in a_dict.items():
  3910. if v is None:
  3911. continue
  3912. if (k not in merged) or can_merge_str(k, v, merged):
  3913. merged[k] = v
  3914. return merged
  3915. # very poor choice of name, as if Python string encodings weren't confusing enough
  3916. def encode_compat_str(s, encoding=preferredencoding(), errors='strict'):
  3917. assert isinstance(s, compat_basestring)
  3918. return s if isinstance(s, compat_str) else compat_str(s, encoding, errors)
  3919. # what it could have been
  3920. def _decode_compat_str(s, encoding=preferredencoding(), errors='strict', or_none=False):
  3921. if not or_none:
  3922. assert isinstance(s, compat_basestring)
  3923. return (
  3924. s if isinstance(s, compat_str)
  3925. else compat_str(s, encoding, errors) if isinstance(s, compat_basestring)
  3926. else None)
  3927. # the real encode_compat_str, but only for internal use
  3928. def _encode_compat_str(s, encoding=preferredencoding(), errors='strict'):
  3929. assert isinstance(s, compat_basestring)
  3930. return s.encode(encoding, errors) if isinstance(s, compat_str) else s
  3931. US_RATINGS = {
  3932. 'G': 0,
  3933. 'PG': 10,
  3934. 'PG-13': 13,
  3935. 'R': 16,
  3936. 'NC': 18,
  3937. }
  3938. TV_PARENTAL_GUIDELINES = {
  3939. 'TV-Y': 0,
  3940. 'TV-Y7': 7,
  3941. 'TV-G': 0,
  3942. 'TV-PG': 0,
  3943. 'TV-14': 14,
  3944. 'TV-MA': 17,
  3945. }
  3946. def parse_age_limit(s):
  3947. if not isinstance(s, bool):
  3948. age = int_or_none(s)
  3949. if age is not None:
  3950. return age if 0 <= age <= 21 else None
  3951. if not isinstance(s, compat_basestring):
  3952. return None
  3953. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3954. if m:
  3955. return int(m.group('age'))
  3956. if s in US_RATINGS:
  3957. return US_RATINGS[s]
  3958. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3959. if m:
  3960. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3961. return None
  3962. def strip_jsonp(code):
  3963. return re.sub(
  3964. r'''(?sx)^
  3965. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3966. (?:\s*&&\s*(?P=func_name))?
  3967. \s*\(\s*(?P<callback_data>.*)\);?
  3968. \s*?(?://[^\n]*)*$''',
  3969. r'\g<callback_data>', code)
  3970. def js_to_json(code, *args, **kwargs):
  3971. # vars is a dict of (var, val) pairs to substitute
  3972. vars = args[0] if len(args) > 0 else kwargs.get('vars', {})
  3973. strict = kwargs.get('strict', False)
  3974. STRING_QUOTES = '\'"`'
  3975. STRING_RE = '|'.join(r'{0}(?:\\.|[^\\{0}])*{0}'.format(q) for q in STRING_QUOTES)
  3976. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
  3977. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3978. INTEGER_TABLE = (
  3979. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3980. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3981. (r'(?s)^(\d+){skip}:?$'.format(skip=SKIP_RE), 10),
  3982. )
  3983. # compat candidate
  3984. JSONDecodeError = json.JSONDecodeError if 'JSONDecodeError' in dir(json) else ValueError
  3985. def process_escape(match):
  3986. JSON_PASSTHROUGH_ESCAPES = r'"\bfnrtu'
  3987. escape = match.group(1) or match.group(2)
  3988. return ('\\' + escape if escape in JSON_PASSTHROUGH_ESCAPES
  3989. else '\\u00' if escape == 'x'
  3990. else '' if escape == '\n'
  3991. else escape)
  3992. def template_substitute(match):
  3993. evaluated = js_to_json(match.group(1), vars, strict=strict)
  3994. if evaluated[0] == '"':
  3995. return json.loads(evaluated)
  3996. return evaluated
  3997. def fix_kv(m):
  3998. v = m.group(0)
  3999. if v in ('true', 'false', 'null'):
  4000. return v
  4001. elif v in ('undefined', 'void 0'):
  4002. return 'null'
  4003. elif v.startswith('/*') or v.startswith('//') or v == ',':
  4004. return ''
  4005. if v[0] in STRING_QUOTES:
  4006. v = re.sub(r'(?s)\${([^}]+)}', template_substitute, v[1:-1]) if v[0] == '`' else v[1:-1]
  4007. escaped = re.sub(r'(?s)(")|\\(.)', process_escape, v)
  4008. return '"{0}"'.format(escaped)
  4009. inv = IDENTITY
  4010. im = re.split(r'^!+', v)
  4011. if len(im) > 1 and not im[-1].endswith(':'):
  4012. if (len(v) - len(im[1])) % 2 == 1:
  4013. inv = lambda x: 'true' if x == 0 else 'false'
  4014. else:
  4015. inv = lambda x: 'false' if x == 0 else 'true'
  4016. if not any(x for x in im):
  4017. return
  4018. v = im[-1]
  4019. for regex, base in INTEGER_TABLE:
  4020. im = re.match(regex, v)
  4021. if im:
  4022. i = int(im.group(1), base)
  4023. return ('"%s":' if v.endswith(':') else '%s') % inv(i)
  4024. if v in vars:
  4025. try:
  4026. if not strict:
  4027. json.loads(vars[v])
  4028. except JSONDecodeError:
  4029. return inv(json.dumps(vars[v]))
  4030. else:
  4031. return inv(vars[v])
  4032. if not strict:
  4033. v = try_call(inv, args=(v,), default=v)
  4034. if v in ('true', 'false'):
  4035. return v
  4036. return '"{0}"'.format(v)
  4037. raise ValueError('Unknown value: ' + v)
  4038. def create_map(mobj):
  4039. return json.dumps(dict(json.loads(js_to_json(mobj.group(1) or '[]', vars=vars))))
  4040. code = re.sub(r'new Map\((\[.*?\])?\)', create_map, code)
  4041. if not strict:
  4042. code = re.sub(r'new Date\((".+")\)', r'\g<1>', code)
  4043. code = re.sub(r'new \w+\((.*?)\)', lambda m: json.dumps(m.group(0)), code)
  4044. code = re.sub(r'parseInt\([^\d]+(\d+)[^\d]+\)', r'\1', code)
  4045. code = re.sub(r'\(function\([^)]*\)\s*\{[^}]*\}\s*\)\s*\(\s*(["\'][^)]*["\'])\s*\)', r'\1', code)
  4046. return re.sub(r'''(?sx)
  4047. {str_}|
  4048. {comment}|
  4049. ,(?={skip}[\]}}])|
  4050. void\s0|
  4051. !*(?:(?<!\d)[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
  4052. (?:\b|!+)0(?:[xX][\da-fA-F]+|[0-7]+)(?:{skip}:)?|
  4053. !+\d+(?:\.\d*)?(?:{skip}:)?|
  4054. [0-9]+(?:{skip}:)|
  4055. !+
  4056. '''.format(comment=COMMENT_RE, skip=SKIP_RE, str_=STRING_RE), fix_kv, code)
  4057. def qualities(quality_ids):
  4058. """ Get a numeric quality value out of a list of possible values """
  4059. def q(qid):
  4060. try:
  4061. return quality_ids.index(qid)
  4062. except ValueError:
  4063. return -1
  4064. return q
  4065. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  4066. def limit_length(s, length):
  4067. """ Add ellipses to overly long strings """
  4068. if s is None:
  4069. return None
  4070. ELLIPSES = '...'
  4071. if len(s) > length:
  4072. return s[:length - len(ELLIPSES)] + ELLIPSES
  4073. return s
  4074. def version_tuple(v):
  4075. return tuple(int(e) for e in re.split(r'[-.]', v))
  4076. def is_outdated_version(version, limit, assume_new=True):
  4077. if not version:
  4078. return not assume_new
  4079. try:
  4080. return version_tuple(version) < version_tuple(limit)
  4081. except ValueError:
  4082. return not assume_new
  4083. def ytdl_is_updateable():
  4084. """ Returns if youtube-dl can be updated with -U """
  4085. from zipimport import zipimporter
  4086. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  4087. def args_to_str(args):
  4088. # Get a short string representation for a subprocess command
  4089. return ' '.join(compat_shlex_quote(a) for a in args)
  4090. def error_to_compat_str(err):
  4091. return _decode_compat_str(str(err))
  4092. def mimetype2ext(mt):
  4093. if mt is None:
  4094. return None
  4095. ext = {
  4096. 'audio/mp4': 'm4a',
  4097. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  4098. # it's the most popular one
  4099. 'audio/mpeg': 'mp3',
  4100. }.get(mt)
  4101. if ext is not None:
  4102. return ext
  4103. _, _, res = mt.rpartition('/')
  4104. res = res.split(';')[0].strip().lower()
  4105. return {
  4106. '3gpp': '3gp',
  4107. 'smptett+xml': 'tt',
  4108. 'ttaf+xml': 'dfxp',
  4109. 'ttml+xml': 'ttml',
  4110. 'x-flv': 'flv',
  4111. 'x-mp4-fragmented': 'mp4',
  4112. 'x-ms-sami': 'sami',
  4113. 'x-ms-wmv': 'wmv',
  4114. 'mpegurl': 'm3u8',
  4115. 'x-mpegurl': 'm3u8',
  4116. 'vnd.apple.mpegurl': 'm3u8',
  4117. 'dash+xml': 'mpd',
  4118. 'f4m+xml': 'f4m',
  4119. 'hds+xml': 'f4m',
  4120. 'vnd.ms-sstr+xml': 'ism',
  4121. 'quicktime': 'mov',
  4122. 'mp2t': 'ts',
  4123. 'x-wav': 'wav',
  4124. }.get(res, res)
  4125. def parse_codecs(codecs_str):
  4126. # http://tools.ietf.org/html/rfc6381
  4127. if not codecs_str:
  4128. return {}
  4129. split_codecs = list(filter(None, map(
  4130. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  4131. vcodec, acodec = None, None
  4132. for full_codec in split_codecs:
  4133. codec = full_codec.split('.')[0]
  4134. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  4135. if not vcodec:
  4136. vcodec = full_codec
  4137. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  4138. if not acodec:
  4139. acodec = full_codec
  4140. else:
  4141. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  4142. if not vcodec and not acodec:
  4143. if len(split_codecs) == 2:
  4144. return {
  4145. 'vcodec': split_codecs[0],
  4146. 'acodec': split_codecs[1],
  4147. }
  4148. else:
  4149. return {
  4150. 'vcodec': vcodec or 'none',
  4151. 'acodec': acodec or 'none',
  4152. }
  4153. return {}
  4154. def urlhandle_detect_ext(url_handle):
  4155. getheader = url_handle.headers.get
  4156. cd = getheader('Content-Disposition')
  4157. if cd:
  4158. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  4159. if m:
  4160. e = determine_ext(m.group('filename'), default_ext=None)
  4161. if e:
  4162. return e
  4163. return mimetype2ext(getheader('Content-Type'))
  4164. def encode_data_uri(data, mime_type):
  4165. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  4166. def age_restricted(content_limit, age_limit):
  4167. """ Returns True iff the content should be blocked """
  4168. if age_limit is None: # No limit set
  4169. return False
  4170. if content_limit is None:
  4171. return False # Content available for everyone
  4172. return age_limit < content_limit
  4173. def is_html(first_bytes):
  4174. """ Detect whether a file contains HTML by examining its first bytes. """
  4175. BOMS = [
  4176. (b'\xef\xbb\xbf', 'utf-8'),
  4177. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  4178. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  4179. (b'\xff\xfe', 'utf-16-le'),
  4180. (b'\xfe\xff', 'utf-16-be'),
  4181. ]
  4182. for bom, enc in BOMS:
  4183. if first_bytes.startswith(bom):
  4184. s = first_bytes[len(bom):].decode(enc, 'replace')
  4185. break
  4186. else:
  4187. s = first_bytes.decode('utf-8', 'replace')
  4188. return re.match(r'^\s*<', s)
  4189. def determine_protocol(info_dict):
  4190. protocol = info_dict.get('protocol')
  4191. if protocol is not None:
  4192. return protocol
  4193. url = info_dict['url']
  4194. if url.startswith('rtmp'):
  4195. return 'rtmp'
  4196. elif url.startswith('mms'):
  4197. return 'mms'
  4198. elif url.startswith('rtsp'):
  4199. return 'rtsp'
  4200. ext = determine_ext(url)
  4201. if ext == 'm3u8':
  4202. return 'm3u8'
  4203. elif ext == 'f4m':
  4204. return 'f4m'
  4205. return compat_urllib_parse_urlparse(url).scheme
  4206. def render_table(header_row, data):
  4207. """ Render a list of rows, each as a list of values """
  4208. table = [header_row] + data
  4209. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  4210. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  4211. return '\n'.join(format_str % tuple(row) for row in table)
  4212. def _match_one(filter_part, dct):
  4213. COMPARISON_OPERATORS = {
  4214. '<': operator.lt,
  4215. '<=': operator.le,
  4216. '>': operator.gt,
  4217. '>=': operator.ge,
  4218. '=': operator.eq,
  4219. '!=': operator.ne,
  4220. }
  4221. operator_rex = re.compile(r'''(?x)\s*
  4222. (?P<key>[a-z_]+)
  4223. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  4224. (?:
  4225. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  4226. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  4227. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  4228. )
  4229. \s*$
  4230. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  4231. m = operator_rex.search(filter_part)
  4232. if m:
  4233. op = COMPARISON_OPERATORS[m.group('op')]
  4234. actual_value = dct.get(m.group('key'))
  4235. if (m.group('quotedstrval') is not None
  4236. or m.group('strval') is not None
  4237. # If the original field is a string and matching comparisonvalue is
  4238. # a number we should respect the origin of the original field
  4239. # and process comparison value as a string (see
  4240. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  4241. or actual_value is not None and m.group('intval') is not None
  4242. and isinstance(actual_value, compat_str)):
  4243. if m.group('op') not in ('=', '!='):
  4244. raise ValueError(
  4245. 'Operator %s does not support string values!' % m.group('op'))
  4246. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  4247. quote = m.group('quote')
  4248. if quote is not None:
  4249. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  4250. else:
  4251. try:
  4252. comparison_value = int(m.group('intval'))
  4253. except ValueError:
  4254. comparison_value = parse_filesize(m.group('intval'))
  4255. if comparison_value is None:
  4256. comparison_value = parse_filesize(m.group('intval') + 'B')
  4257. if comparison_value is None:
  4258. raise ValueError(
  4259. 'Invalid integer value %r in filter part %r' % (
  4260. m.group('intval'), filter_part))
  4261. if actual_value is None:
  4262. return m.group('none_inclusive')
  4263. return op(actual_value, comparison_value)
  4264. UNARY_OPERATORS = {
  4265. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  4266. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  4267. }
  4268. operator_rex = re.compile(r'''(?x)\s*
  4269. (?P<op>%s)\s*(?P<key>[a-z_]+)
  4270. \s*$
  4271. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  4272. m = operator_rex.search(filter_part)
  4273. if m:
  4274. op = UNARY_OPERATORS[m.group('op')]
  4275. actual_value = dct.get(m.group('key'))
  4276. return op(actual_value)
  4277. raise ValueError('Invalid filter part %r' % filter_part)
  4278. def match_str(filter_str, dct):
  4279. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  4280. return all(
  4281. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  4282. def match_filter_func(filter_str):
  4283. def _match_func(info_dict):
  4284. if match_str(filter_str, info_dict):
  4285. return None
  4286. else:
  4287. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  4288. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  4289. return _match_func
  4290. def parse_dfxp_time_expr(time_expr):
  4291. if not time_expr:
  4292. return
  4293. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  4294. if mobj:
  4295. return float(mobj.group('time_offset'))
  4296. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  4297. if mobj:
  4298. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  4299. def srt_subtitles_timecode(seconds):
  4300. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  4301. def dfxp2srt(dfxp_data):
  4302. '''
  4303. @param dfxp_data A bytes-like object containing DFXP data
  4304. @returns A unicode object containing converted SRT data
  4305. '''
  4306. LEGACY_NAMESPACES = (
  4307. (b'http://www.w3.org/ns/ttml', [
  4308. b'http://www.w3.org/2004/11/ttaf1',
  4309. b'http://www.w3.org/2006/04/ttaf1',
  4310. b'http://www.w3.org/2006/10/ttaf1',
  4311. ]),
  4312. (b'http://www.w3.org/ns/ttml#styling', [
  4313. b'http://www.w3.org/ns/ttml#style',
  4314. ]),
  4315. )
  4316. SUPPORTED_STYLING = [
  4317. 'color',
  4318. 'fontFamily',
  4319. 'fontSize',
  4320. 'fontStyle',
  4321. 'fontWeight',
  4322. 'textDecoration'
  4323. ]
  4324. _x = functools.partial(xpath_with_ns, ns_map={
  4325. 'xml': 'http://www.w3.org/XML/1998/namespace',
  4326. 'ttml': 'http://www.w3.org/ns/ttml',
  4327. 'tts': 'http://www.w3.org/ns/ttml#styling',
  4328. })
  4329. styles = {}
  4330. default_style = {}
  4331. class TTMLPElementParser(object):
  4332. _out = ''
  4333. _unclosed_elements = []
  4334. _applied_styles = []
  4335. def start(self, tag, attrib):
  4336. if tag in (_x('ttml:br'), 'br'):
  4337. self._out += '\n'
  4338. else:
  4339. unclosed_elements = []
  4340. style = {}
  4341. element_style_id = attrib.get('style')
  4342. if default_style:
  4343. style.update(default_style)
  4344. if element_style_id:
  4345. style.update(styles.get(element_style_id, {}))
  4346. for prop in SUPPORTED_STYLING:
  4347. prop_val = attrib.get(_x('tts:' + prop))
  4348. if prop_val:
  4349. style[prop] = prop_val
  4350. if style:
  4351. font = ''
  4352. for k, v in sorted(style.items()):
  4353. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  4354. continue
  4355. if k == 'color':
  4356. font += ' color="%s"' % v
  4357. elif k == 'fontSize':
  4358. font += ' size="%s"' % v
  4359. elif k == 'fontFamily':
  4360. font += ' face="%s"' % v
  4361. elif k == 'fontWeight' and v == 'bold':
  4362. self._out += '<b>'
  4363. unclosed_elements.append('b')
  4364. elif k == 'fontStyle' and v == 'italic':
  4365. self._out += '<i>'
  4366. unclosed_elements.append('i')
  4367. elif k == 'textDecoration' and v == 'underline':
  4368. self._out += '<u>'
  4369. unclosed_elements.append('u')
  4370. if font:
  4371. self._out += '<font' + font + '>'
  4372. unclosed_elements.append('font')
  4373. applied_style = {}
  4374. if self._applied_styles:
  4375. applied_style.update(self._applied_styles[-1])
  4376. applied_style.update(style)
  4377. self._applied_styles.append(applied_style)
  4378. self._unclosed_elements.append(unclosed_elements)
  4379. def end(self, tag):
  4380. if tag not in (_x('ttml:br'), 'br'):
  4381. unclosed_elements = self._unclosed_elements.pop()
  4382. for element in reversed(unclosed_elements):
  4383. self._out += '</%s>' % element
  4384. if unclosed_elements and self._applied_styles:
  4385. self._applied_styles.pop()
  4386. def data(self, data):
  4387. self._out += data
  4388. def close(self):
  4389. return self._out.strip()
  4390. def parse_node(node):
  4391. target = TTMLPElementParser()
  4392. parser = xml.etree.ElementTree.XMLParser(target=target)
  4393. parser.feed(xml.etree.ElementTree.tostring(node))
  4394. return parser.close()
  4395. for k, v in LEGACY_NAMESPACES:
  4396. for ns in v:
  4397. dfxp_data = dfxp_data.replace(ns, k)
  4398. dfxp = compat_etree_fromstring(dfxp_data)
  4399. out = []
  4400. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  4401. if not paras:
  4402. raise ValueError('Invalid dfxp/TTML subtitle')
  4403. repeat = False
  4404. while True:
  4405. for style in dfxp.findall(_x('.//ttml:style')):
  4406. style_id = style.get('id') or style.get(_x('xml:id'))
  4407. if not style_id:
  4408. continue
  4409. parent_style_id = style.get('style')
  4410. if parent_style_id:
  4411. if parent_style_id not in styles:
  4412. repeat = True
  4413. continue
  4414. styles[style_id] = styles[parent_style_id].copy()
  4415. for prop in SUPPORTED_STYLING:
  4416. prop_val = style.get(_x('tts:' + prop))
  4417. if prop_val:
  4418. styles.setdefault(style_id, {})[prop] = prop_val
  4419. if repeat:
  4420. repeat = False
  4421. else:
  4422. break
  4423. for p in ('body', 'div'):
  4424. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  4425. if ele is None:
  4426. continue
  4427. style = styles.get(ele.get('style'))
  4428. if not style:
  4429. continue
  4430. default_style.update(style)
  4431. for para, index in zip(paras, itertools.count(1)):
  4432. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  4433. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  4434. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  4435. if begin_time is None:
  4436. continue
  4437. if not end_time:
  4438. if not dur:
  4439. continue
  4440. end_time = begin_time + dur
  4441. out.append('%d\n%s --> %s\n%s\n\n' % (
  4442. index,
  4443. srt_subtitles_timecode(begin_time),
  4444. srt_subtitles_timecode(end_time),
  4445. parse_node(para)))
  4446. return ''.join(out)
  4447. def cli_option(params, command_option, param):
  4448. param = params.get(param)
  4449. if param:
  4450. param = compat_str(param)
  4451. return [command_option, param] if param is not None else []
  4452. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  4453. param = params.get(param)
  4454. if param is None:
  4455. return []
  4456. assert isinstance(param, bool)
  4457. if separator:
  4458. return [command_option + separator + (true_value if param else false_value)]
  4459. return [command_option, true_value if param else false_value]
  4460. def cli_valueless_option(params, command_option, param, expected_value=True):
  4461. param = params.get(param)
  4462. return [command_option] if param == expected_value else []
  4463. def cli_configuration_args(params, param, default=[]):
  4464. ex_args = params.get(param)
  4465. if ex_args is None:
  4466. return default
  4467. assert isinstance(ex_args, list)
  4468. return ex_args
  4469. class ISO639Utils(object):
  4470. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  4471. _lang_map = {
  4472. 'aa': 'aar',
  4473. 'ab': 'abk',
  4474. 'ae': 'ave',
  4475. 'af': 'afr',
  4476. 'ak': 'aka',
  4477. 'am': 'amh',
  4478. 'an': 'arg',
  4479. 'ar': 'ara',
  4480. 'as': 'asm',
  4481. 'av': 'ava',
  4482. 'ay': 'aym',
  4483. 'az': 'aze',
  4484. 'ba': 'bak',
  4485. 'be': 'bel',
  4486. 'bg': 'bul',
  4487. 'bh': 'bih',
  4488. 'bi': 'bis',
  4489. 'bm': 'bam',
  4490. 'bn': 'ben',
  4491. 'bo': 'bod',
  4492. 'br': 'bre',
  4493. 'bs': 'bos',
  4494. 'ca': 'cat',
  4495. 'ce': 'che',
  4496. 'ch': 'cha',
  4497. 'co': 'cos',
  4498. 'cr': 'cre',
  4499. 'cs': 'ces',
  4500. 'cu': 'chu',
  4501. 'cv': 'chv',
  4502. 'cy': 'cym',
  4503. 'da': 'dan',
  4504. 'de': 'deu',
  4505. 'dv': 'div',
  4506. 'dz': 'dzo',
  4507. 'ee': 'ewe',
  4508. 'el': 'ell',
  4509. 'en': 'eng',
  4510. 'eo': 'epo',
  4511. 'es': 'spa',
  4512. 'et': 'est',
  4513. 'eu': 'eus',
  4514. 'fa': 'fas',
  4515. 'ff': 'ful',
  4516. 'fi': 'fin',
  4517. 'fj': 'fij',
  4518. 'fo': 'fao',
  4519. 'fr': 'fra',
  4520. 'fy': 'fry',
  4521. 'ga': 'gle',
  4522. 'gd': 'gla',
  4523. 'gl': 'glg',
  4524. 'gn': 'grn',
  4525. 'gu': 'guj',
  4526. 'gv': 'glv',
  4527. 'ha': 'hau',
  4528. 'he': 'heb',
  4529. 'iw': 'heb', # Replaced by he in 1989 revision
  4530. 'hi': 'hin',
  4531. 'ho': 'hmo',
  4532. 'hr': 'hrv',
  4533. 'ht': 'hat',
  4534. 'hu': 'hun',
  4535. 'hy': 'hye',
  4536. 'hz': 'her',
  4537. 'ia': 'ina',
  4538. 'id': 'ind',
  4539. 'in': 'ind', # Replaced by id in 1989 revision
  4540. 'ie': 'ile',
  4541. 'ig': 'ibo',
  4542. 'ii': 'iii',
  4543. 'ik': 'ipk',
  4544. 'io': 'ido',
  4545. 'is': 'isl',
  4546. 'it': 'ita',
  4547. 'iu': 'iku',
  4548. 'ja': 'jpn',
  4549. 'jv': 'jav',
  4550. 'ka': 'kat',
  4551. 'kg': 'kon',
  4552. 'ki': 'kik',
  4553. 'kj': 'kua',
  4554. 'kk': 'kaz',
  4555. 'kl': 'kal',
  4556. 'km': 'khm',
  4557. 'kn': 'kan',
  4558. 'ko': 'kor',
  4559. 'kr': 'kau',
  4560. 'ks': 'kas',
  4561. 'ku': 'kur',
  4562. 'kv': 'kom',
  4563. 'kw': 'cor',
  4564. 'ky': 'kir',
  4565. 'la': 'lat',
  4566. 'lb': 'ltz',
  4567. 'lg': 'lug',
  4568. 'li': 'lim',
  4569. 'ln': 'lin',
  4570. 'lo': 'lao',
  4571. 'lt': 'lit',
  4572. 'lu': 'lub',
  4573. 'lv': 'lav',
  4574. 'mg': 'mlg',
  4575. 'mh': 'mah',
  4576. 'mi': 'mri',
  4577. 'mk': 'mkd',
  4578. 'ml': 'mal',
  4579. 'mn': 'mon',
  4580. 'mr': 'mar',
  4581. 'ms': 'msa',
  4582. 'mt': 'mlt',
  4583. 'my': 'mya',
  4584. 'na': 'nau',
  4585. 'nb': 'nob',
  4586. 'nd': 'nde',
  4587. 'ne': 'nep',
  4588. 'ng': 'ndo',
  4589. 'nl': 'nld',
  4590. 'nn': 'nno',
  4591. 'no': 'nor',
  4592. 'nr': 'nbl',
  4593. 'nv': 'nav',
  4594. 'ny': 'nya',
  4595. 'oc': 'oci',
  4596. 'oj': 'oji',
  4597. 'om': 'orm',
  4598. 'or': 'ori',
  4599. 'os': 'oss',
  4600. 'pa': 'pan',
  4601. 'pi': 'pli',
  4602. 'pl': 'pol',
  4603. 'ps': 'pus',
  4604. 'pt': 'por',
  4605. 'qu': 'que',
  4606. 'rm': 'roh',
  4607. 'rn': 'run',
  4608. 'ro': 'ron',
  4609. 'ru': 'rus',
  4610. 'rw': 'kin',
  4611. 'sa': 'san',
  4612. 'sc': 'srd',
  4613. 'sd': 'snd',
  4614. 'se': 'sme',
  4615. 'sg': 'sag',
  4616. 'si': 'sin',
  4617. 'sk': 'slk',
  4618. 'sl': 'slv',
  4619. 'sm': 'smo',
  4620. 'sn': 'sna',
  4621. 'so': 'som',
  4622. 'sq': 'sqi',
  4623. 'sr': 'srp',
  4624. 'ss': 'ssw',
  4625. 'st': 'sot',
  4626. 'su': 'sun',
  4627. 'sv': 'swe',
  4628. 'sw': 'swa',
  4629. 'ta': 'tam',
  4630. 'te': 'tel',
  4631. 'tg': 'tgk',
  4632. 'th': 'tha',
  4633. 'ti': 'tir',
  4634. 'tk': 'tuk',
  4635. 'tl': 'tgl',
  4636. 'tn': 'tsn',
  4637. 'to': 'ton',
  4638. 'tr': 'tur',
  4639. 'ts': 'tso',
  4640. 'tt': 'tat',
  4641. 'tw': 'twi',
  4642. 'ty': 'tah',
  4643. 'ug': 'uig',
  4644. 'uk': 'ukr',
  4645. 'ur': 'urd',
  4646. 'uz': 'uzb',
  4647. 've': 'ven',
  4648. 'vi': 'vie',
  4649. 'vo': 'vol',
  4650. 'wa': 'wln',
  4651. 'wo': 'wol',
  4652. 'xh': 'xho',
  4653. 'yi': 'yid',
  4654. 'ji': 'yid', # Replaced by yi in 1989 revision
  4655. 'yo': 'yor',
  4656. 'za': 'zha',
  4657. 'zh': 'zho',
  4658. 'zu': 'zul',
  4659. }
  4660. @classmethod
  4661. def short2long(cls, code):
  4662. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4663. return cls._lang_map.get(code[:2])
  4664. @classmethod
  4665. def long2short(cls, code):
  4666. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4667. for short_name, long_name in cls._lang_map.items():
  4668. if long_name == code:
  4669. return short_name
  4670. class ISO3166Utils(object):
  4671. # From http://data.okfn.org/data/core/country-list
  4672. _country_map = {
  4673. 'AF': 'Afghanistan',
  4674. 'AX': 'Åland Islands',
  4675. 'AL': 'Albania',
  4676. 'DZ': 'Algeria',
  4677. 'AS': 'American Samoa',
  4678. 'AD': 'Andorra',
  4679. 'AO': 'Angola',
  4680. 'AI': 'Anguilla',
  4681. 'AQ': 'Antarctica',
  4682. 'AG': 'Antigua and Barbuda',
  4683. 'AR': 'Argentina',
  4684. 'AM': 'Armenia',
  4685. 'AW': 'Aruba',
  4686. 'AU': 'Australia',
  4687. 'AT': 'Austria',
  4688. 'AZ': 'Azerbaijan',
  4689. 'BS': 'Bahamas',
  4690. 'BH': 'Bahrain',
  4691. 'BD': 'Bangladesh',
  4692. 'BB': 'Barbados',
  4693. 'BY': 'Belarus',
  4694. 'BE': 'Belgium',
  4695. 'BZ': 'Belize',
  4696. 'BJ': 'Benin',
  4697. 'BM': 'Bermuda',
  4698. 'BT': 'Bhutan',
  4699. 'BO': 'Bolivia, Plurinational State of',
  4700. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4701. 'BA': 'Bosnia and Herzegovina',
  4702. 'BW': 'Botswana',
  4703. 'BV': 'Bouvet Island',
  4704. 'BR': 'Brazil',
  4705. 'IO': 'British Indian Ocean Territory',
  4706. 'BN': 'Brunei Darussalam',
  4707. 'BG': 'Bulgaria',
  4708. 'BF': 'Burkina Faso',
  4709. 'BI': 'Burundi',
  4710. 'KH': 'Cambodia',
  4711. 'CM': 'Cameroon',
  4712. 'CA': 'Canada',
  4713. 'CV': 'Cape Verde',
  4714. 'KY': 'Cayman Islands',
  4715. 'CF': 'Central African Republic',
  4716. 'TD': 'Chad',
  4717. 'CL': 'Chile',
  4718. 'CN': 'China',
  4719. 'CX': 'Christmas Island',
  4720. 'CC': 'Cocos (Keeling) Islands',
  4721. 'CO': 'Colombia',
  4722. 'KM': 'Comoros',
  4723. 'CG': 'Congo',
  4724. 'CD': 'Congo, the Democratic Republic of the',
  4725. 'CK': 'Cook Islands',
  4726. 'CR': 'Costa Rica',
  4727. 'CI': 'Côte d\'Ivoire',
  4728. 'HR': 'Croatia',
  4729. 'CU': 'Cuba',
  4730. 'CW': 'Curaçao',
  4731. 'CY': 'Cyprus',
  4732. 'CZ': 'Czech Republic',
  4733. 'DK': 'Denmark',
  4734. 'DJ': 'Djibouti',
  4735. 'DM': 'Dominica',
  4736. 'DO': 'Dominican Republic',
  4737. 'EC': 'Ecuador',
  4738. 'EG': 'Egypt',
  4739. 'SV': 'El Salvador',
  4740. 'GQ': 'Equatorial Guinea',
  4741. 'ER': 'Eritrea',
  4742. 'EE': 'Estonia',
  4743. 'ET': 'Ethiopia',
  4744. 'FK': 'Falkland Islands (Malvinas)',
  4745. 'FO': 'Faroe Islands',
  4746. 'FJ': 'Fiji',
  4747. 'FI': 'Finland',
  4748. 'FR': 'France',
  4749. 'GF': 'French Guiana',
  4750. 'PF': 'French Polynesia',
  4751. 'TF': 'French Southern Territories',
  4752. 'GA': 'Gabon',
  4753. 'GM': 'Gambia',
  4754. 'GE': 'Georgia',
  4755. 'DE': 'Germany',
  4756. 'GH': 'Ghana',
  4757. 'GI': 'Gibraltar',
  4758. 'GR': 'Greece',
  4759. 'GL': 'Greenland',
  4760. 'GD': 'Grenada',
  4761. 'GP': 'Guadeloupe',
  4762. 'GU': 'Guam',
  4763. 'GT': 'Guatemala',
  4764. 'GG': 'Guernsey',
  4765. 'GN': 'Guinea',
  4766. 'GW': 'Guinea-Bissau',
  4767. 'GY': 'Guyana',
  4768. 'HT': 'Haiti',
  4769. 'HM': 'Heard Island and McDonald Islands',
  4770. 'VA': 'Holy See (Vatican City State)',
  4771. 'HN': 'Honduras',
  4772. 'HK': 'Hong Kong',
  4773. 'HU': 'Hungary',
  4774. 'IS': 'Iceland',
  4775. 'IN': 'India',
  4776. 'ID': 'Indonesia',
  4777. 'IR': 'Iran, Islamic Republic of',
  4778. 'IQ': 'Iraq',
  4779. 'IE': 'Ireland',
  4780. 'IM': 'Isle of Man',
  4781. 'IL': 'Israel',
  4782. 'IT': 'Italy',
  4783. 'JM': 'Jamaica',
  4784. 'JP': 'Japan',
  4785. 'JE': 'Jersey',
  4786. 'JO': 'Jordan',
  4787. 'KZ': 'Kazakhstan',
  4788. 'KE': 'Kenya',
  4789. 'KI': 'Kiribati',
  4790. 'KP': 'Korea, Democratic People\'s Republic of',
  4791. 'KR': 'Korea, Republic of',
  4792. 'KW': 'Kuwait',
  4793. 'KG': 'Kyrgyzstan',
  4794. 'LA': 'Lao People\'s Democratic Republic',
  4795. 'LV': 'Latvia',
  4796. 'LB': 'Lebanon',
  4797. 'LS': 'Lesotho',
  4798. 'LR': 'Liberia',
  4799. 'LY': 'Libya',
  4800. 'LI': 'Liechtenstein',
  4801. 'LT': 'Lithuania',
  4802. 'LU': 'Luxembourg',
  4803. 'MO': 'Macao',
  4804. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4805. 'MG': 'Madagascar',
  4806. 'MW': 'Malawi',
  4807. 'MY': 'Malaysia',
  4808. 'MV': 'Maldives',
  4809. 'ML': 'Mali',
  4810. 'MT': 'Malta',
  4811. 'MH': 'Marshall Islands',
  4812. 'MQ': 'Martinique',
  4813. 'MR': 'Mauritania',
  4814. 'MU': 'Mauritius',
  4815. 'YT': 'Mayotte',
  4816. 'MX': 'Mexico',
  4817. 'FM': 'Micronesia, Federated States of',
  4818. 'MD': 'Moldova, Republic of',
  4819. 'MC': 'Monaco',
  4820. 'MN': 'Mongolia',
  4821. 'ME': 'Montenegro',
  4822. 'MS': 'Montserrat',
  4823. 'MA': 'Morocco',
  4824. 'MZ': 'Mozambique',
  4825. 'MM': 'Myanmar',
  4826. 'NA': 'Namibia',
  4827. 'NR': 'Nauru',
  4828. 'NP': 'Nepal',
  4829. 'NL': 'Netherlands',
  4830. 'NC': 'New Caledonia',
  4831. 'NZ': 'New Zealand',
  4832. 'NI': 'Nicaragua',
  4833. 'NE': 'Niger',
  4834. 'NG': 'Nigeria',
  4835. 'NU': 'Niue',
  4836. 'NF': 'Norfolk Island',
  4837. 'MP': 'Northern Mariana Islands',
  4838. 'NO': 'Norway',
  4839. 'OM': 'Oman',
  4840. 'PK': 'Pakistan',
  4841. 'PW': 'Palau',
  4842. 'PS': 'Palestine, State of',
  4843. 'PA': 'Panama',
  4844. 'PG': 'Papua New Guinea',
  4845. 'PY': 'Paraguay',
  4846. 'PE': 'Peru',
  4847. 'PH': 'Philippines',
  4848. 'PN': 'Pitcairn',
  4849. 'PL': 'Poland',
  4850. 'PT': 'Portugal',
  4851. 'PR': 'Puerto Rico',
  4852. 'QA': 'Qatar',
  4853. 'RE': 'Réunion',
  4854. 'RO': 'Romania',
  4855. 'RU': 'Russian Federation',
  4856. 'RW': 'Rwanda',
  4857. 'BL': 'Saint Barthélemy',
  4858. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4859. 'KN': 'Saint Kitts and Nevis',
  4860. 'LC': 'Saint Lucia',
  4861. 'MF': 'Saint Martin (French part)',
  4862. 'PM': 'Saint Pierre and Miquelon',
  4863. 'VC': 'Saint Vincent and the Grenadines',
  4864. 'WS': 'Samoa',
  4865. 'SM': 'San Marino',
  4866. 'ST': 'Sao Tome and Principe',
  4867. 'SA': 'Saudi Arabia',
  4868. 'SN': 'Senegal',
  4869. 'RS': 'Serbia',
  4870. 'SC': 'Seychelles',
  4871. 'SL': 'Sierra Leone',
  4872. 'SG': 'Singapore',
  4873. 'SX': 'Sint Maarten (Dutch part)',
  4874. 'SK': 'Slovakia',
  4875. 'SI': 'Slovenia',
  4876. 'SB': 'Solomon Islands',
  4877. 'SO': 'Somalia',
  4878. 'ZA': 'South Africa',
  4879. 'GS': 'South Georgia and the South Sandwich Islands',
  4880. 'SS': 'South Sudan',
  4881. 'ES': 'Spain',
  4882. 'LK': 'Sri Lanka',
  4883. 'SD': 'Sudan',
  4884. 'SR': 'Suriname',
  4885. 'SJ': 'Svalbard and Jan Mayen',
  4886. 'SZ': 'Swaziland',
  4887. 'SE': 'Sweden',
  4888. 'CH': 'Switzerland',
  4889. 'SY': 'Syrian Arab Republic',
  4890. 'TW': 'Taiwan, Province of China',
  4891. 'TJ': 'Tajikistan',
  4892. 'TZ': 'Tanzania, United Republic of',
  4893. 'TH': 'Thailand',
  4894. 'TL': 'Timor-Leste',
  4895. 'TG': 'Togo',
  4896. 'TK': 'Tokelau',
  4897. 'TO': 'Tonga',
  4898. 'TT': 'Trinidad and Tobago',
  4899. 'TN': 'Tunisia',
  4900. 'TR': 'Turkey',
  4901. 'TM': 'Turkmenistan',
  4902. 'TC': 'Turks and Caicos Islands',
  4903. 'TV': 'Tuvalu',
  4904. 'UG': 'Uganda',
  4905. 'UA': 'Ukraine',
  4906. 'AE': 'United Arab Emirates',
  4907. 'GB': 'United Kingdom',
  4908. 'US': 'United States',
  4909. 'UM': 'United States Minor Outlying Islands',
  4910. 'UY': 'Uruguay',
  4911. 'UZ': 'Uzbekistan',
  4912. 'VU': 'Vanuatu',
  4913. 'VE': 'Venezuela, Bolivarian Republic of',
  4914. 'VN': 'Viet Nam',
  4915. 'VG': 'Virgin Islands, British',
  4916. 'VI': 'Virgin Islands, U.S.',
  4917. 'WF': 'Wallis and Futuna',
  4918. 'EH': 'Western Sahara',
  4919. 'YE': 'Yemen',
  4920. 'ZM': 'Zambia',
  4921. 'ZW': 'Zimbabwe',
  4922. }
  4923. @classmethod
  4924. def short2full(cls, code):
  4925. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4926. return cls._country_map.get(code.upper())
  4927. class GeoUtils(object):
  4928. # Major IPv4 address blocks per country
  4929. _country_ip_map = {
  4930. 'AD': '46.172.224.0/19',
  4931. 'AE': '94.200.0.0/13',
  4932. 'AF': '149.54.0.0/17',
  4933. 'AG': '209.59.64.0/18',
  4934. 'AI': '204.14.248.0/21',
  4935. 'AL': '46.99.0.0/16',
  4936. 'AM': '46.70.0.0/15',
  4937. 'AO': '105.168.0.0/13',
  4938. 'AP': '182.50.184.0/21',
  4939. 'AQ': '23.154.160.0/24',
  4940. 'AR': '181.0.0.0/12',
  4941. 'AS': '202.70.112.0/20',
  4942. 'AT': '77.116.0.0/14',
  4943. 'AU': '1.128.0.0/11',
  4944. 'AW': '181.41.0.0/18',
  4945. 'AX': '185.217.4.0/22',
  4946. 'AZ': '5.197.0.0/16',
  4947. 'BA': '31.176.128.0/17',
  4948. 'BB': '65.48.128.0/17',
  4949. 'BD': '114.130.0.0/16',
  4950. 'BE': '57.0.0.0/8',
  4951. 'BF': '102.178.0.0/15',
  4952. 'BG': '95.42.0.0/15',
  4953. 'BH': '37.131.0.0/17',
  4954. 'BI': '154.117.192.0/18',
  4955. 'BJ': '137.255.0.0/16',
  4956. 'BL': '185.212.72.0/23',
  4957. 'BM': '196.12.64.0/18',
  4958. 'BN': '156.31.0.0/16',
  4959. 'BO': '161.56.0.0/16',
  4960. 'BQ': '161.0.80.0/20',
  4961. 'BR': '191.128.0.0/12',
  4962. 'BS': '24.51.64.0/18',
  4963. 'BT': '119.2.96.0/19',
  4964. 'BW': '168.167.0.0/16',
  4965. 'BY': '178.120.0.0/13',
  4966. 'BZ': '179.42.192.0/18',
  4967. 'CA': '99.224.0.0/11',
  4968. 'CD': '41.243.0.0/16',
  4969. 'CF': '197.242.176.0/21',
  4970. 'CG': '160.113.0.0/16',
  4971. 'CH': '85.0.0.0/13',
  4972. 'CI': '102.136.0.0/14',
  4973. 'CK': '202.65.32.0/19',
  4974. 'CL': '152.172.0.0/14',
  4975. 'CM': '102.244.0.0/14',
  4976. 'CN': '36.128.0.0/10',
  4977. 'CO': '181.240.0.0/12',
  4978. 'CR': '201.192.0.0/12',
  4979. 'CU': '152.206.0.0/15',
  4980. 'CV': '165.90.96.0/19',
  4981. 'CW': '190.88.128.0/17',
  4982. 'CY': '31.153.0.0/16',
  4983. 'CZ': '88.100.0.0/14',
  4984. 'DE': '53.0.0.0/8',
  4985. 'DJ': '197.241.0.0/17',
  4986. 'DK': '87.48.0.0/12',
  4987. 'DM': '192.243.48.0/20',
  4988. 'DO': '152.166.0.0/15',
  4989. 'DZ': '41.96.0.0/12',
  4990. 'EC': '186.68.0.0/15',
  4991. 'EE': '90.190.0.0/15',
  4992. 'EG': '156.160.0.0/11',
  4993. 'ER': '196.200.96.0/20',
  4994. 'ES': '88.0.0.0/11',
  4995. 'ET': '196.188.0.0/14',
  4996. 'EU': '2.16.0.0/13',
  4997. 'FI': '91.152.0.0/13',
  4998. 'FJ': '144.120.0.0/16',
  4999. 'FK': '80.73.208.0/21',
  5000. 'FM': '119.252.112.0/20',
  5001. 'FO': '88.85.32.0/19',
  5002. 'FR': '90.0.0.0/9',
  5003. 'GA': '41.158.0.0/15',
  5004. 'GB': '25.0.0.0/8',
  5005. 'GD': '74.122.88.0/21',
  5006. 'GE': '31.146.0.0/16',
  5007. 'GF': '161.22.64.0/18',
  5008. 'GG': '62.68.160.0/19',
  5009. 'GH': '154.160.0.0/12',
  5010. 'GI': '95.164.0.0/16',
  5011. 'GL': '88.83.0.0/19',
  5012. 'GM': '160.182.0.0/15',
  5013. 'GN': '197.149.192.0/18',
  5014. 'GP': '104.250.0.0/19',
  5015. 'GQ': '105.235.224.0/20',
  5016. 'GR': '94.64.0.0/13',
  5017. 'GT': '168.234.0.0/16',
  5018. 'GU': '168.123.0.0/16',
  5019. 'GW': '197.214.80.0/20',
  5020. 'GY': '181.41.64.0/18',
  5021. 'HK': '113.252.0.0/14',
  5022. 'HN': '181.210.0.0/16',
  5023. 'HR': '93.136.0.0/13',
  5024. 'HT': '148.102.128.0/17',
  5025. 'HU': '84.0.0.0/14',
  5026. 'ID': '39.192.0.0/10',
  5027. 'IE': '87.32.0.0/12',
  5028. 'IL': '79.176.0.0/13',
  5029. 'IM': '5.62.80.0/20',
  5030. 'IN': '117.192.0.0/10',
  5031. 'IO': '203.83.48.0/21',
  5032. 'IQ': '37.236.0.0/14',
  5033. 'IR': '2.176.0.0/12',
  5034. 'IS': '82.221.0.0/16',
  5035. 'IT': '79.0.0.0/10',
  5036. 'JE': '87.244.64.0/18',
  5037. 'JM': '72.27.0.0/17',
  5038. 'JO': '176.29.0.0/16',
  5039. 'JP': '133.0.0.0/8',
  5040. 'KE': '105.48.0.0/12',
  5041. 'KG': '158.181.128.0/17',
  5042. 'KH': '36.37.128.0/17',
  5043. 'KI': '103.25.140.0/22',
  5044. 'KM': '197.255.224.0/20',
  5045. 'KN': '198.167.192.0/19',
  5046. 'KP': '175.45.176.0/22',
  5047. 'KR': '175.192.0.0/10',
  5048. 'KW': '37.36.0.0/14',
  5049. 'KY': '64.96.0.0/15',
  5050. 'KZ': '2.72.0.0/13',
  5051. 'LA': '115.84.64.0/18',
  5052. 'LB': '178.135.0.0/16',
  5053. 'LC': '24.92.144.0/20',
  5054. 'LI': '82.117.0.0/19',
  5055. 'LK': '112.134.0.0/15',
  5056. 'LR': '102.183.0.0/16',
  5057. 'LS': '129.232.0.0/17',
  5058. 'LT': '78.56.0.0/13',
  5059. 'LU': '188.42.0.0/16',
  5060. 'LV': '46.109.0.0/16',
  5061. 'LY': '41.252.0.0/14',
  5062. 'MA': '105.128.0.0/11',
  5063. 'MC': '88.209.64.0/18',
  5064. 'MD': '37.246.0.0/16',
  5065. 'ME': '178.175.0.0/17',
  5066. 'MF': '74.112.232.0/21',
  5067. 'MG': '154.126.0.0/17',
  5068. 'MH': '117.103.88.0/21',
  5069. 'MK': '77.28.0.0/15',
  5070. 'ML': '154.118.128.0/18',
  5071. 'MM': '37.111.0.0/17',
  5072. 'MN': '49.0.128.0/17',
  5073. 'MO': '60.246.0.0/16',
  5074. 'MP': '202.88.64.0/20',
  5075. 'MQ': '109.203.224.0/19',
  5076. 'MR': '41.188.64.0/18',
  5077. 'MS': '208.90.112.0/22',
  5078. 'MT': '46.11.0.0/16',
  5079. 'MU': '105.16.0.0/12',
  5080. 'MV': '27.114.128.0/18',
  5081. 'MW': '102.70.0.0/15',
  5082. 'MX': '187.192.0.0/11',
  5083. 'MY': '175.136.0.0/13',
  5084. 'MZ': '197.218.0.0/15',
  5085. 'NA': '41.182.0.0/16',
  5086. 'NC': '101.101.0.0/18',
  5087. 'NE': '197.214.0.0/18',
  5088. 'NF': '203.17.240.0/22',
  5089. 'NG': '105.112.0.0/12',
  5090. 'NI': '186.76.0.0/15',
  5091. 'NL': '145.96.0.0/11',
  5092. 'NO': '84.208.0.0/13',
  5093. 'NP': '36.252.0.0/15',
  5094. 'NR': '203.98.224.0/19',
  5095. 'NU': '49.156.48.0/22',
  5096. 'NZ': '49.224.0.0/14',
  5097. 'OM': '5.36.0.0/15',
  5098. 'PA': '186.72.0.0/15',
  5099. 'PE': '186.160.0.0/14',
  5100. 'PF': '123.50.64.0/18',
  5101. 'PG': '124.240.192.0/19',
  5102. 'PH': '49.144.0.0/13',
  5103. 'PK': '39.32.0.0/11',
  5104. 'PL': '83.0.0.0/11',
  5105. 'PM': '70.36.0.0/20',
  5106. 'PR': '66.50.0.0/16',
  5107. 'PS': '188.161.0.0/16',
  5108. 'PT': '85.240.0.0/13',
  5109. 'PW': '202.124.224.0/20',
  5110. 'PY': '181.120.0.0/14',
  5111. 'QA': '37.210.0.0/15',
  5112. 'RE': '102.35.0.0/16',
  5113. 'RO': '79.112.0.0/13',
  5114. 'RS': '93.86.0.0/15',
  5115. 'RU': '5.136.0.0/13',
  5116. 'RW': '41.186.0.0/16',
  5117. 'SA': '188.48.0.0/13',
  5118. 'SB': '202.1.160.0/19',
  5119. 'SC': '154.192.0.0/11',
  5120. 'SD': '102.120.0.0/13',
  5121. 'SE': '78.64.0.0/12',
  5122. 'SG': '8.128.0.0/10',
  5123. 'SI': '188.196.0.0/14',
  5124. 'SK': '78.98.0.0/15',
  5125. 'SL': '102.143.0.0/17',
  5126. 'SM': '89.186.32.0/19',
  5127. 'SN': '41.82.0.0/15',
  5128. 'SO': '154.115.192.0/18',
  5129. 'SR': '186.179.128.0/17',
  5130. 'SS': '105.235.208.0/21',
  5131. 'ST': '197.159.160.0/19',
  5132. 'SV': '168.243.0.0/16',
  5133. 'SX': '190.102.0.0/20',
  5134. 'SY': '5.0.0.0/16',
  5135. 'SZ': '41.84.224.0/19',
  5136. 'TC': '65.255.48.0/20',
  5137. 'TD': '154.68.128.0/19',
  5138. 'TG': '196.168.0.0/14',
  5139. 'TH': '171.96.0.0/13',
  5140. 'TJ': '85.9.128.0/18',
  5141. 'TK': '27.96.24.0/21',
  5142. 'TL': '180.189.160.0/20',
  5143. 'TM': '95.85.96.0/19',
  5144. 'TN': '197.0.0.0/11',
  5145. 'TO': '175.176.144.0/21',
  5146. 'TR': '78.160.0.0/11',
  5147. 'TT': '186.44.0.0/15',
  5148. 'TV': '202.2.96.0/19',
  5149. 'TW': '120.96.0.0/11',
  5150. 'TZ': '156.156.0.0/14',
  5151. 'UA': '37.52.0.0/14',
  5152. 'UG': '102.80.0.0/13',
  5153. 'US': '6.0.0.0/8',
  5154. 'UY': '167.56.0.0/13',
  5155. 'UZ': '84.54.64.0/18',
  5156. 'VA': '212.77.0.0/19',
  5157. 'VC': '207.191.240.0/21',
  5158. 'VE': '186.88.0.0/13',
  5159. 'VG': '66.81.192.0/20',
  5160. 'VI': '146.226.0.0/16',
  5161. 'VN': '14.160.0.0/11',
  5162. 'VU': '202.80.32.0/20',
  5163. 'WF': '117.20.32.0/21',
  5164. 'WS': '202.4.32.0/19',
  5165. 'YE': '134.35.0.0/16',
  5166. 'YT': '41.242.116.0/22',
  5167. 'ZA': '41.0.0.0/11',
  5168. 'ZM': '102.144.0.0/13',
  5169. 'ZW': '102.177.192.0/18',
  5170. }
  5171. @classmethod
  5172. def random_ipv4(cls, code_or_block):
  5173. if len(code_or_block) == 2:
  5174. block = cls._country_ip_map.get(code_or_block.upper())
  5175. if not block:
  5176. return None
  5177. else:
  5178. block = code_or_block
  5179. addr, preflen = block.split('/')
  5180. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  5181. addr_max = addr_min | (0xffffffff >> int(preflen))
  5182. return compat_str(socket.inet_ntoa(
  5183. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  5184. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  5185. def __init__(self, proxies=None):
  5186. # Set default handlers
  5187. for type in ('http', 'https'):
  5188. setattr(self, '%s_open' % type,
  5189. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  5190. meth(r, proxy, type))
  5191. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  5192. def proxy_open(self, req, proxy, type):
  5193. req_proxy = req.headers.get('Ytdl-request-proxy')
  5194. if req_proxy is not None:
  5195. proxy = req_proxy
  5196. del req.headers['Ytdl-request-proxy']
  5197. if proxy == '__noproxy__':
  5198. return None # No Proxy
  5199. if compat_urllib_parse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  5200. req.add_header('Ytdl-socks-proxy', proxy)
  5201. # youtube-dl's http/https handlers do wrapping the socket with socks
  5202. return None
  5203. return compat_urllib_request.ProxyHandler.proxy_open(
  5204. self, req, proxy, type)
  5205. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  5206. # released into Public Domain
  5207. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  5208. def long_to_bytes(n, blocksize=0):
  5209. """long_to_bytes(n:long, blocksize:int) : string
  5210. Convert a long integer to a byte string.
  5211. If optional blocksize is given and greater than zero, pad the front of the
  5212. byte string with binary zeros so that the length is a multiple of
  5213. blocksize.
  5214. """
  5215. # after much testing, this algorithm was deemed to be the fastest
  5216. s = b''
  5217. n = int(n)
  5218. while n > 0:
  5219. s = compat_struct_pack('>I', n & 0xffffffff) + s
  5220. n = n >> 32
  5221. # strip off leading zeros
  5222. for i in range(len(s)):
  5223. if s[i] != b'\000'[0]:
  5224. break
  5225. else:
  5226. # only happens when n == 0
  5227. s = b'\000'
  5228. i = 0
  5229. s = s[i:]
  5230. # add back some pad bytes. this could be done more efficiently w.r.t. the
  5231. # de-padding being done above, but sigh...
  5232. if blocksize > 0 and len(s) % blocksize:
  5233. s = (blocksize - len(s) % blocksize) * b'\000' + s
  5234. return s
  5235. def bytes_to_long(s):
  5236. """bytes_to_long(string) : long
  5237. Convert a byte string to a long integer.
  5238. This is (essentially) the inverse of long_to_bytes().
  5239. """
  5240. acc = 0
  5241. length = len(s)
  5242. if length % 4:
  5243. extra = (4 - length % 4)
  5244. s = b'\000' * extra + s
  5245. length = length + extra
  5246. for i in range(0, length, 4):
  5247. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  5248. return acc
  5249. def ohdave_rsa_encrypt(data, exponent, modulus):
  5250. '''
  5251. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  5252. Input:
  5253. data: data to encrypt, bytes-like object
  5254. exponent, modulus: parameter e and N of RSA algorithm, both integer
  5255. Output: hex string of encrypted data
  5256. Limitation: supports one block encryption only
  5257. '''
  5258. payload = int(binascii.hexlify(data[::-1]), 16)
  5259. encrypted = pow(payload, exponent, modulus)
  5260. return '%x' % encrypted
  5261. def pkcs1pad(data, length):
  5262. """
  5263. Padding input data with PKCS#1 scheme
  5264. @param {int[]} data input data
  5265. @param {int} length target length
  5266. @returns {int[]} padded data
  5267. """
  5268. if len(data) > length - 11:
  5269. raise ValueError('Input data too long for PKCS#1 padding')
  5270. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  5271. return [0, 2] + pseudo_random + [0] + data
  5272. def encode_base_n(num, n, table=None):
  5273. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  5274. if not table:
  5275. table = FULL_TABLE[:n]
  5276. if n > len(table):
  5277. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  5278. if num == 0:
  5279. return table[0]
  5280. ret = ''
  5281. while num:
  5282. ret = table[num % n] + ret
  5283. num = num // n
  5284. return ret
  5285. def decode_packed_codes(code):
  5286. mobj = re.search(PACKED_CODES_RE, code)
  5287. obfuscated_code, base, count, symbols = mobj.groups()
  5288. base = int(base)
  5289. count = int(count)
  5290. symbols = symbols.split('|')
  5291. symbol_table = {}
  5292. while count:
  5293. count -= 1
  5294. base_n_count = encode_base_n(count, base)
  5295. symbol_table[base_n_count] = symbols[count] or base_n_count
  5296. return re.sub(
  5297. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  5298. obfuscated_code)
  5299. def caesar(s, alphabet, shift):
  5300. if shift == 0:
  5301. return s
  5302. l = len(alphabet)
  5303. return ''.join(
  5304. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  5305. for c in s)
  5306. def rot47(s):
  5307. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  5308. def parse_m3u8_attributes(attrib):
  5309. info = {}
  5310. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  5311. if val.startswith('"'):
  5312. val = val[1:-1]
  5313. info[key] = val
  5314. return info
  5315. def urshift(val, n):
  5316. return val >> n if val >= 0 else (val + 0x100000000) >> n
  5317. # Based on png2str() written by @gdkchan and improved by @yokrysty
  5318. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  5319. def decode_png(png_data):
  5320. # Reference: https://www.w3.org/TR/PNG/
  5321. header = png_data[8:]
  5322. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  5323. raise IOError('Not a valid PNG file.')
  5324. int_map = {1: '>B', 2: '>H', 4: '>I'}
  5325. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  5326. chunks = []
  5327. while header:
  5328. length = unpack_integer(header[:4])
  5329. header = header[4:]
  5330. chunk_type = header[:4]
  5331. header = header[4:]
  5332. chunk_data = header[:length]
  5333. header = header[length:]
  5334. header = header[4:] # Skip CRC
  5335. chunks.append({
  5336. 'type': chunk_type,
  5337. 'length': length,
  5338. 'data': chunk_data
  5339. })
  5340. ihdr = chunks[0]['data']
  5341. width = unpack_integer(ihdr[:4])
  5342. height = unpack_integer(ihdr[4:8])
  5343. idat = b''
  5344. for chunk in chunks:
  5345. if chunk['type'] == b'IDAT':
  5346. idat += chunk['data']
  5347. if not idat:
  5348. raise IOError('Unable to read PNG data.')
  5349. decompressed_data = bytearray(zlib.decompress(idat))
  5350. stride = width * 3
  5351. pixels = []
  5352. def _get_pixel(idx):
  5353. x = idx % stride
  5354. y = idx // stride
  5355. return pixels[y][x]
  5356. for y in range(height):
  5357. basePos = y * (1 + stride)
  5358. filter_type = decompressed_data[basePos]
  5359. current_row = []
  5360. pixels.append(current_row)
  5361. for x in range(stride):
  5362. color = decompressed_data[1 + basePos + x]
  5363. basex = y * stride + x
  5364. left = 0
  5365. up = 0
  5366. if x > 2:
  5367. left = _get_pixel(basex - 3)
  5368. if y > 0:
  5369. up = _get_pixel(basex - stride)
  5370. if filter_type == 1: # Sub
  5371. color = (color + left) & 0xff
  5372. elif filter_type == 2: # Up
  5373. color = (color + up) & 0xff
  5374. elif filter_type == 3: # Average
  5375. color = (color + ((left + up) >> 1)) & 0xff
  5376. elif filter_type == 4: # Paeth
  5377. a = left
  5378. b = up
  5379. c = 0
  5380. if x > 2 and y > 0:
  5381. c = _get_pixel(basex - stride - 3)
  5382. p = a + b - c
  5383. pa = abs(p - a)
  5384. pb = abs(p - b)
  5385. pc = abs(p - c)
  5386. if pa <= pb and pa <= pc:
  5387. color = (color + a) & 0xff
  5388. elif pb <= pc:
  5389. color = (color + b) & 0xff
  5390. else:
  5391. color = (color + c) & 0xff
  5392. current_row.append(color)
  5393. return width, height, pixels
  5394. def write_xattr(path, key, value):
  5395. # This mess below finds the best xattr tool for the job
  5396. try:
  5397. # try the pyxattr module...
  5398. import xattr
  5399. if hasattr(xattr, 'set'): # pyxattr
  5400. # Unicode arguments are not supported in python-pyxattr until
  5401. # version 0.5.0
  5402. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  5403. pyxattr_required_version = '0.5.0'
  5404. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  5405. # TODO: fallback to CLI tools
  5406. raise XAttrUnavailableError(
  5407. 'python-pyxattr is detected but is too old. '
  5408. 'youtube-dl requires %s or above while your version is %s. '
  5409. 'Falling back to other xattr implementations' % (
  5410. pyxattr_required_version, xattr.__version__))
  5411. setxattr = xattr.set
  5412. else: # xattr
  5413. setxattr = xattr.setxattr
  5414. try:
  5415. setxattr(path, key, value)
  5416. except EnvironmentError as e:
  5417. raise XAttrMetadataError(e.errno, e.strerror)
  5418. except ImportError:
  5419. if compat_os_name == 'nt':
  5420. # Write xattrs to NTFS Alternate Data Streams:
  5421. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  5422. assert ':' not in key
  5423. assert os.path.exists(path)
  5424. ads_fn = path + ':' + key
  5425. try:
  5426. with open(ads_fn, 'wb') as f:
  5427. f.write(value)
  5428. except EnvironmentError as e:
  5429. raise XAttrMetadataError(e.errno, e.strerror)
  5430. else:
  5431. user_has_setfattr = check_executable('setfattr', ['--version'])
  5432. user_has_xattr = check_executable('xattr', ['-h'])
  5433. if user_has_setfattr or user_has_xattr:
  5434. value = value.decode('utf-8')
  5435. if user_has_setfattr:
  5436. executable = 'setfattr'
  5437. opts = ['-n', key, '-v', value]
  5438. elif user_has_xattr:
  5439. executable = 'xattr'
  5440. opts = ['-w', key, value]
  5441. cmd = ([encodeFilename(executable, True)]
  5442. + [encodeArgument(o) for o in opts]
  5443. + [encodeFilename(path, True)])
  5444. try:
  5445. p = subprocess.Popen(
  5446. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5447. except EnvironmentError as e:
  5448. raise XAttrMetadataError(e.errno, e.strerror)
  5449. stdout, stderr = process_communicate_or_kill(p)
  5450. stderr = stderr.decode('utf-8', 'replace')
  5451. if p.returncode != 0:
  5452. raise XAttrMetadataError(p.returncode, stderr)
  5453. else:
  5454. # On Unix, and can't find pyxattr, setfattr, or xattr.
  5455. if sys.platform.startswith('linux'):
  5456. raise XAttrUnavailableError(
  5457. "Couldn't find a tool to set the xattrs. "
  5458. "Install either the python 'pyxattr' or 'xattr' "
  5459. "modules, or the GNU 'attr' package "
  5460. "(which contains the 'setfattr' tool).")
  5461. else:
  5462. raise XAttrUnavailableError(
  5463. "Couldn't find a tool to set the xattrs. "
  5464. "Install either the python 'xattr' module, "
  5465. "or the 'xattr' binary.")
  5466. def random_birthday(year_field, month_field, day_field):
  5467. start_date = datetime.date(1950, 1, 1)
  5468. end_date = datetime.date(1995, 12, 31)
  5469. offset = random.randint(0, (end_date - start_date).days)
  5470. random_date = start_date + datetime.timedelta(offset)
  5471. return {
  5472. year_field: str(random_date.year),
  5473. month_field: str(random_date.month),
  5474. day_field: str(random_date.day),
  5475. }
  5476. def clean_podcast_url(url):
  5477. return re.sub(r'''(?x)
  5478. (?:
  5479. (?:
  5480. chtbl\.com/track|
  5481. media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
  5482. play\.podtrac\.com
  5483. )/[^/]+|
  5484. (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
  5485. flex\.acast\.com|
  5486. pd(?:
  5487. cn\.co| # https://podcorn.com/analytics-prefix/
  5488. st\.fm # https://podsights.com/docs/
  5489. )/e
  5490. )/''', '', url)
  5491. if __debug__:
  5492. # Raise TypeError if args can't be bound
  5493. # needs compat owing to unstable inspect API, thanks PSF :-(
  5494. try:
  5495. inspect.signature
  5496. def _try_bind_args(fn, *args, **kwargs):
  5497. inspect.signature(fn).bind(*args, **kwargs)
  5498. except AttributeError:
  5499. # Py < 3.3
  5500. def _try_bind_args(fn, *args, **kwargs):
  5501. fn_args = inspect.getargspec(fn)
  5502. # Py2: ArgInfo(args, varargs, keywords, defaults)
  5503. # Py3: ArgSpec(args, varargs, keywords, defaults)
  5504. if not fn_args.keywords:
  5505. for k in kwargs:
  5506. if k not in (fn_args.args or []):
  5507. raise TypeError("got an unexpected keyword argument: '{0}'".format(k))
  5508. if not fn_args.varargs:
  5509. args_to_bind = len(args)
  5510. bindable = len(fn_args.args or [])
  5511. if args_to_bind > bindable:
  5512. raise TypeError('too many positional arguments')
  5513. bindable -= len(fn_args.defaults or [])
  5514. if args_to_bind < bindable:
  5515. if kwargs:
  5516. bindable -= len(set(fn_args.args or []) & set(kwargs))
  5517. if bindable > args_to_bind:
  5518. raise TypeError("missing a required argument: '{0}'".format(fn_args.args[args_to_bind]))
  5519. def traverse_obj(obj, *paths, **kwargs):
  5520. """
  5521. Safely traverse nested `dict`s and `Iterable`s, etc
  5522. >>> obj = [{}, {"key": "value"}]
  5523. >>> traverse_obj(obj, (1, "key"))
  5524. 'value'
  5525. Each of the provided `paths` is tested and the first producing a valid result will be returned.
  5526. The next path will also be tested if the path branched but no results could be found.
  5527. Supported values for traversal are `Mapping`, `Iterable`, `re.Match`, `xml.etree.ElementTree`
  5528. (xpath) and `http.cookies.Morsel`.
  5529. Unhelpful values (`{}`, `None`) are treated as the absence of a value and discarded.
  5530. The paths will be wrapped in `variadic`, so that `'key'` is conveniently the same as `('key', )`.
  5531. The keys in the path can be one of:
  5532. - `None`: Return the current object.
  5533. - `set`: Requires the only item in the set to be a type or function,
  5534. like `{type}`/`{type, type, ...}`/`{func}`. If one or more `type`s,
  5535. return only values that have one of the types. If a function,
  5536. return `func(obj)`.
  5537. - `str`/`int`: Return `obj[key]`. For `re.Match`, return `obj.group(key)`.
  5538. - `slice`: Branch out and return all values in `obj[key]`.
  5539. - `Ellipsis`: Branch out and return a list of all values.
  5540. - `tuple`/`list`: Branch out and return a list of all matching values.
  5541. Read as: `[traverse_obj(obj, branch) for branch in branches]`.
  5542. - `function`: Branch out and return values filtered by the function.
  5543. Read as: `[value for key, value in obj if function(key, value)]`.
  5544. For `Sequence`s, `key` is the index of the value.
  5545. For `Iterable`s, `key` is the enumeration count of the value.
  5546. For `re.Match`es, `key` is the group number (0 = full match)
  5547. as well as additionally any group names, if given.
  5548. - `dict`: Transform the current object and return a matching dict.
  5549. Read as: `{key: traverse_obj(obj, path) for key, path in dct.items()}`.
  5550. - `any`-builtin: Take the first matching object and return it, resetting branching.
  5551. - `all`-builtin: Take all matching objects and return them as a list, resetting branching.
  5552. - `filter`-builtin: Return the value if it is truthy, `None` otherwise.
  5553. `tuple`, `list`, and `dict` all support nested paths and branches.
  5554. @params paths Paths which to traverse by.
  5555. Keyword arguments:
  5556. @param default Value to return if the paths do not match.
  5557. If the last key in the path is a `dict`, it will apply to each value inside
  5558. the dict instead, depth first. Try to avoid if using nested `dict` keys.
  5559. @param expected_type If a `type`, only accept final values of this type.
  5560. If any other callable, try to call the function on each result.
  5561. If the last key in the path is a `dict`, it will apply to each value inside
  5562. the dict instead, recursively. This does respect branching paths.
  5563. @param get_all If `False`, return the first matching result, otherwise all matching ones.
  5564. @param casesense If `False`, consider string dictionary keys as case insensitive.
  5565. The following is only meant to be used by YoutubeDL.prepare_outtmpl and is not part of the API
  5566. @param _traverse_string Whether to traverse into objects as strings.
  5567. If `True`, any non-compatible object will first be
  5568. converted into a string and then traversed into.
  5569. The return value of that path will be a string instead,
  5570. not respecting any further branching.
  5571. @returns The result of the object traversal.
  5572. If successful, `get_all=True`, and the path branches at least once,
  5573. then a list of results is returned instead.
  5574. A list is always returned if the last path branches and no `default` is given.
  5575. If a path ends on a `dict` that result will always be a `dict`.
  5576. """
  5577. # parameter defaults
  5578. default = kwargs.get('default', NO_DEFAULT)
  5579. expected_type = kwargs.get('expected_type')
  5580. get_all = kwargs.get('get_all', True)
  5581. casesense = kwargs.get('casesense', True)
  5582. _traverse_string = kwargs.get('_traverse_string', False)
  5583. # instant compat
  5584. str = compat_str
  5585. casefold = lambda k: compat_casefold(k) if isinstance(k, str) else k
  5586. if isinstance(expected_type, type):
  5587. type_test = lambda val: val if isinstance(val, expected_type) else None
  5588. else:
  5589. type_test = lambda val: try_call(expected_type or IDENTITY, args=(val,))
  5590. def lookup_or_none(v, k, getter=None):
  5591. with compat_contextlib_suppress(LookupError):
  5592. return getter(v, k) if getter else v[k]
  5593. def from_iterable(iterables):
  5594. # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
  5595. for it in iterables:
  5596. for item in it:
  5597. yield item
  5598. def apply_key(key, obj, is_last):
  5599. branching = False
  5600. if obj is None and _traverse_string:
  5601. if key is Ellipsis or callable(key) or isinstance(key, slice):
  5602. branching = True
  5603. result = ()
  5604. else:
  5605. result = None
  5606. elif key is None:
  5607. result = obj
  5608. elif isinstance(key, set):
  5609. assert len(key) >= 1, 'At least one item is required in a `set` key'
  5610. if all(isinstance(item, type) for item in key):
  5611. result = obj if isinstance(obj, tuple(key)) else None
  5612. else:
  5613. item = next(iter(key))
  5614. assert len(key) == 1, 'Multiple items in a `set` key must all be types'
  5615. result = try_call(item, args=(obj,)) if not isinstance(item, type) else None
  5616. elif isinstance(key, (list, tuple)):
  5617. branching = True
  5618. result = from_iterable(
  5619. apply_path(obj, branch, is_last)[0] for branch in key)
  5620. elif key is Ellipsis:
  5621. branching = True
  5622. if isinstance(obj, compat_http_cookies.Morsel):
  5623. obj = dict(obj, key=obj.key, value=obj.value)
  5624. if isinstance(obj, compat_collections_abc.Mapping):
  5625. result = obj.values()
  5626. elif is_iterable_like(obj, (compat_collections_abc.Iterable, compat_etree_Element)):
  5627. result = obj
  5628. elif isinstance(obj, compat_re_Match):
  5629. result = obj.groups()
  5630. elif _traverse_string:
  5631. branching = False
  5632. result = str(obj)
  5633. else:
  5634. result = ()
  5635. elif callable(key):
  5636. branching = True
  5637. if isinstance(obj, compat_http_cookies.Morsel):
  5638. obj = dict(obj, key=obj.key, value=obj.value)
  5639. if isinstance(obj, compat_collections_abc.Mapping):
  5640. iter_obj = obj.items()
  5641. elif is_iterable_like(obj, (compat_collections_abc.Iterable, compat_etree_Element)):
  5642. iter_obj = enumerate(obj)
  5643. elif isinstance(obj, compat_re_Match):
  5644. iter_obj = itertools.chain(
  5645. enumerate(itertools.chain((obj.group(),), obj.groups())),
  5646. obj.groupdict().items())
  5647. elif _traverse_string:
  5648. branching = False
  5649. iter_obj = enumerate(str(obj))
  5650. else:
  5651. iter_obj = ()
  5652. result = (v for k, v in iter_obj if try_call(key, args=(k, v)))
  5653. if not branching: # string traversal
  5654. result = ''.join(result)
  5655. elif isinstance(key, dict):
  5656. iter_obj = ((k, _traverse_obj(obj, v, False, is_last)) for k, v in key.items())
  5657. result = dict((k, v if v is not None else default) for k, v in iter_obj
  5658. if v is not None or default is not NO_DEFAULT) or None
  5659. elif isinstance(obj, compat_collections_abc.Mapping):
  5660. if isinstance(obj, compat_http_cookies.Morsel):
  5661. obj = dict(obj, key=obj.key, value=obj.value)
  5662. result = (try_call(obj.get, args=(key,))
  5663. if casesense or try_call(obj.__contains__, args=(key,))
  5664. else next((v for k, v in obj.items() if casefold(k) == key), None))
  5665. elif isinstance(obj, compat_re_Match):
  5666. result = None
  5667. if isinstance(key, int) or casesense:
  5668. # Py 2.6 doesn't have methods in the Match class/type
  5669. result = lookup_or_none(obj, key, getter=lambda _, k: obj.group(k))
  5670. elif isinstance(key, str):
  5671. result = next((v for k, v in obj.groupdict().items()
  5672. if casefold(k) == key), None)
  5673. else:
  5674. result = None
  5675. if isinstance(key, (int, slice)):
  5676. if is_iterable_like(obj, (compat_collections_abc.Sequence, compat_etree_Element)):
  5677. branching = isinstance(key, slice)
  5678. result = lookup_or_none(obj, key)
  5679. elif _traverse_string:
  5680. result = lookup_or_none(str(obj), key)
  5681. elif isinstance(obj, compat_etree_Element) and isinstance(key, str):
  5682. xpath, _, special = key.rpartition('/')
  5683. if not special.startswith('@') and not special.endswith('()'):
  5684. xpath = key
  5685. special = None
  5686. # Allow abbreviations of relative paths, absolute paths error
  5687. if xpath.startswith('/'):
  5688. xpath = '.' + xpath
  5689. elif xpath and not xpath.startswith('./'):
  5690. xpath = './' + xpath
  5691. def apply_specials(element):
  5692. if special is None:
  5693. return element
  5694. if special == '@':
  5695. return element.attrib
  5696. if special.startswith('@'):
  5697. return try_call(element.attrib.get, args=(special[1:],))
  5698. if special == 'text()':
  5699. return element.text
  5700. raise SyntaxError('apply_specials is missing case for {0!r}'.format(special))
  5701. if xpath:
  5702. result = list(map(apply_specials, compat_etree_iterfind(obj, xpath)))
  5703. else:
  5704. result = apply_specials(obj)
  5705. return branching, result if branching else (result,)
  5706. def lazy_last(iterable):
  5707. iterator = iter(iterable)
  5708. prev = next(iterator, NO_DEFAULT)
  5709. if prev is NO_DEFAULT:
  5710. return
  5711. for item in iterator:
  5712. yield False, prev
  5713. prev = item
  5714. yield True, prev
  5715. def apply_path(start_obj, path, test_type):
  5716. objs = (start_obj,)
  5717. has_branched = False
  5718. key = None
  5719. for last, key in lazy_last(variadic(path, (str, bytes, dict, set))):
  5720. if not casesense and isinstance(key, str):
  5721. key = compat_casefold(key)
  5722. if key in (any, all):
  5723. has_branched = False
  5724. filtered_objs = (obj for obj in objs if obj not in (None, {}))
  5725. if key is any:
  5726. objs = (next(filtered_objs, None),)
  5727. else:
  5728. objs = (list(filtered_objs),)
  5729. continue
  5730. # filter might be from __builtin__, future_builtins, or itertools.ifilter
  5731. if key in compat_filter_fns:
  5732. objs = filter(None, objs)
  5733. continue
  5734. if __debug__ and callable(key):
  5735. # Verify function signature
  5736. _try_bind_args(key, None, None)
  5737. new_objs = []
  5738. for obj in objs:
  5739. branching, results = apply_key(key, obj, last)
  5740. has_branched |= branching
  5741. new_objs.append(results)
  5742. objs = from_iterable(new_objs)
  5743. if test_type and not isinstance(key, (dict, list, tuple)):
  5744. objs = map(type_test, objs)
  5745. return objs, has_branched, isinstance(key, dict)
  5746. def _traverse_obj(obj, path, allow_empty, test_type):
  5747. results, has_branched, is_dict = apply_path(obj, path, test_type)
  5748. results = LazyList(x for x in results if x not in (None, {}))
  5749. if get_all and has_branched:
  5750. if results:
  5751. return results.exhaust()
  5752. if allow_empty:
  5753. return [] if default is NO_DEFAULT else default
  5754. return None
  5755. return results[0] if results else {} if allow_empty and is_dict else None
  5756. for index, path in enumerate(paths, 1):
  5757. result = _traverse_obj(obj, path, index == len(paths), True)
  5758. if result is not None:
  5759. return result
  5760. return None if default is NO_DEFAULT else default
  5761. def T(*x):
  5762. """ For use in yt-dl instead of {type, ...} or set((type, ...)) """
  5763. return set(x)
  5764. def get_first(obj, keys, **kwargs):
  5765. return traverse_obj(obj, (Ellipsis,) + tuple(variadic(keys)), get_all=False, **kwargs)
  5766. def join_nonempty(*values, **kwargs):
  5767. # parameter defaults
  5768. delim = kwargs.get('delim', '-')
  5769. from_dict = kwargs.get('from_dict')
  5770. if from_dict is not None:
  5771. values = (traverse_obj(from_dict, variadic(v)) for v in values)
  5772. return delim.join(map(compat_str, filter(None, values)))
  5773. class Namespace(object):
  5774. """Immutable namespace"""
  5775. def __init__(self, **kw_attr):
  5776. self.__dict__.update(kw_attr)
  5777. def __iter__(self):
  5778. return iter(self.__dict__.values())
  5779. @property
  5780. def items_(self):
  5781. return self.__dict__.items()
  5782. MEDIA_EXTENSIONS = Namespace(
  5783. common_video=('avi', 'flv', 'mkv', 'mov', 'mp4', 'webm'),
  5784. video=('3g2', '3gp', 'f4v', 'mk3d', 'divx', 'mpg', 'ogv', 'm4v', 'wmv'),
  5785. common_audio=('aiff', 'alac', 'flac', 'm4a', 'mka', 'mp3', 'ogg', 'opus', 'wav'),
  5786. audio=('aac', 'ape', 'asf', 'f4a', 'f4b', 'm4b', 'm4p', 'm4r', 'oga', 'ogx', 'spx', 'vorbis', 'wma', 'weba'),
  5787. thumbnails=('jpg', 'png', 'webp'),
  5788. # storyboards=('mhtml', ),
  5789. subtitles=('srt', 'vtt', 'ass', 'lrc', 'ttml'),
  5790. manifests=('f4f', 'f4m', 'm3u8', 'smil', 'mpd'),
  5791. )
  5792. MEDIA_EXTENSIONS.video = MEDIA_EXTENSIONS.common_video + MEDIA_EXTENSIONS.video
  5793. MEDIA_EXTENSIONS.audio = MEDIA_EXTENSIONS.common_audio + MEDIA_EXTENSIONS.audio
  5794. KNOWN_EXTENSIONS = (
  5795. MEDIA_EXTENSIONS.video + MEDIA_EXTENSIONS.audio
  5796. + MEDIA_EXTENSIONS.manifests
  5797. )
  5798. class _UnsafeExtensionError(Exception):
  5799. """
  5800. Mitigation exception for unwanted file overwrite/path traversal
  5801. Ref: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-79w7-vh3h-8g4j
  5802. """
  5803. _ALLOWED_EXTENSIONS = frozenset(itertools.chain(
  5804. ( # internal
  5805. 'description',
  5806. 'json',
  5807. 'meta',
  5808. 'orig',
  5809. 'part',
  5810. 'temp',
  5811. 'uncut',
  5812. 'unknown_video',
  5813. 'ytdl',
  5814. ),
  5815. # video
  5816. MEDIA_EXTENSIONS.video, (
  5817. 'asx',
  5818. 'ismv',
  5819. 'm2t',
  5820. 'm2ts',
  5821. 'm2v',
  5822. 'm4s',
  5823. 'mng',
  5824. 'mp2v',
  5825. 'mp4v',
  5826. 'mpe',
  5827. 'mpeg',
  5828. 'mpeg1',
  5829. 'mpeg2',
  5830. 'mpeg4',
  5831. 'mxf',
  5832. 'ogm',
  5833. 'qt',
  5834. 'rm',
  5835. 'swf',
  5836. 'ts',
  5837. 'vob',
  5838. 'vp9',
  5839. ),
  5840. # audio
  5841. MEDIA_EXTENSIONS.audio, (
  5842. '3ga',
  5843. 'ac3',
  5844. 'adts',
  5845. 'aif',
  5846. 'au',
  5847. 'dts',
  5848. 'isma',
  5849. 'it',
  5850. 'mid',
  5851. 'mod',
  5852. 'mpga',
  5853. 'mp1',
  5854. 'mp2',
  5855. 'mp4a',
  5856. 'mpa',
  5857. 'ra',
  5858. 'shn',
  5859. 'xm',
  5860. ),
  5861. # image
  5862. MEDIA_EXTENSIONS.thumbnails, (
  5863. 'avif',
  5864. 'bmp',
  5865. 'gif',
  5866. 'ico',
  5867. 'heic',
  5868. 'jng',
  5869. 'jpeg',
  5870. 'jxl',
  5871. 'svg',
  5872. 'tif',
  5873. 'tiff',
  5874. 'wbmp',
  5875. ),
  5876. # subtitle
  5877. MEDIA_EXTENSIONS.subtitles, (
  5878. 'dfxp',
  5879. 'fs',
  5880. 'ismt',
  5881. 'json3',
  5882. 'sami',
  5883. 'scc',
  5884. 'srv1',
  5885. 'srv2',
  5886. 'srv3',
  5887. 'ssa',
  5888. 'tt',
  5889. 'xml',
  5890. ),
  5891. # others
  5892. MEDIA_EXTENSIONS.manifests,
  5893. (
  5894. # not used in yt-dl
  5895. # *MEDIA_EXTENSIONS.storyboards,
  5896. # 'desktop',
  5897. # 'ism',
  5898. # 'm3u',
  5899. # 'sbv',
  5900. # 'swp',
  5901. # 'url',
  5902. # 'webloc',
  5903. )))
  5904. def __init__(self, extension):
  5905. super(_UnsafeExtensionError, self).__init__('unsafe file extension: {0!r}'.format(extension))
  5906. self.extension = extension
  5907. # support --no-check-extensions
  5908. lenient = False
  5909. @classmethod
  5910. def sanitize_extension(cls, extension, **kwargs):
  5911. # ... /, *, prepend=False
  5912. prepend = kwargs.get('prepend', False)
  5913. if '/' in extension or '\\' in extension:
  5914. raise cls(extension)
  5915. if not prepend:
  5916. last = extension.rpartition('.')[-1]
  5917. if last == 'bin':
  5918. extension = last = 'unknown_video'
  5919. if not (cls.lenient or last.lower() in cls._ALLOWED_EXTENSIONS):
  5920. raise cls(extension)
  5921. return extension