utils.py 200 KB

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