utils.py 197 KB

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