utils.py 187 KB

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