utils.py 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563
  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. KNOWN_EXTENSIONS = (
  1701. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  1702. 'flv', 'f4v', 'f4a', 'f4b',
  1703. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  1704. 'mkv', 'mka', 'mk3d',
  1705. 'avi', 'divx',
  1706. 'mov',
  1707. 'asf', 'wmv', 'wma',
  1708. '3gp', '3g2',
  1709. 'mp3',
  1710. 'flac',
  1711. 'ape',
  1712. 'wav',
  1713. 'f4f', 'f4m', 'm3u8', 'smil')
  1714. # needed for sanitizing filenames in restricted mode
  1715. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  1716. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  1717. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  1718. DATE_FORMATS = (
  1719. '%d %B %Y',
  1720. '%d %b %Y',
  1721. '%B %d %Y',
  1722. '%B %dst %Y',
  1723. '%B %dnd %Y',
  1724. '%B %drd %Y',
  1725. '%B %dth %Y',
  1726. '%b %d %Y',
  1727. '%b %dst %Y',
  1728. '%b %dnd %Y',
  1729. '%b %drd %Y',
  1730. '%b %dth %Y',
  1731. '%b %dst %Y %I:%M',
  1732. '%b %dnd %Y %I:%M',
  1733. '%b %drd %Y %I:%M',
  1734. '%b %dth %Y %I:%M',
  1735. '%Y %m %d',
  1736. '%Y-%m-%d',
  1737. '%Y.%m.%d.',
  1738. '%Y/%m/%d',
  1739. '%Y/%m/%d %H:%M',
  1740. '%Y/%m/%d %H:%M:%S',
  1741. '%Y%m%d%H%M',
  1742. '%Y%m%d%H%M%S',
  1743. '%Y%m%d',
  1744. '%Y-%m-%d %H:%M',
  1745. '%Y-%m-%d %H:%M:%S',
  1746. '%Y-%m-%d %H:%M:%S.%f',
  1747. '%Y-%m-%d %H:%M:%S:%f',
  1748. '%d.%m.%Y %H:%M',
  1749. '%d.%m.%Y %H.%M',
  1750. '%Y-%m-%dT%H:%M:%SZ',
  1751. '%Y-%m-%dT%H:%M:%S.%fZ',
  1752. '%Y-%m-%dT%H:%M:%S.%f0Z',
  1753. '%Y-%m-%dT%H:%M:%S',
  1754. '%Y-%m-%dT%H:%M:%S.%f',
  1755. '%Y-%m-%dT%H:%M',
  1756. '%b %d %Y at %H:%M',
  1757. '%b %d %Y at %H:%M:%S',
  1758. '%B %d %Y at %H:%M',
  1759. '%B %d %Y at %H:%M:%S',
  1760. '%H:%M %d-%b-%Y',
  1761. )
  1762. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  1763. DATE_FORMATS_DAY_FIRST.extend([
  1764. '%d-%m-%Y',
  1765. '%d.%m.%Y',
  1766. '%d.%m.%y',
  1767. '%d/%m/%Y',
  1768. '%d/%m/%y',
  1769. '%d/%m/%Y %H:%M:%S',
  1770. '%d-%m-%Y %H:%M',
  1771. ])
  1772. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  1773. DATE_FORMATS_MONTH_FIRST.extend([
  1774. '%m-%d-%Y',
  1775. '%m.%d.%Y',
  1776. '%m/%d/%Y',
  1777. '%m/%d/%y',
  1778. '%m/%d/%Y %H:%M:%S',
  1779. ])
  1780. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  1781. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  1782. def preferredencoding():
  1783. """Get preferred encoding.
  1784. Returns the best encoding scheme for the system, based on
  1785. locale.getpreferredencoding() and some further tweaks.
  1786. """
  1787. try:
  1788. pref = locale.getpreferredencoding()
  1789. 'TEST'.encode(pref)
  1790. except Exception:
  1791. pref = 'UTF-8'
  1792. return pref
  1793. def write_json_file(obj, fn):
  1794. """ Encode obj as JSON and write it to fn, atomically if possible """
  1795. fn = encodeFilename(fn)
  1796. if sys.version_info < (3, 0) and sys.platform != 'win32':
  1797. encoding = get_filesystem_encoding()
  1798. # os.path.basename returns a bytes object, but NamedTemporaryFile
  1799. # will fail if the filename contains non-ascii characters unless we
  1800. # use a unicode object
  1801. path_basename = lambda f: os.path.basename(f).decode(encoding)
  1802. # the same for os.path.dirname
  1803. path_dirname = lambda f: os.path.dirname(f).decode(encoding)
  1804. else:
  1805. path_basename = os.path.basename
  1806. path_dirname = os.path.dirname
  1807. args = {
  1808. 'suffix': '.tmp',
  1809. 'prefix': path_basename(fn) + '.',
  1810. 'dir': path_dirname(fn),
  1811. 'delete': False,
  1812. }
  1813. # In Python 2.x, json.dump expects a bytestream.
  1814. # In Python 3.x, it writes to a character stream
  1815. if sys.version_info < (3, 0):
  1816. args['mode'] = 'wb'
  1817. else:
  1818. args.update({
  1819. 'mode': 'w',
  1820. 'encoding': 'utf-8',
  1821. })
  1822. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  1823. try:
  1824. with tf:
  1825. json.dump(obj, tf)
  1826. with compat_contextlib_suppress(OSError):
  1827. if sys.platform == 'win32':
  1828. # Need to remove existing file on Windows, else os.rename raises
  1829. # WindowsError or FileExistsError.
  1830. os.unlink(fn)
  1831. mask = os.umask(0)
  1832. os.umask(mask)
  1833. os.chmod(tf.name, 0o666 & ~mask)
  1834. os.rename(tf.name, fn)
  1835. except Exception:
  1836. with compat_contextlib_suppress(OSError):
  1837. os.remove(tf.name)
  1838. raise
  1839. if sys.version_info >= (2, 7):
  1840. def find_xpath_attr(node, xpath, key, val=None):
  1841. """ Find the xpath xpath[@key=val] """
  1842. assert re.match(r'^[a-zA-Z_-]+$', key)
  1843. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  1844. return node.find(expr)
  1845. else:
  1846. def find_xpath_attr(node, xpath, key, val=None):
  1847. for f in node.findall(compat_xpath(xpath)):
  1848. if key not in f.attrib:
  1849. continue
  1850. if val is None or f.attrib.get(key) == val:
  1851. return f
  1852. return None
  1853. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  1854. # the namespace parameter
  1855. def xpath_with_ns(path, ns_map):
  1856. components = [c.split(':') for c in path.split('/')]
  1857. replaced = []
  1858. for c in components:
  1859. if len(c) == 1:
  1860. replaced.append(c[0])
  1861. else:
  1862. ns, tag = c
  1863. replaced.append('{%s}%s' % (ns_map[ns], tag))
  1864. return '/'.join(replaced)
  1865. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1866. def _find_xpath(xpath):
  1867. return node.find(compat_xpath(xpath))
  1868. if isinstance(xpath, compat_basestring):
  1869. n = _find_xpath(xpath)
  1870. else:
  1871. for xp in xpath:
  1872. n = _find_xpath(xp)
  1873. if n is not None:
  1874. break
  1875. if n is None:
  1876. if default is not NO_DEFAULT:
  1877. return default
  1878. elif fatal:
  1879. name = xpath if name is None else name
  1880. raise ExtractorError('Could not find XML element %s' % name)
  1881. else:
  1882. return None
  1883. return n
  1884. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  1885. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  1886. if n is None or n == default:
  1887. return n
  1888. if n.text is None:
  1889. if default is not NO_DEFAULT:
  1890. return default
  1891. elif fatal:
  1892. name = xpath if name is None else name
  1893. raise ExtractorError('Could not find XML element\'s text %s' % name)
  1894. else:
  1895. return None
  1896. return n.text
  1897. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  1898. n = find_xpath_attr(node, xpath, key)
  1899. if n is None:
  1900. if default is not NO_DEFAULT:
  1901. return default
  1902. elif fatal:
  1903. name = '%s[@%s]' % (xpath, key) if name is None else name
  1904. raise ExtractorError('Could not find XML attribute %s' % name)
  1905. else:
  1906. return None
  1907. return n.attrib[key]
  1908. def get_element_by_id(id, html):
  1909. """Return the content of the tag with the specified ID in the passed HTML document"""
  1910. return get_element_by_attribute('id', id, html)
  1911. def get_element_by_class(class_name, html):
  1912. """Return the content of the first tag with the specified class in the passed HTML document"""
  1913. retval = get_elements_by_class(class_name, html)
  1914. return retval[0] if retval else None
  1915. def get_element_by_attribute(attribute, value, html, escape_value=True):
  1916. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  1917. return retval[0] if retval else None
  1918. def get_elements_by_class(class_name, html):
  1919. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  1920. return get_elements_by_attribute(
  1921. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  1922. html, escape_value=False)
  1923. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  1924. """Return the content of the tag with the specified attribute in the passed HTML document"""
  1925. value = re.escape(value) if escape_value else value
  1926. retlist = []
  1927. for m in re.finditer(r'''(?xs)
  1928. <([a-zA-Z0-9:._-]+)
  1929. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1930. \s+%s=['"]?%s['"]?
  1931. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  1932. \s*>
  1933. (?P<content>.*?)
  1934. </\1>
  1935. ''' % (re.escape(attribute), value), html):
  1936. res = m.group('content')
  1937. if res.startswith('"') or res.startswith("'"):
  1938. res = res[1:-1]
  1939. retlist.append(unescapeHTML(res))
  1940. return retlist
  1941. class HTMLAttributeParser(compat_HTMLParser):
  1942. """Trivial HTML parser to gather the attributes for a single element"""
  1943. def __init__(self):
  1944. self.attrs = {}
  1945. compat_HTMLParser.__init__(self)
  1946. def handle_starttag(self, tag, attrs):
  1947. self.attrs = dict(attrs)
  1948. def extract_attributes(html_element):
  1949. """Given a string for an HTML element such as
  1950. <el
  1951. a="foo" B="bar" c="&98;az" d=boz
  1952. empty= noval entity="&amp;"
  1953. sq='"' dq="'"
  1954. >
  1955. Decode and return a dictionary of attributes.
  1956. {
  1957. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  1958. 'empty': '', 'noval': None, 'entity': '&',
  1959. 'sq': '"', 'dq': '\''
  1960. }.
  1961. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  1962. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  1963. """
  1964. ret = None
  1965. # Older Python may throw HTMLParseError in case of malformed HTML (and on .close()!)
  1966. with compat_contextlib_suppress(compat_HTMLParseError):
  1967. with contextlib.closing(HTMLAttributeParser()) as parser:
  1968. parser.feed(html_element)
  1969. ret = parser.attrs
  1970. return ret or {}
  1971. def clean_html(html):
  1972. """Clean an HTML snippet into a readable string"""
  1973. if html is None: # Convenience for sanitizing descriptions etc.
  1974. return html
  1975. # Newline vs <br />
  1976. html = html.replace('\n', ' ')
  1977. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  1978. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  1979. # Strip html tags
  1980. html = re.sub('<.*?>', '', html)
  1981. # Replace html entities
  1982. html = unescapeHTML(html)
  1983. return html.strip()
  1984. def sanitize_open(filename, open_mode):
  1985. """Try to open the given filename, and slightly tweak it if this fails.
  1986. Attempts to open the given filename. If this fails, it tries to change
  1987. the filename slightly, step by step, until it's either able to open it
  1988. or it fails and raises a final exception, like the standard open()
  1989. function.
  1990. It returns the tuple (stream, definitive_file_name).
  1991. """
  1992. try:
  1993. if filename == '-':
  1994. if sys.platform == 'win32':
  1995. import msvcrt
  1996. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  1997. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  1998. stream = open(encodeFilename(filename), open_mode)
  1999. return (stream, filename)
  2000. except (IOError, OSError) as err:
  2001. if err.errno in (errno.EACCES,):
  2002. raise
  2003. # In case of error, try to remove win32 forbidden chars
  2004. alt_filename = sanitize_path(filename)
  2005. if alt_filename == filename:
  2006. raise
  2007. else:
  2008. # An exception here should be caught in the caller
  2009. stream = open(encodeFilename(alt_filename), open_mode)
  2010. return (stream, alt_filename)
  2011. def timeconvert(timestr):
  2012. """Convert RFC 2822 defined time string into system timestamp"""
  2013. timestamp = None
  2014. timetuple = email.utils.parsedate_tz(timestr)
  2015. if timetuple is not None:
  2016. timestamp = email.utils.mktime_tz(timetuple)
  2017. return timestamp
  2018. def sanitize_filename(s, restricted=False, is_id=False):
  2019. """Sanitizes a string so it could be used as part of a filename.
  2020. If restricted is set, use a stricter subset of allowed characters.
  2021. Set is_id if this is not an arbitrary string, but an ID that should be kept
  2022. if possible.
  2023. """
  2024. def replace_insane(char):
  2025. if restricted and char in ACCENT_CHARS:
  2026. return ACCENT_CHARS[char]
  2027. if char == '?' or ord(char) < 32 or ord(char) == 127:
  2028. return ''
  2029. elif char == '"':
  2030. return '' if restricted else '\''
  2031. elif char == ':':
  2032. return '_-' if restricted else ' -'
  2033. elif char in '\\/|*<>':
  2034. return '_'
  2035. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  2036. return '_'
  2037. if restricted and ord(char) > 127:
  2038. return '' if unicodedata.category(char)[0] in 'CM' else '_'
  2039. return char
  2040. # Replace look-alike Unicode glyphs
  2041. if restricted and not is_id:
  2042. s = unicodedata.normalize('NFKC', s)
  2043. # Handle timestamps
  2044. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  2045. result = ''.join(map(replace_insane, s))
  2046. if not is_id:
  2047. while '__' in result:
  2048. result = result.replace('__', '_')
  2049. result = result.strip('_')
  2050. # Common case of "Foreign band name - English song title"
  2051. if restricted and result.startswith('-_'):
  2052. result = result[2:]
  2053. if result.startswith('-'):
  2054. result = '_' + result[len('-'):]
  2055. result = result.lstrip('.')
  2056. if not result:
  2057. result = '_'
  2058. return result
  2059. def sanitize_path(s):
  2060. """Sanitizes and normalizes path on Windows"""
  2061. if sys.platform != 'win32':
  2062. return s
  2063. drive_or_unc, _ = os.path.splitdrive(s)
  2064. if sys.version_info < (2, 7) and not drive_or_unc:
  2065. drive_or_unc, _ = os.path.splitunc(s)
  2066. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  2067. if drive_or_unc:
  2068. norm_path.pop(0)
  2069. sanitized_path = [
  2070. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  2071. for path_part in norm_path]
  2072. if drive_or_unc:
  2073. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  2074. return os.path.join(*sanitized_path)
  2075. def sanitize_url(url):
  2076. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  2077. # the number of unwanted failures due to missing protocol
  2078. if url.startswith('//'):
  2079. return 'http:%s' % url
  2080. # Fix some common typos seen so far
  2081. COMMON_TYPOS = (
  2082. # https://github.com/ytdl-org/youtube-dl/issues/15649
  2083. (r'^httpss://', r'https://'),
  2084. # https://bx1.be/lives/direct-tv/
  2085. (r'^rmtp([es]?)://', r'rtmp\1://'),
  2086. )
  2087. for mistake, fixup in COMMON_TYPOS:
  2088. if re.match(mistake, url):
  2089. return re.sub(mistake, fixup, url)
  2090. return url
  2091. def extract_basic_auth(url):
  2092. parts = compat_urllib_parse.urlsplit(url)
  2093. if parts.username is None:
  2094. return url, None
  2095. url = compat_urllib_parse.urlunsplit(parts._replace(netloc=(
  2096. parts.hostname if parts.port is None
  2097. else '%s:%d' % (parts.hostname, parts.port))))
  2098. auth_payload = base64.b64encode(
  2099. ('%s:%s' % (parts.username, parts.password or '')).encode('utf-8'))
  2100. return url, 'Basic {0}'.format(auth_payload.decode('ascii'))
  2101. def sanitized_Request(url, *args, **kwargs):
  2102. url, auth_header = extract_basic_auth(escape_url(sanitize_url(url)))
  2103. if auth_header is not None:
  2104. headers = args[1] if len(args) > 1 else kwargs.get('headers')
  2105. headers = headers or {}
  2106. headers['Authorization'] = auth_header
  2107. if len(args) <= 1 and kwargs.get('headers') is None:
  2108. kwargs['headers'] = headers
  2109. kwargs = compat_kwargs(kwargs)
  2110. return compat_urllib_request.Request(url, *args, **kwargs)
  2111. def expand_path(s):
  2112. """Expand shell variables and ~"""
  2113. return os.path.expandvars(compat_expanduser(s))
  2114. def orderedSet(iterable):
  2115. """ Remove all duplicates from the input iterable """
  2116. res = []
  2117. for el in iterable:
  2118. if el not in res:
  2119. res.append(el)
  2120. return res
  2121. def _htmlentity_transform(entity_with_semicolon):
  2122. """Transforms an HTML entity to a character."""
  2123. entity = entity_with_semicolon[:-1]
  2124. # Known non-numeric HTML entity
  2125. if entity in compat_html_entities.name2codepoint:
  2126. return compat_chr(compat_html_entities.name2codepoint[entity])
  2127. # TODO: HTML5 allows entities without a semicolon. For example,
  2128. # '&Eacuteric' should be decoded as 'Éric'.
  2129. if entity_with_semicolon in compat_html_entities_html5:
  2130. return compat_html_entities_html5[entity_with_semicolon]
  2131. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  2132. if mobj is not None:
  2133. numstr = mobj.group(1)
  2134. if numstr.startswith('x'):
  2135. base = 16
  2136. numstr = '0%s' % numstr
  2137. else:
  2138. base = 10
  2139. # See https://github.com/ytdl-org/youtube-dl/issues/7518\
  2140. # Also, weirdly, compat_contextlib_suppress fails here in 2.6
  2141. try:
  2142. return compat_chr(int(numstr, base))
  2143. except ValueError:
  2144. pass
  2145. # Unknown entity in name, return its literal representation
  2146. return '&%s;' % entity
  2147. def unescapeHTML(s):
  2148. if s is None:
  2149. return None
  2150. assert isinstance(s, compat_str)
  2151. return re.sub(
  2152. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  2153. def process_communicate_or_kill(p, *args, **kwargs):
  2154. try:
  2155. return p.communicate(*args, **kwargs)
  2156. except BaseException: # Including KeyboardInterrupt
  2157. p.kill()
  2158. p.wait()
  2159. raise
  2160. def get_subprocess_encoding():
  2161. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  2162. # For subprocess calls, encode with locale encoding
  2163. # Refer to http://stackoverflow.com/a/9951851/35070
  2164. encoding = preferredencoding()
  2165. else:
  2166. encoding = sys.getfilesystemencoding()
  2167. if encoding is None:
  2168. encoding = 'utf-8'
  2169. return encoding
  2170. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  2171. if sys.version_info < (3, 0) and not sys.platform.startswith('java'):
  2172. def encodeFilename(s, for_subprocess=False):
  2173. """
  2174. @param s The name of the file
  2175. """
  2176. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  2177. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  2178. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  2179. if (not for_subprocess
  2180. and sys.platform == 'win32'
  2181. and sys.getwindowsversion()[0] >= 5
  2182. and isinstance(s, compat_str)):
  2183. return s
  2184. return _encode_compat_str(s, get_subprocess_encoding(), 'ignore')
  2185. def decodeFilename(b, for_subprocess=False):
  2186. return _decode_compat_str(b, get_subprocess_encoding(), 'ignore')
  2187. else:
  2188. # Python 3 has a Unicode API
  2189. encodeFilename = decodeFilename = lambda *s, **k: s[0]
  2190. def encodeArgument(s):
  2191. if not isinstance(s, compat_str):
  2192. # Legacy code that uses byte strings
  2193. # Uncomment the following line after fixing all post processors
  2194. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  2195. s = s.decode('ascii')
  2196. return encodeFilename(s, True)
  2197. def decodeArgument(b):
  2198. return decodeFilename(b, True)
  2199. def decodeOption(optval):
  2200. if optval is None:
  2201. return optval
  2202. return _decode_compat_str(optval)
  2203. def formatSeconds(secs):
  2204. if secs > 3600:
  2205. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  2206. elif secs > 60:
  2207. return '%d:%02d' % (secs // 60, secs % 60)
  2208. else:
  2209. return '%d' % secs
  2210. def make_HTTPS_handler(params, **kwargs):
  2211. # https://www.rfc-editor.org/info/rfc7301
  2212. ALPN_PROTOCOLS = ['http/1.1']
  2213. def set_alpn_protocols(ctx):
  2214. # From https://github.com/yt-dlp/yt-dlp/commit/2c6dcb65fb612fc5bc5c61937bf438d3c473d8d0
  2215. # Thanks @coletdjnz
  2216. # Some servers may (wrongly) reject requests if ALPN extension is not sent. See:
  2217. # https://github.com/python/cpython/issues/85140
  2218. # https://github.com/yt-dlp/yt-dlp/issues/3878
  2219. with compat_contextlib_suppress(AttributeError, NotImplementedError):
  2220. # fails for Python < 2.7.10, not ssl.HAS_ALPN
  2221. ctx.set_alpn_protocols(ALPN_PROTOCOLS)
  2222. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2223. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2224. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2225. set_alpn_protocols(context)
  2226. if opts_no_check_certificate:
  2227. context.check_hostname = False
  2228. context.verify_mode = ssl.CERT_NONE
  2229. with compat_contextlib_suppress(TypeError):
  2230. # Fails with Python 2.7.8 (create_default_context present
  2231. # but HTTPSHandler has no context=)
  2232. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2233. if sys.version_info < (3, 2):
  2234. return YoutubeDLHTTPSHandler(params, **kwargs)
  2235. else: # Python3 < 3.4
  2236. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2237. context.verify_mode = (ssl.CERT_NONE
  2238. if opts_no_check_certificate
  2239. else ssl.CERT_REQUIRED)
  2240. context.set_default_verify_paths()
  2241. set_alpn_protocols(context)
  2242. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2243. def bug_reports_message(before=';'):
  2244. if ytdl_is_updateable():
  2245. update_cmd = 'type youtube-dl -U to update'
  2246. else:
  2247. update_cmd = 'see https://github.com/ytdl-org/youtube-dl/#user-content-installation on how to update'
  2248. msg = (
  2249. 'please report this issue on https://github.com/ytdl-org/youtube-dl/issues ,'
  2250. ' using the appropriate issue template.'
  2251. ' Make sure you are using the latest version; %s.'
  2252. ' Be sure to call youtube-dl with the --verbose option and include the complete output.'
  2253. ) % update_cmd
  2254. before = (before or '').rstrip()
  2255. if not before or before.endswith(('.', '!', '?')):
  2256. msg = msg[0].title() + msg[1:]
  2257. return (before + ' ' if before else '') + msg
  2258. class YoutubeDLError(Exception):
  2259. """Base exception for YoutubeDL errors."""
  2260. pass
  2261. class ExtractorError(YoutubeDLError):
  2262. """Error during info extraction."""
  2263. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2264. """ tb, if given, is the original traceback (so that it can be printed out).
  2265. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2266. """
  2267. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2268. expected = True
  2269. if video_id is not None:
  2270. msg = video_id + ': ' + msg
  2271. if cause:
  2272. msg += ' (caused by %r)' % cause
  2273. if not expected:
  2274. msg += bug_reports_message()
  2275. super(ExtractorError, self).__init__(msg)
  2276. self.traceback = tb
  2277. self.exc_info = sys.exc_info() # preserve original exception
  2278. self.cause = cause
  2279. self.video_id = video_id
  2280. def format_traceback(self):
  2281. if self.traceback is None:
  2282. return None
  2283. return ''.join(traceback.format_tb(self.traceback))
  2284. class UnsupportedError(ExtractorError):
  2285. def __init__(self, url):
  2286. super(UnsupportedError, self).__init__(
  2287. 'Unsupported URL: %s' % url, expected=True)
  2288. self.url = url
  2289. class RegexNotFoundError(ExtractorError):
  2290. """Error when a regex didn't match"""
  2291. pass
  2292. class GeoRestrictedError(ExtractorError):
  2293. """Geographic restriction Error exception.
  2294. This exception may be thrown when a video is not available from your
  2295. geographic location due to geographic restrictions imposed by a website.
  2296. """
  2297. def __init__(self, msg, countries=None):
  2298. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2299. self.msg = msg
  2300. self.countries = countries
  2301. class DownloadError(YoutubeDLError):
  2302. """Download Error exception.
  2303. This exception may be thrown by FileDownloader objects if they are not
  2304. configured to continue on errors. They will contain the appropriate
  2305. error message.
  2306. """
  2307. def __init__(self, msg, exc_info=None):
  2308. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2309. super(DownloadError, self).__init__(msg)
  2310. self.exc_info = exc_info
  2311. class SameFileError(YoutubeDLError):
  2312. """Same File exception.
  2313. This exception will be thrown by FileDownloader objects if they detect
  2314. multiple files would have to be downloaded to the same file on disk.
  2315. """
  2316. pass
  2317. class PostProcessingError(YoutubeDLError):
  2318. """Post Processing exception.
  2319. This exception may be raised by PostProcessor's .run() method to
  2320. indicate an error in the postprocessing task.
  2321. """
  2322. def __init__(self, msg):
  2323. super(PostProcessingError, self).__init__(msg)
  2324. self.msg = msg
  2325. class MaxDownloadsReached(YoutubeDLError):
  2326. """ --max-downloads limit has been reached. """
  2327. pass
  2328. class UnavailableVideoError(YoutubeDLError):
  2329. """Unavailable Format exception.
  2330. This exception will be thrown when a video is requested
  2331. in a format that is not available for that video.
  2332. """
  2333. pass
  2334. class ContentTooShortError(YoutubeDLError):
  2335. """Content Too Short exception.
  2336. This exception may be raised by FileDownloader objects when a file they
  2337. download is too small for what the server announced first, indicating
  2338. the connection was probably interrupted.
  2339. """
  2340. def __init__(self, downloaded, expected):
  2341. super(ContentTooShortError, self).__init__(
  2342. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2343. )
  2344. # Both in bytes
  2345. self.downloaded = downloaded
  2346. self.expected = expected
  2347. class XAttrMetadataError(YoutubeDLError):
  2348. def __init__(self, code=None, msg='Unknown error'):
  2349. super(XAttrMetadataError, self).__init__(msg)
  2350. self.code = code
  2351. self.msg = msg
  2352. # Parsing code and msg
  2353. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2354. or 'No space left' in self.msg or 'Disk quota exceeded' in self.msg):
  2355. self.reason = 'NO_SPACE'
  2356. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2357. self.reason = 'VALUE_TOO_LONG'
  2358. else:
  2359. self.reason = 'NOT_SUPPORTED'
  2360. class XAttrUnavailableError(YoutubeDLError):
  2361. pass
  2362. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2363. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2364. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2365. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2366. if sys.version_info < (3, 0):
  2367. kwargs['strict'] = True
  2368. hc = http_class(*args, **compat_kwargs(kwargs))
  2369. source_address = ydl_handler._params.get('source_address')
  2370. if source_address is not None:
  2371. # This is to workaround _create_connection() from socket where it will try all
  2372. # address data from getaddrinfo() including IPv6. This filters the result from
  2373. # getaddrinfo() based on the source_address value.
  2374. # This is based on the cpython socket.create_connection() function.
  2375. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2376. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2377. host, port = address
  2378. err = None
  2379. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2380. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2381. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2382. if addrs and not ip_addrs:
  2383. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2384. raise socket.error(
  2385. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2386. % (ip_version, source_address[0]))
  2387. for res in ip_addrs:
  2388. af, socktype, proto, canonname, sa = res
  2389. sock = None
  2390. try:
  2391. sock = socket.socket(af, socktype, proto)
  2392. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2393. sock.settimeout(timeout)
  2394. sock.bind(source_address)
  2395. sock.connect(sa)
  2396. err = None # Explicitly break reference cycle
  2397. return sock
  2398. except socket.error as _:
  2399. err = _
  2400. if sock is not None:
  2401. sock.close()
  2402. if err is not None:
  2403. raise err
  2404. else:
  2405. raise socket.error('getaddrinfo returns an empty list')
  2406. if hasattr(hc, '_create_connection'):
  2407. hc._create_connection = _create_connection
  2408. sa = (source_address, 0)
  2409. if hasattr(hc, 'source_address'): # Python 2.7+
  2410. hc.source_address = sa
  2411. else: # Python 2.6
  2412. def _hc_connect(self, *args, **kwargs):
  2413. sock = _create_connection(
  2414. (self.host, self.port), self.timeout, sa)
  2415. if is_https:
  2416. self.sock = ssl.wrap_socket(
  2417. sock, self.key_file, self.cert_file,
  2418. ssl_version=ssl.PROTOCOL_TLSv1)
  2419. else:
  2420. self.sock = sock
  2421. hc.connect = functools.partial(_hc_connect, hc)
  2422. return hc
  2423. def handle_youtubedl_headers(headers):
  2424. filtered_headers = headers
  2425. if 'Youtubedl-no-compression' in filtered_headers:
  2426. filtered_headers = filter_dict(filtered_headers, cndn=lambda k, _: k.lower() != 'accept-encoding')
  2427. del filtered_headers['Youtubedl-no-compression']
  2428. return filtered_headers
  2429. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2430. """Handler for HTTP requests and responses.
  2431. This class, when installed with an OpenerDirector, automatically adds
  2432. the standard headers to every HTTP request and handles gzipped and
  2433. deflated responses from web servers. If compression is to be avoided in
  2434. a particular request, the original request in the program code only has
  2435. to include the HTTP header "Youtubedl-no-compression", which will be
  2436. removed before making the real request.
  2437. Part of this code was copied from:
  2438. http://techknack.net/python-urllib2-handlers/, archived at
  2439. https://web.archive.org/web/20130527205558/http://techknack.net/python-urllib2-handlers/
  2440. Andrew Rowls, the author of that code, agreed to release it to the
  2441. public domain.
  2442. """
  2443. def __init__(self, params, *args, **kwargs):
  2444. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2445. self._params = params
  2446. def http_open(self, req):
  2447. conn_class = compat_http_client.HTTPConnection
  2448. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2449. if socks_proxy:
  2450. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2451. del req.headers['Ytdl-socks-proxy']
  2452. return self.do_open(functools.partial(
  2453. _create_http_connection, self, conn_class, False),
  2454. req)
  2455. @staticmethod
  2456. def deflate_gz(data):
  2457. try:
  2458. # format:zlib,gzip + windowsize:32768
  2459. return data and zlib.decompress(data, 32 + zlib.MAX_WBITS)
  2460. except zlib.error:
  2461. # raw zlib * windowsize:32768 (RFC 9110: "non-conformant")
  2462. return zlib.decompress(data, -zlib.MAX_WBITS)
  2463. @staticmethod
  2464. def gzip(data):
  2465. from gzip import GzipFile
  2466. def _gzip(data):
  2467. with io.BytesIO(data) as data_buf:
  2468. gz = GzipFile(fileobj=data_buf, mode='rb')
  2469. return gz.read()
  2470. try:
  2471. return _gzip(data)
  2472. except IOError as original_ioerror:
  2473. # There may be junk at the end of the file
  2474. # See http://stackoverflow.com/q/4928560/35070 for details
  2475. for i in range(1, 1024):
  2476. try:
  2477. return _gzip(data[:-i])
  2478. except IOError:
  2479. continue
  2480. else:
  2481. raise original_ioerror
  2482. @staticmethod
  2483. def brotli(data):
  2484. return data and brotli.decompress(data)
  2485. @staticmethod
  2486. def compress(data):
  2487. return data and ncompress.decompress(data)
  2488. @staticmethod
  2489. def _fix_path(url):
  2490. # an embedded /../ or /./ sequence is not automatically handled by urllib2
  2491. # see https://github.com/yt-dlp/yt-dlp/issues/3355
  2492. parsed_url = compat_urllib_parse.urlsplit(url)
  2493. path = parsed_url.path
  2494. if not path.endswith('/'):
  2495. path += '/'
  2496. parts = path.partition('/./')
  2497. if not parts[1]:
  2498. parts = path.partition('/../')
  2499. if parts[1]:
  2500. path = compat_urllib_parse.urljoin(
  2501. parts[0] + parts[1][:1],
  2502. parts[1][1:] + (parts[2] if parsed_url.path.endswith('/') else parts[2][:-1]))
  2503. url = parsed_url._replace(path=path).geturl()
  2504. if '/.' in url:
  2505. # worse, URL path may have initial /../ against RFCs: work-around
  2506. # by stripping such prefixes, like eg Firefox
  2507. path = parsed_url.path + '/'
  2508. while path.startswith('/.'):
  2509. if path.startswith('/../'):
  2510. path = path[3:]
  2511. elif path.startswith('/./'):
  2512. path = path[2:]
  2513. else:
  2514. break
  2515. path = path[:-1]
  2516. if not path.startswith('/') and parsed_url.path.startswith('/'):
  2517. path = '/' + path
  2518. url = parsed_url._replace(path=path).geturl()
  2519. return url
  2520. def http_request(self, req):
  2521. url = req.get_full_url()
  2522. # resolve embedded . and ..
  2523. url_fixed = self._fix_path(url)
  2524. # According to RFC 3986, URLs can not contain non-ASCII characters; however this is not
  2525. # always respected by websites: some tend to give out URLs with non percent-encoded
  2526. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2527. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2528. # To work around aforementioned issue we will replace request's original URL with
  2529. # percent-encoded one
  2530. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2531. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2532. url_escaped = escape_url(url_fixed)
  2533. # Substitute URL if any change after escaping
  2534. if url != url_escaped:
  2535. req = update_Request(req, url=url_escaped)
  2536. for h, v in std_headers.items():
  2537. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2538. # The dict keys are capitalized because of this bug by urllib
  2539. if h.capitalize() not in req.headers:
  2540. req.add_header(h, v)
  2541. # Similarly, 'Accept-encoding'
  2542. if 'Accept-encoding' not in req.headers:
  2543. req.add_header(
  2544. 'Accept-Encoding', join_nonempty(
  2545. 'gzip', 'deflate', brotli and 'br', ncompress and 'compress',
  2546. delim=', '))
  2547. req.headers = handle_youtubedl_headers(req.headers)
  2548. if sys.version_info < (2, 7):
  2549. # avoid possible race where __r_type may be unset
  2550. req.get_type()
  2551. if '#' in req.get_full_url():
  2552. # Python 2.6 is brain-dead when it comes to fragments
  2553. req._Request__original = req._Request__original.partition('#')[0]
  2554. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2555. # Use the totally undocumented AbstractHTTPHandler per
  2556. # https://github.com/yt-dlp/yt-dlp/pull/4158
  2557. return compat_urllib_request.AbstractHTTPHandler.do_request_(self, req)
  2558. def http_response(self, req, resp):
  2559. old_resp = resp
  2560. # Content-Encoding header lists the encodings in order that they were applied [1].
  2561. # To decompress, we simply do the reverse.
  2562. # [1]: https://datatracker.ietf.org/doc/html/rfc9110#name-content-encoding
  2563. decoded_response = None
  2564. decoders = {
  2565. 'gzip': self.deflate_gz,
  2566. 'deflate': self.deflate_gz,
  2567. }
  2568. if brotli:
  2569. decoders['br'] = self.brotli
  2570. if ncompress:
  2571. decoders['compress'] = self.compress
  2572. if sys.platform.startswith('java'):
  2573. # Jython zlib implementation misses gzip
  2574. decoders['gzip'] = self.gzip
  2575. def encodings(hdrs):
  2576. # A header field that allows multiple values can have multiple instances [2].
  2577. # [2]: https://datatracker.ietf.org/doc/html/rfc9110#name-fields
  2578. for e in reversed(','.join(hdrs).split(',')):
  2579. if e:
  2580. yield e.strip()
  2581. encodings_left = []
  2582. try:
  2583. resp.headers.get_all
  2584. hdrs = resp.headers
  2585. except AttributeError:
  2586. # Py2 has no get_all() method: headers are rfc822.Message
  2587. from email.message import Message
  2588. hdrs = Message()
  2589. for k, v in resp.headers.items():
  2590. hdrs[k] = v
  2591. decoder, decoded_response = True, None
  2592. for encoding in encodings(hdrs.get_all('Content-Encoding', [])):
  2593. # "SHOULD consider" x-compress, x-gzip as compress, gzip
  2594. decoder = decoder and decoders.get(remove_start(encoding, 'x-'))
  2595. if not decoder:
  2596. encodings_left.insert(0, encoding)
  2597. continue
  2598. decoded_response = decoder(decoded_response or resp.read())
  2599. if decoded_response is not None:
  2600. resp = compat_urllib_request.addinfourl(
  2601. io.BytesIO(decoded_response), old_resp.headers, old_resp.url, old_resp.code)
  2602. resp.msg = old_resp.msg
  2603. del resp.headers['Content-Length']
  2604. resp.headers['Content-Length'] = '%d' % len(decoded_response)
  2605. del resp.headers['Content-Encoding']
  2606. if encodings_left:
  2607. resp.headers['Content-Encoding'] = ', '.join(encodings_left)
  2608. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2609. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2610. if 300 <= resp.code < 400:
  2611. location = resp.headers.get('Location')
  2612. if location:
  2613. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2614. if sys.version_info >= (3, 0):
  2615. location = location.encode('iso-8859-1')
  2616. location = location.decode('utf-8')
  2617. # resolve embedded . and ..
  2618. location_fixed = self._fix_path(location)
  2619. location_escaped = escape_url(location_fixed)
  2620. if location != location_escaped:
  2621. del resp.headers['Location']
  2622. if not isinstance(location_escaped, str): # Py 2 case
  2623. location_escaped = location_escaped.encode('utf-8')
  2624. resp.headers['Location'] = location_escaped
  2625. return resp
  2626. https_request = http_request
  2627. https_response = http_response
  2628. def make_socks_conn_class(base_class, socks_proxy):
  2629. assert issubclass(base_class, (
  2630. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2631. url_components = compat_urllib_parse.urlparse(socks_proxy)
  2632. if url_components.scheme.lower() == 'socks5':
  2633. socks_type = ProxyType.SOCKS5
  2634. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2635. socks_type = ProxyType.SOCKS4
  2636. elif url_components.scheme.lower() == 'socks4a':
  2637. socks_type = ProxyType.SOCKS4A
  2638. def unquote_if_non_empty(s):
  2639. if not s:
  2640. return s
  2641. return compat_urllib_parse_unquote_plus(s)
  2642. proxy_args = (
  2643. socks_type,
  2644. url_components.hostname, url_components.port or 1080,
  2645. True, # Remote DNS
  2646. unquote_if_non_empty(url_components.username),
  2647. unquote_if_non_empty(url_components.password),
  2648. )
  2649. class SocksConnection(base_class):
  2650. def connect(self):
  2651. self.sock = sockssocket()
  2652. self.sock.setproxy(*proxy_args)
  2653. if type(self.timeout) in (int, float):
  2654. self.sock.settimeout(self.timeout)
  2655. self.sock.connect((self.host, self.port))
  2656. if isinstance(self, compat_http_client.HTTPSConnection):
  2657. if hasattr(self, '_context'): # Python > 2.6
  2658. self.sock = self._context.wrap_socket(
  2659. self.sock, server_hostname=self.host)
  2660. else:
  2661. self.sock = ssl.wrap_socket(self.sock)
  2662. return SocksConnection
  2663. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2664. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2665. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2666. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2667. self._params = params
  2668. def https_open(self, req):
  2669. kwargs = {}
  2670. conn_class = self._https_conn_class
  2671. if hasattr(self, '_context'): # python > 2.6
  2672. kwargs['context'] = self._context
  2673. if hasattr(self, '_check_hostname'): # python 3.x
  2674. kwargs['check_hostname'] = self._check_hostname
  2675. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2676. if socks_proxy:
  2677. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2678. del req.headers['Ytdl-socks-proxy']
  2679. return self.do_open(functools.partial(
  2680. _create_http_connection, self, conn_class, True),
  2681. req, **kwargs)
  2682. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2683. """
  2684. See [1] for cookie file format.
  2685. 1. https://curl.haxx.se/docs/http-cookies.html
  2686. """
  2687. _HTTPONLY_PREFIX = '#HttpOnly_'
  2688. _ENTRY_LEN = 7
  2689. _HEADER = '''# Netscape HTTP Cookie File
  2690. # This file is generated by youtube-dl. Do not edit.
  2691. '''
  2692. _CookieFileEntry = collections.namedtuple(
  2693. 'CookieFileEntry',
  2694. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  2695. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2696. """
  2697. Save cookies to a file.
  2698. Most of the code is taken from CPython 3.8 and slightly adapted
  2699. to support cookie files with UTF-8 in both python 2 and 3.
  2700. """
  2701. if filename is None:
  2702. if self.filename is not None:
  2703. filename = self.filename
  2704. else:
  2705. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2706. # Store session cookies with `expires` set to 0 instead of an empty
  2707. # string
  2708. for cookie in self:
  2709. if cookie.expires is None:
  2710. cookie.expires = 0
  2711. with io.open(filename, 'w', encoding='utf-8') as f:
  2712. f.write(self._HEADER)
  2713. now = time.time()
  2714. for cookie in self:
  2715. if not ignore_discard and cookie.discard:
  2716. continue
  2717. if not ignore_expires and cookie.is_expired(now):
  2718. continue
  2719. if cookie.secure:
  2720. secure = 'TRUE'
  2721. else:
  2722. secure = 'FALSE'
  2723. if cookie.domain.startswith('.'):
  2724. initial_dot = 'TRUE'
  2725. else:
  2726. initial_dot = 'FALSE'
  2727. if cookie.expires is not None:
  2728. expires = compat_str(cookie.expires)
  2729. else:
  2730. expires = ''
  2731. if cookie.value is None:
  2732. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  2733. # with no name, whereas http.cookiejar regards it as a
  2734. # cookie with no value.
  2735. name = ''
  2736. value = cookie.name
  2737. else:
  2738. name = cookie.name
  2739. value = cookie.value
  2740. f.write(
  2741. '\t'.join([cookie.domain, initial_dot, cookie.path,
  2742. secure, expires, name, value]) + '\n')
  2743. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2744. """Load cookies from a file."""
  2745. if filename is None:
  2746. if self.filename is not None:
  2747. filename = self.filename
  2748. else:
  2749. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2750. def prepare_line(line):
  2751. if line.startswith(self._HTTPONLY_PREFIX):
  2752. line = line[len(self._HTTPONLY_PREFIX):]
  2753. # comments and empty lines are fine
  2754. if line.startswith('#') or not line.strip():
  2755. return line
  2756. cookie_list = line.split('\t')
  2757. if len(cookie_list) != self._ENTRY_LEN:
  2758. raise compat_cookiejar.LoadError('invalid length %d' % len(cookie_list))
  2759. cookie = self._CookieFileEntry(*cookie_list)
  2760. if cookie.expires_at and not cookie.expires_at.isdigit():
  2761. raise compat_cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
  2762. return line
  2763. cf = io.StringIO()
  2764. with io.open(filename, encoding='utf-8') as f:
  2765. for line in f:
  2766. try:
  2767. cf.write(prepare_line(line))
  2768. except compat_cookiejar.LoadError as e:
  2769. write_string(
  2770. 'WARNING: skipping cookie file entry due to %s: %r\n'
  2771. % (e, line), sys.stderr)
  2772. continue
  2773. cf.seek(0)
  2774. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2775. # Session cookies are denoted by either `expires` field set to
  2776. # an empty string or 0. MozillaCookieJar only recognizes the former
  2777. # (see [1]). So we need force the latter to be recognized as session
  2778. # cookies on our own.
  2779. # Session cookies may be important for cookies-based authentication,
  2780. # e.g. usually, when user does not check 'Remember me' check box while
  2781. # logging in on a site, some important cookies are stored as session
  2782. # cookies so that not recognizing them will result in failed login.
  2783. # 1. https://bugs.python.org/issue17164
  2784. for cookie in self:
  2785. # Treat `expires=0` cookies as session cookies
  2786. if cookie.expires == 0:
  2787. cookie.expires = None
  2788. cookie.discard = True
  2789. def get_cookie_header(self, url):
  2790. """Generate a Cookie HTTP header for a given url"""
  2791. cookie_req = sanitized_Request(url)
  2792. self.add_cookie_header(cookie_req)
  2793. return cookie_req.get_header('Cookie')
  2794. def get_cookies_for_url(self, url):
  2795. """Generate a list of Cookie objects for a given url"""
  2796. # Policy `_now` attribute must be set before calling `_cookies_for_request`
  2797. # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360
  2798. self._policy._now = self._now = int(time.time())
  2799. return self._cookies_for_request(sanitized_Request(url))
  2800. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2801. def __init__(self, cookiejar=None):
  2802. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2803. def http_response(self, request, response):
  2804. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2805. # characters in Set-Cookie HTTP header of last response (see
  2806. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2807. # In order to at least prevent crashing we will percent encode Set-Cookie
  2808. # header before HTTPCookieProcessor starts processing it.
  2809. # if sys.version_info < (3, 0) and response.headers:
  2810. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2811. # set_cookie = response.headers.get(set_cookie_header)
  2812. # if set_cookie:
  2813. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2814. # if set_cookie != set_cookie_escaped:
  2815. # del response.headers[set_cookie_header]
  2816. # response.headers[set_cookie_header] = set_cookie_escaped
  2817. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2818. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2819. https_response = http_response
  2820. class YoutubeDLRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  2821. """YoutubeDL redirect handler
  2822. The code is based on HTTPRedirectHandler implementation from CPython [1].
  2823. This redirect handler fixes and improves the logic to better align with RFC7261
  2824. and what browsers tend to do [2][3]
  2825. 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
  2826. 2. https://datatracker.ietf.org/doc/html/rfc7231
  2827. 3. https://github.com/python/cpython/issues/91306
  2828. """
  2829. # Supply possibly missing alias
  2830. http_error_308 = compat_urllib_request.HTTPRedirectHandler.http_error_302
  2831. def redirect_request(self, req, fp, code, msg, headers, newurl):
  2832. """Return a Request or None in response to a redirect.
  2833. This is called by the http_error_30x methods when a
  2834. redirection response is received. If a redirection should
  2835. take place, return a new Request to allow http_error_30x to
  2836. perform the redirect. Otherwise, raise HTTPError if no-one
  2837. else should try to handle this url. Return None if you can't
  2838. but another Handler might.
  2839. """
  2840. if code not in (301, 302, 303, 307, 308):
  2841. raise compat_urllib_HTTPError(req.full_url, code, msg, headers, fp)
  2842. new_method = req.get_method()
  2843. new_data = req.data
  2844. # On python 2 urlh.geturl() may sometimes return redirect URL
  2845. # as a byte string instead of unicode. This workaround forces
  2846. # it to return unicode.
  2847. newurl = _decode_compat_str(newurl)
  2848. # Be conciliant with URIs containing a space. This is mainly
  2849. # redundant with the more complete encoding done in http_error_302(),
  2850. # but it is kept for compatibility with other callers.
  2851. newurl = newurl.replace(' ', '%20')
  2852. # Technically the Cookie header should be in unredirected_hdrs;
  2853. # however in practice some may set it in normal headers anyway.
  2854. # We will remove it here to prevent any leaks.
  2855. remove_headers = ['Cookie']
  2856. # A 303 must either use GET or HEAD for subsequent request
  2857. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.4
  2858. if code == 303 and req.get_method() != 'HEAD':
  2859. new_method = 'GET'
  2860. # 301 and 302 redirects are commonly turned into a GET from a POST
  2861. # for subsequent requests by browsers, so we'll do the same.
  2862. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.2
  2863. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.3
  2864. elif code in (301, 302) and req.get_method() == 'POST':
  2865. new_method = 'GET'
  2866. # only remove payload if method changed (e.g. POST to GET)
  2867. if new_method != req.get_method():
  2868. new_data = None
  2869. remove_headers.extend(['Content-Length', 'Content-Type'])
  2870. new_headers = filter_dict(req.headers, cndn=lambda k, _: k.title() not in remove_headers)
  2871. return compat_urllib_request.Request(
  2872. newurl, headers=new_headers, origin_req_host=req.origin_req_host,
  2873. unverifiable=True, method=new_method, data=new_data)
  2874. def extract_timezone(date_str):
  2875. m = re.search(
  2876. r'''(?x)
  2877. ^.{8,}? # >=8 char non-TZ prefix, if present
  2878. (?P<tz>Z| # just the UTC Z, or
  2879. (?:(?<=.\b\d{4}|\b\d{2}:\d\d)| # preceded by 4 digits or hh:mm or
  2880. (?<!.\b[a-zA-Z]{3}|[a-zA-Z]{4}|..\b\d\d)) # not preceded by 3 alpha word or >= 4 alpha or 2 digits
  2881. [ ]? # optional space
  2882. (?P<sign>\+|-) # +/-
  2883. (?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2}) # hh[:]mm
  2884. $)
  2885. ''', date_str)
  2886. if not m:
  2887. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2888. timezone = TIMEZONE_NAMES.get(m and m.group('tz').strip())
  2889. if timezone is not None:
  2890. date_str = date_str[:-len(m.group('tz'))]
  2891. timezone = datetime.timedelta(hours=timezone or 0)
  2892. else:
  2893. date_str = date_str[:-len(m.group('tz'))]
  2894. if not m.group('sign'):
  2895. timezone = datetime.timedelta()
  2896. else:
  2897. sign = 1 if m.group('sign') == '+' else -1
  2898. timezone = datetime.timedelta(
  2899. hours=sign * int(m.group('hours')),
  2900. minutes=sign * int(m.group('minutes')))
  2901. return timezone, date_str
  2902. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2903. """ Return a UNIX timestamp from the given date """
  2904. if date_str is None:
  2905. return None
  2906. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2907. if timezone is None:
  2908. timezone, date_str = extract_timezone(date_str)
  2909. with compat_contextlib_suppress(ValueError):
  2910. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2911. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2912. return calendar.timegm(dt.timetuple())
  2913. def date_formats(day_first=True):
  2914. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2915. def unified_strdate(date_str, day_first=True):
  2916. """Return a string with the date in the format YYYYMMDD"""
  2917. if date_str is None:
  2918. return None
  2919. upload_date = None
  2920. # Replace commas
  2921. date_str = date_str.replace(',', ' ')
  2922. # Remove AM/PM + timezone
  2923. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2924. _, date_str = extract_timezone(date_str)
  2925. for expression in date_formats(day_first):
  2926. with compat_contextlib_suppress(ValueError):
  2927. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2928. if upload_date is None:
  2929. timetuple = email.utils.parsedate_tz(date_str)
  2930. if timetuple:
  2931. with compat_contextlib_suppress(ValueError):
  2932. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2933. if upload_date is not None:
  2934. return compat_str(upload_date)
  2935. def unified_timestamp(date_str, day_first=True):
  2936. if date_str is None:
  2937. return None
  2938. date_str = re.sub(r'\s+', ' ', re.sub(
  2939. r'(?i)[,|]|(mon|tues?|wed(nes)?|thu(rs)?|fri|sat(ur)?)(day)?', '', date_str))
  2940. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2941. timezone, date_str = extract_timezone(date_str)
  2942. # Remove AM/PM + timezone
  2943. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2944. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2945. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2946. if m:
  2947. date_str = date_str[:-len(m.group('tz'))]
  2948. # Python only supports microseconds, so remove nanoseconds
  2949. 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)
  2950. if m:
  2951. date_str = m.group(1)
  2952. for expression in date_formats(day_first):
  2953. with compat_contextlib_suppress(ValueError):
  2954. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2955. return calendar.timegm(dt.timetuple())
  2956. timetuple = email.utils.parsedate_tz(date_str)
  2957. if timetuple:
  2958. return calendar.timegm(timetuple) + pm_delta * 3600 - compat_datetime_timedelta_total_seconds(timezone)
  2959. def determine_ext(url, default_ext='unknown_video'):
  2960. if url is None or '.' not in url:
  2961. return default_ext
  2962. guess = url.partition('?')[0].rpartition('.')[2]
  2963. if re.match(r'^[A-Za-z0-9]+$', guess):
  2964. return guess
  2965. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2966. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2967. return guess.rstrip('/')
  2968. else:
  2969. return default_ext
  2970. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2971. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2972. def date_from_str(date_str):
  2973. """
  2974. Return a datetime object from a string in the format YYYYMMDD or
  2975. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2976. today = datetime.date.today()
  2977. if date_str in ('now', 'today'):
  2978. return today
  2979. if date_str == 'yesterday':
  2980. return today - datetime.timedelta(days=1)
  2981. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2982. if match is not None:
  2983. sign = match.group('sign')
  2984. time = int(match.group('time'))
  2985. if sign == '-':
  2986. time = -time
  2987. unit = match.group('unit')
  2988. # A bad approximation?
  2989. if unit == 'month':
  2990. unit = 'day'
  2991. time *= 30
  2992. elif unit == 'year':
  2993. unit = 'day'
  2994. time *= 365
  2995. unit += 's'
  2996. delta = datetime.timedelta(**{unit: time})
  2997. return today + delta
  2998. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2999. def hyphenate_date(date_str):
  3000. """
  3001. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  3002. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  3003. if match is not None:
  3004. return '-'.join(match.groups())
  3005. else:
  3006. return date_str
  3007. class DateRange(object):
  3008. """Represents a time interval between two dates"""
  3009. def __init__(self, start=None, end=None):
  3010. """start and end must be strings in the format accepted by date"""
  3011. if start is not None:
  3012. self.start = date_from_str(start)
  3013. else:
  3014. self.start = datetime.datetime.min.date()
  3015. if end is not None:
  3016. self.end = date_from_str(end)
  3017. else:
  3018. self.end = datetime.datetime.max.date()
  3019. if self.start > self.end:
  3020. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  3021. @classmethod
  3022. def day(cls, day):
  3023. """Returns a range that only contains the given day"""
  3024. return cls(day, day)
  3025. def __contains__(self, date):
  3026. """Check if the date is in the range"""
  3027. if not isinstance(date, datetime.date):
  3028. date = date_from_str(date)
  3029. return self.start <= date <= self.end
  3030. def __str__(self):
  3031. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  3032. def __eq__(self, other):
  3033. return (isinstance(other, DateRange)
  3034. and self.start == other.start and self.end == other.end)
  3035. def platform_name():
  3036. """ Returns the platform name as a compat_str """
  3037. res = platform.platform()
  3038. return _decode_compat_str(res)
  3039. def _windows_write_string(s, out):
  3040. """ Returns True if the string was written using special methods,
  3041. False if it has yet to be written out."""
  3042. # Adapted from http://stackoverflow.com/a/3259271/35070
  3043. import ctypes
  3044. import ctypes.wintypes
  3045. WIN_OUTPUT_IDS = {
  3046. 1: -11,
  3047. 2: -12,
  3048. }
  3049. try:
  3050. fileno = out.fileno()
  3051. except AttributeError:
  3052. # If the output stream doesn't have a fileno, it's virtual
  3053. return False
  3054. except io.UnsupportedOperation:
  3055. # Some strange Windows pseudo files?
  3056. return False
  3057. if fileno not in WIN_OUTPUT_IDS:
  3058. return False
  3059. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  3060. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  3061. ('GetStdHandle', ctypes.windll.kernel32))
  3062. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  3063. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  3064. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  3065. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  3066. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  3067. written = ctypes.wintypes.DWORD(0)
  3068. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  3069. FILE_TYPE_CHAR = 0x0002
  3070. FILE_TYPE_REMOTE = 0x8000
  3071. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  3072. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  3073. ctypes.POINTER(ctypes.wintypes.DWORD))(
  3074. ('GetConsoleMode', ctypes.windll.kernel32))
  3075. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  3076. def not_a_console(handle):
  3077. if handle == INVALID_HANDLE_VALUE or handle is None:
  3078. return True
  3079. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  3080. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  3081. if not_a_console(h):
  3082. return False
  3083. def next_nonbmp_pos(s):
  3084. try:
  3085. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  3086. except StopIteration:
  3087. return len(s)
  3088. while s:
  3089. count = min(next_nonbmp_pos(s), 1024)
  3090. ret = WriteConsoleW(
  3091. h, s, count if count else 2, ctypes.byref(written), None)
  3092. if ret == 0:
  3093. raise OSError('Failed to write string')
  3094. if not count: # We just wrote a non-BMP character
  3095. assert written.value == 2
  3096. s = s[1:]
  3097. else:
  3098. assert written.value > 0
  3099. s = s[written.value:]
  3100. return True
  3101. def write_string(s, out=None, encoding=None):
  3102. if out is None:
  3103. out = sys.stderr
  3104. assert isinstance(s, compat_str)
  3105. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  3106. if _windows_write_string(s, out):
  3107. return
  3108. if ('b' in getattr(out, 'mode', '')
  3109. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  3110. byt = s.encode(encoding or preferredencoding(), 'ignore')
  3111. out.write(byt)
  3112. elif hasattr(out, 'buffer'):
  3113. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  3114. byt = s.encode(enc, 'ignore')
  3115. out.buffer.write(byt)
  3116. else:
  3117. out.write(s)
  3118. out.flush()
  3119. def bytes_to_intlist(bs):
  3120. if not bs:
  3121. return []
  3122. if isinstance(bs[0], int): # Python 3
  3123. return list(bs)
  3124. else:
  3125. return [ord(c) for c in bs]
  3126. def intlist_to_bytes(xs):
  3127. if not xs:
  3128. return b''
  3129. return compat_struct_pack('%dB' % len(xs), *xs)
  3130. # Cross-platform file locking
  3131. if sys.platform == 'win32':
  3132. import ctypes.wintypes
  3133. import msvcrt
  3134. class OVERLAPPED(ctypes.Structure):
  3135. _fields_ = [
  3136. ('Internal', ctypes.wintypes.LPVOID),
  3137. ('InternalHigh', ctypes.wintypes.LPVOID),
  3138. ('Offset', ctypes.wintypes.DWORD),
  3139. ('OffsetHigh', ctypes.wintypes.DWORD),
  3140. ('hEvent', ctypes.wintypes.HANDLE),
  3141. ]
  3142. kernel32 = ctypes.windll.kernel32
  3143. LockFileEx = kernel32.LockFileEx
  3144. LockFileEx.argtypes = [
  3145. ctypes.wintypes.HANDLE, # hFile
  3146. ctypes.wintypes.DWORD, # dwFlags
  3147. ctypes.wintypes.DWORD, # dwReserved
  3148. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  3149. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  3150. ctypes.POINTER(OVERLAPPED) # Overlapped
  3151. ]
  3152. LockFileEx.restype = ctypes.wintypes.BOOL
  3153. UnlockFileEx = kernel32.UnlockFileEx
  3154. UnlockFileEx.argtypes = [
  3155. ctypes.wintypes.HANDLE, # hFile
  3156. ctypes.wintypes.DWORD, # dwReserved
  3157. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  3158. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  3159. ctypes.POINTER(OVERLAPPED) # Overlapped
  3160. ]
  3161. UnlockFileEx.restype = ctypes.wintypes.BOOL
  3162. whole_low = 0xffffffff
  3163. whole_high = 0x7fffffff
  3164. def _lock_file(f, exclusive):
  3165. overlapped = OVERLAPPED()
  3166. overlapped.Offset = 0
  3167. overlapped.OffsetHigh = 0
  3168. overlapped.hEvent = 0
  3169. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  3170. handle = msvcrt.get_osfhandle(f.fileno())
  3171. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  3172. whole_low, whole_high, f._lock_file_overlapped_p):
  3173. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  3174. def _unlock_file(f):
  3175. assert f._lock_file_overlapped_p
  3176. handle = msvcrt.get_osfhandle(f.fileno())
  3177. if not UnlockFileEx(handle, 0,
  3178. whole_low, whole_high, f._lock_file_overlapped_p):
  3179. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  3180. else:
  3181. # Some platforms, such as Jython, is missing fcntl
  3182. try:
  3183. import fcntl
  3184. def _lock_file(f, exclusive):
  3185. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  3186. def _unlock_file(f):
  3187. fcntl.flock(f, fcntl.LOCK_UN)
  3188. except ImportError:
  3189. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  3190. def _lock_file(f, exclusive):
  3191. raise IOError(UNSUPPORTED_MSG)
  3192. def _unlock_file(f):
  3193. raise IOError(UNSUPPORTED_MSG)
  3194. class locked_file(object):
  3195. def __init__(self, filename, mode, encoding=None):
  3196. assert mode in ['r', 'a', 'w']
  3197. self.f = io.open(filename, mode, encoding=encoding)
  3198. self.mode = mode
  3199. def __enter__(self):
  3200. exclusive = self.mode != 'r'
  3201. try:
  3202. _lock_file(self.f, exclusive)
  3203. except IOError:
  3204. self.f.close()
  3205. raise
  3206. return self
  3207. def __exit__(self, etype, value, traceback):
  3208. try:
  3209. _unlock_file(self.f)
  3210. finally:
  3211. self.f.close()
  3212. def __iter__(self):
  3213. return iter(self.f)
  3214. def write(self, *args):
  3215. return self.f.write(*args)
  3216. def read(self, *args):
  3217. return self.f.read(*args)
  3218. def get_filesystem_encoding():
  3219. encoding = sys.getfilesystemencoding()
  3220. return encoding if encoding is not None else 'utf-8'
  3221. def shell_quote(args):
  3222. quoted_args = []
  3223. encoding = get_filesystem_encoding()
  3224. for a in args:
  3225. # We may get a filename encoded with 'encodeFilename'
  3226. a = _decode_compat_str(a, encoding)
  3227. quoted_args.append(compat_shlex_quote(a))
  3228. return ' '.join(quoted_args)
  3229. def smuggle_url(url, data):
  3230. """ Pass additional data in a URL for internal use. """
  3231. url, idata = unsmuggle_url(url, {})
  3232. data.update(idata)
  3233. sdata = compat_urllib_parse_urlencode(
  3234. {'__youtubedl_smuggle': json.dumps(data)})
  3235. return url + '#' + sdata
  3236. def unsmuggle_url(smug_url, default=None):
  3237. if '#__youtubedl_smuggle' not in smug_url:
  3238. return smug_url, default
  3239. url, _, sdata = smug_url.rpartition('#')
  3240. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  3241. data = json.loads(jsond)
  3242. return url, data
  3243. def format_bytes(bytes):
  3244. if bytes is None:
  3245. return 'N/A'
  3246. if type(bytes) is str:
  3247. bytes = float(bytes)
  3248. if bytes == 0.0:
  3249. exponent = 0
  3250. else:
  3251. exponent = int(math.log(bytes, 1024.0))
  3252. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  3253. converted = float(bytes) / float(1024 ** exponent)
  3254. return '%.2f%s' % (converted, suffix)
  3255. def lookup_unit_table(unit_table, s):
  3256. units_re = '|'.join(re.escape(u) for u in unit_table)
  3257. m = re.match(
  3258. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  3259. if not m:
  3260. return None
  3261. num_str = m.group('num').replace(',', '.')
  3262. mult = unit_table[m.group('unit')]
  3263. return int(float(num_str) * mult)
  3264. def parse_filesize(s):
  3265. if s is None:
  3266. return None
  3267. # The lower-case forms are of course incorrect and unofficial,
  3268. # but we support those too
  3269. _UNIT_TABLE = {
  3270. 'B': 1,
  3271. 'b': 1,
  3272. 'bytes': 1,
  3273. 'KiB': 1024,
  3274. 'KB': 1000,
  3275. 'kB': 1024,
  3276. 'Kb': 1000,
  3277. 'kb': 1000,
  3278. 'kilobytes': 1000,
  3279. 'kibibytes': 1024,
  3280. 'MiB': 1024 ** 2,
  3281. 'MB': 1000 ** 2,
  3282. 'mB': 1024 ** 2,
  3283. 'Mb': 1000 ** 2,
  3284. 'mb': 1000 ** 2,
  3285. 'megabytes': 1000 ** 2,
  3286. 'mebibytes': 1024 ** 2,
  3287. 'GiB': 1024 ** 3,
  3288. 'GB': 1000 ** 3,
  3289. 'gB': 1024 ** 3,
  3290. 'Gb': 1000 ** 3,
  3291. 'gb': 1000 ** 3,
  3292. 'gigabytes': 1000 ** 3,
  3293. 'gibibytes': 1024 ** 3,
  3294. 'TiB': 1024 ** 4,
  3295. 'TB': 1000 ** 4,
  3296. 'tB': 1024 ** 4,
  3297. 'Tb': 1000 ** 4,
  3298. 'tb': 1000 ** 4,
  3299. 'terabytes': 1000 ** 4,
  3300. 'tebibytes': 1024 ** 4,
  3301. 'PiB': 1024 ** 5,
  3302. 'PB': 1000 ** 5,
  3303. 'pB': 1024 ** 5,
  3304. 'Pb': 1000 ** 5,
  3305. 'pb': 1000 ** 5,
  3306. 'petabytes': 1000 ** 5,
  3307. 'pebibytes': 1024 ** 5,
  3308. 'EiB': 1024 ** 6,
  3309. 'EB': 1000 ** 6,
  3310. 'eB': 1024 ** 6,
  3311. 'Eb': 1000 ** 6,
  3312. 'eb': 1000 ** 6,
  3313. 'exabytes': 1000 ** 6,
  3314. 'exbibytes': 1024 ** 6,
  3315. 'ZiB': 1024 ** 7,
  3316. 'ZB': 1000 ** 7,
  3317. 'zB': 1024 ** 7,
  3318. 'Zb': 1000 ** 7,
  3319. 'zb': 1000 ** 7,
  3320. 'zettabytes': 1000 ** 7,
  3321. 'zebibytes': 1024 ** 7,
  3322. 'YiB': 1024 ** 8,
  3323. 'YB': 1000 ** 8,
  3324. 'yB': 1024 ** 8,
  3325. 'Yb': 1000 ** 8,
  3326. 'yb': 1000 ** 8,
  3327. 'yottabytes': 1000 ** 8,
  3328. 'yobibytes': 1024 ** 8,
  3329. }
  3330. return lookup_unit_table(_UNIT_TABLE, s)
  3331. def parse_count(s):
  3332. if s is None:
  3333. return None
  3334. s = s.strip()
  3335. if re.match(r'^[\d,.]+$', s):
  3336. return str_to_int(s)
  3337. _UNIT_TABLE = {
  3338. 'k': 1000,
  3339. 'K': 1000,
  3340. 'm': 1000 ** 2,
  3341. 'M': 1000 ** 2,
  3342. 'kk': 1000 ** 2,
  3343. 'KK': 1000 ** 2,
  3344. }
  3345. return lookup_unit_table(_UNIT_TABLE, s)
  3346. def parse_resolution(s):
  3347. if s is None:
  3348. return {}
  3349. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3350. if mobj:
  3351. return {
  3352. 'width': int(mobj.group('w')),
  3353. 'height': int(mobj.group('h')),
  3354. }
  3355. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3356. if mobj:
  3357. return {'height': int(mobj.group(1))}
  3358. mobj = re.search(r'\b([48])[kK]\b', s)
  3359. if mobj:
  3360. return {'height': int(mobj.group(1)) * 540}
  3361. return {}
  3362. def parse_bitrate(s):
  3363. s = txt_or_none(s)
  3364. if not s:
  3365. return None
  3366. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3367. if mobj:
  3368. return int(mobj.group(1))
  3369. def month_by_name(name, lang='en'):
  3370. """ Return the number of a month by (locale-independently) English name """
  3371. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3372. try:
  3373. return month_names.index(name) + 1
  3374. except ValueError:
  3375. return None
  3376. def month_by_abbreviation(abbrev):
  3377. """ Return the number of a month by (locale-independently) English
  3378. abbreviations """
  3379. try:
  3380. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3381. except ValueError:
  3382. return None
  3383. def fix_xml_ampersands(xml_str):
  3384. """Replace all the '&' by '&amp;' in XML"""
  3385. return re.sub(
  3386. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3387. '&amp;',
  3388. xml_str)
  3389. def setproctitle(title):
  3390. assert isinstance(title, compat_str)
  3391. # ctypes in Jython is not complete
  3392. # http://bugs.jython.org/issue2148
  3393. if sys.platform.startswith('java'):
  3394. return
  3395. try:
  3396. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3397. except OSError:
  3398. return
  3399. except TypeError:
  3400. # LoadLibrary in Windows Python 2.7.13 only expects
  3401. # a bytestring, but since unicode_literals turns
  3402. # every string into a unicode string, it fails.
  3403. return
  3404. title_bytes = title.encode('utf-8')
  3405. buf = ctypes.create_string_buffer(len(title_bytes))
  3406. buf.value = title_bytes
  3407. try:
  3408. libc.prctl(15, buf, 0, 0, 0)
  3409. except AttributeError:
  3410. return # Strange libc, just skip this
  3411. def remove_start(s, start):
  3412. return s[len(start):] if s is not None and s.startswith(start) else s
  3413. def remove_end(s, end):
  3414. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3415. def remove_quotes(s):
  3416. if s is None or len(s) < 2:
  3417. return s
  3418. for quote in ('"', "'", ):
  3419. if s[0] == quote and s[-1] == quote:
  3420. return s[1:-1]
  3421. return s
  3422. def url_basename(url):
  3423. path = compat_urllib_parse.urlparse(url).path
  3424. return path.strip('/').split('/')[-1]
  3425. def base_url(url):
  3426. return re.match(r'https?://[^?#&]+/', url).group()
  3427. def urljoin(base, path):
  3428. path = _decode_compat_str(path, encoding='utf-8', or_none=True)
  3429. if not path:
  3430. return None
  3431. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3432. return path
  3433. base = _decode_compat_str(base, encoding='utf-8', or_none=True)
  3434. if not base:
  3435. return None
  3436. return (
  3437. re.match(r'^(?:https?:)?//', base)
  3438. and compat_urllib_parse.urljoin(base, path))
  3439. class HEADRequest(compat_urllib_request.Request):
  3440. def get_method(self):
  3441. return 'HEAD'
  3442. class PUTRequest(compat_urllib_request.Request):
  3443. def get_method(self):
  3444. return 'PUT'
  3445. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1, base=None):
  3446. if get_attr:
  3447. if v is not None:
  3448. v = getattr(v, get_attr, None)
  3449. if v in (None, ''):
  3450. return default
  3451. try:
  3452. # like int, raise if base is specified and v is not a string
  3453. return (int(v) if base is None else int(v, base=base)) * invscale // scale
  3454. except (ValueError, TypeError, OverflowError):
  3455. return default
  3456. def str_or_none(v, default=None):
  3457. return default if v is None else compat_str(v)
  3458. def str_to_int(int_str):
  3459. """ A more relaxed version of int_or_none """
  3460. if isinstance(int_str, compat_integer_types):
  3461. return int_str
  3462. elif isinstance(int_str, compat_str):
  3463. int_str = re.sub(r'[,\.\+]', '', int_str)
  3464. return int_or_none(int_str)
  3465. def float_or_none(v, scale=1, invscale=1, default=None):
  3466. if v is None:
  3467. return default
  3468. try:
  3469. return float(v) * invscale / scale
  3470. except (ValueError, TypeError):
  3471. return default
  3472. def bool_or_none(v, default=None):
  3473. return v if isinstance(v, bool) else default
  3474. def strip_or_none(v, default=None):
  3475. return v.strip() if isinstance(v, compat_str) else default
  3476. def txt_or_none(v, default=None):
  3477. """ Combine str/strip_or_none, disallow blank value (for traverse_obj) """
  3478. return default if v is None else (compat_str(v).strip() or default)
  3479. def url_or_none(url):
  3480. if not url or not isinstance(url, compat_str):
  3481. return None
  3482. url = url.strip()
  3483. return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None
  3484. def parse_duration(s):
  3485. if not isinstance(s, compat_basestring):
  3486. return None
  3487. s = s.strip()
  3488. days, hours, mins, secs, ms = [None] * 5
  3489. 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)
  3490. if m:
  3491. days, hours, mins, secs, ms = m.groups()
  3492. else:
  3493. m = re.match(
  3494. r'''(?ix)(?:P?
  3495. (?:
  3496. [0-9]+\s*y(?:ears?)?\s*
  3497. )?
  3498. (?:
  3499. [0-9]+\s*m(?:onths?)?\s*
  3500. )?
  3501. (?:
  3502. [0-9]+\s*w(?:eeks?)?\s*
  3503. )?
  3504. (?:
  3505. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3506. )?
  3507. T)?
  3508. (?:
  3509. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3510. )?
  3511. (?:
  3512. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3513. )?
  3514. (?:
  3515. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3516. )?Z?$''', s)
  3517. if m:
  3518. days, hours, mins, secs, ms = m.groups()
  3519. else:
  3520. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3521. if m:
  3522. hours, mins = m.groups()
  3523. else:
  3524. return None
  3525. duration = 0
  3526. if secs:
  3527. duration += float(secs)
  3528. if mins:
  3529. duration += float(mins) * 60
  3530. if hours:
  3531. duration += float(hours) * 60 * 60
  3532. if days:
  3533. duration += float(days) * 24 * 60 * 60
  3534. if ms:
  3535. duration += float(ms)
  3536. return duration
  3537. def prepend_extension(filename, ext, expected_real_ext=None):
  3538. name, real_ext = os.path.splitext(filename)
  3539. return (
  3540. '{0}.{1}{2}'.format(name, ext, real_ext)
  3541. if not expected_real_ext or real_ext[1:] == expected_real_ext
  3542. else '{0}.{1}'.format(filename, ext))
  3543. def replace_extension(filename, ext, expected_real_ext=None):
  3544. name, real_ext = os.path.splitext(filename)
  3545. return '{0}.{1}'.format(
  3546. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  3547. ext)
  3548. def check_executable(exe, args=[]):
  3549. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3550. args can be a list of arguments for a short output (like -version) """
  3551. try:
  3552. process_communicate_or_kill(subprocess.Popen(
  3553. [exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
  3554. except OSError:
  3555. return False
  3556. return exe
  3557. def get_exe_version(exe, args=['--version'],
  3558. version_re=None, unrecognized='present'):
  3559. """ Returns the version of the specified executable,
  3560. or False if the executable is not present """
  3561. try:
  3562. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3563. # SIGTTOU if youtube-dl is run in the background.
  3564. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3565. out, _ = process_communicate_or_kill(subprocess.Popen(
  3566. [encodeArgument(exe)] + args,
  3567. stdin=subprocess.PIPE,
  3568. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  3569. except OSError:
  3570. return False
  3571. out = _decode_compat_str(out, 'ascii', 'ignore')
  3572. return detect_exe_version(out, version_re, unrecognized)
  3573. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3574. assert isinstance(output, compat_str)
  3575. if version_re is None:
  3576. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3577. m = re.search(version_re, output)
  3578. if m:
  3579. return m.group(1)
  3580. else:
  3581. return unrecognized
  3582. class LazyList(compat_collections_abc.Iterable):
  3583. """Lazy immutable list from an iterable
  3584. Note that slices of a LazyList are lists and not LazyList"""
  3585. class IndexError(IndexError):
  3586. def __init__(self, cause=None):
  3587. if cause:
  3588. # reproduce `raise from`
  3589. self.__cause__ = cause
  3590. super(IndexError, self).__init__()
  3591. def __init__(self, iterable, **kwargs):
  3592. # kwarg-only
  3593. reverse = kwargs.get('reverse', False)
  3594. _cache = kwargs.get('_cache')
  3595. self._iterable = iter(iterable)
  3596. self._cache = [] if _cache is None else _cache
  3597. self._reversed = reverse
  3598. def __iter__(self):
  3599. if self._reversed:
  3600. # We need to consume the entire iterable to iterate in reverse
  3601. for item in self.exhaust():
  3602. yield item
  3603. return
  3604. for item in self._cache:
  3605. yield item
  3606. for item in self._iterable:
  3607. self._cache.append(item)
  3608. yield item
  3609. def _exhaust(self):
  3610. self._cache.extend(self._iterable)
  3611. self._iterable = [] # Discard the emptied iterable to make it pickle-able
  3612. return self._cache
  3613. def exhaust(self):
  3614. """Evaluate the entire iterable"""
  3615. return self._exhaust()[::-1 if self._reversed else 1]
  3616. @staticmethod
  3617. def _reverse_index(x):
  3618. return None if x is None else ~x
  3619. def __getitem__(self, idx):
  3620. if isinstance(idx, slice):
  3621. if self._reversed:
  3622. idx = slice(self._reverse_index(idx.start), self._reverse_index(idx.stop), -(idx.step or 1))
  3623. start, stop, step = idx.start, idx.stop, idx.step or 1
  3624. elif isinstance(idx, int):
  3625. if self._reversed:
  3626. idx = self._reverse_index(idx)
  3627. start, stop, step = idx, idx, 0
  3628. else:
  3629. raise TypeError('indices must be integers or slices')
  3630. if ((start or 0) < 0 or (stop or 0) < 0
  3631. or (start is None and step < 0)
  3632. or (stop is None and step > 0)):
  3633. # We need to consume the entire iterable to be able to slice from the end
  3634. # Obviously, never use this with infinite iterables
  3635. self._exhaust()
  3636. try:
  3637. return self._cache[idx]
  3638. except IndexError as e:
  3639. raise self.IndexError(e)
  3640. n = max(start or 0, stop or 0) - len(self._cache) + 1
  3641. if n > 0:
  3642. self._cache.extend(itertools.islice(self._iterable, n))
  3643. try:
  3644. return self._cache[idx]
  3645. except IndexError as e:
  3646. raise self.IndexError(e)
  3647. def __bool__(self):
  3648. try:
  3649. self[-1] if self._reversed else self[0]
  3650. except self.IndexError:
  3651. return False
  3652. return True
  3653. def __len__(self):
  3654. self._exhaust()
  3655. return len(self._cache)
  3656. def __reversed__(self):
  3657. return type(self)(self._iterable, reverse=not self._reversed, _cache=self._cache)
  3658. def __copy__(self):
  3659. return type(self)(self._iterable, reverse=self._reversed, _cache=self._cache)
  3660. def __repr__(self):
  3661. # repr and str should mimic a list. So we exhaust the iterable
  3662. return repr(self.exhaust())
  3663. def __str__(self):
  3664. return repr(self.exhaust())
  3665. class PagedList(object):
  3666. def __len__(self):
  3667. # This is only useful for tests
  3668. return len(self.getslice())
  3669. class OnDemandPagedList(PagedList):
  3670. def __init__(self, pagefunc, pagesize, use_cache=True):
  3671. self._pagefunc = pagefunc
  3672. self._pagesize = pagesize
  3673. self._use_cache = use_cache
  3674. if use_cache:
  3675. self._cache = {}
  3676. def getslice(self, start=0, end=None):
  3677. res = []
  3678. for pagenum in itertools.count(start // self._pagesize):
  3679. firstid = pagenum * self._pagesize
  3680. nextfirstid = pagenum * self._pagesize + self._pagesize
  3681. if start >= nextfirstid:
  3682. continue
  3683. page_results = None
  3684. if self._use_cache:
  3685. page_results = self._cache.get(pagenum)
  3686. if page_results is None:
  3687. page_results = list(self._pagefunc(pagenum))
  3688. if self._use_cache:
  3689. self._cache[pagenum] = page_results
  3690. startv = (
  3691. start % self._pagesize
  3692. if firstid <= start < nextfirstid
  3693. else 0)
  3694. endv = (
  3695. ((end - 1) % self._pagesize) + 1
  3696. if (end is not None and firstid <= end <= nextfirstid)
  3697. else None)
  3698. if startv != 0 or endv is not None:
  3699. page_results = page_results[startv:endv]
  3700. res.extend(page_results)
  3701. # A little optimization - if current page is not "full", ie. does
  3702. # not contain page_size videos then we can assume that this page
  3703. # is the last one - there are no more ids on further pages -
  3704. # i.e. no need to query again.
  3705. if len(page_results) + startv < self._pagesize:
  3706. break
  3707. # If we got the whole page, but the next page is not interesting,
  3708. # break out early as well
  3709. if end == nextfirstid:
  3710. break
  3711. return res
  3712. class InAdvancePagedList(PagedList):
  3713. def __init__(self, pagefunc, pagecount, pagesize):
  3714. self._pagefunc = pagefunc
  3715. self._pagecount = pagecount
  3716. self._pagesize = pagesize
  3717. def getslice(self, start=0, end=None):
  3718. res = []
  3719. start_page = start // self._pagesize
  3720. end_page = (
  3721. self._pagecount if end is None else (end // self._pagesize + 1))
  3722. skip_elems = start - start_page * self._pagesize
  3723. only_more = None if end is None else end - start
  3724. for pagenum in range(start_page, end_page):
  3725. page = list(self._pagefunc(pagenum))
  3726. if skip_elems:
  3727. page = page[skip_elems:]
  3728. skip_elems = None
  3729. if only_more is not None:
  3730. if len(page) < only_more:
  3731. only_more -= len(page)
  3732. else:
  3733. page = page[:only_more]
  3734. res.extend(page)
  3735. break
  3736. res.extend(page)
  3737. return res
  3738. def uppercase_escape(s):
  3739. unicode_escape = codecs.getdecoder('unicode_escape')
  3740. return re.sub(
  3741. r'\\U[0-9a-fA-F]{8}',
  3742. lambda m: unicode_escape(m.group(0))[0],
  3743. s)
  3744. def lowercase_escape(s):
  3745. unicode_escape = codecs.getdecoder('unicode_escape')
  3746. return re.sub(
  3747. r'\\u[0-9a-fA-F]{4}',
  3748. lambda m: unicode_escape(m.group(0))[0],
  3749. s)
  3750. def escape_rfc3986(s):
  3751. """Escape non-ASCII characters as suggested by RFC 3986"""
  3752. if sys.version_info < (3, 0):
  3753. s = _encode_compat_str(s, 'utf-8')
  3754. # ensure unicode: after quoting, it can always be converted
  3755. return compat_str(compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]"))
  3756. def escape_url(url):
  3757. """Escape URL as suggested by RFC 3986"""
  3758. url_parsed = compat_urllib_parse_urlparse(url)
  3759. return url_parsed._replace(
  3760. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3761. path=escape_rfc3986(url_parsed.path),
  3762. params=escape_rfc3986(url_parsed.params),
  3763. query=escape_rfc3986(url_parsed.query),
  3764. fragment=escape_rfc3986(url_parsed.fragment)
  3765. ).geturl()
  3766. def parse_qs(url, **kwargs):
  3767. return compat_parse_qs(compat_urllib_parse.urlparse(url).query, **kwargs)
  3768. def read_batch_urls(batch_fd):
  3769. def fixup(url):
  3770. url = _decode_compat_str(url, 'utf-8', 'replace')
  3771. BOM_UTF8 = '\xef\xbb\xbf'
  3772. if url.startswith(BOM_UTF8):
  3773. url = url[len(BOM_UTF8):]
  3774. url = url.strip()
  3775. if url.startswith(('#', ';', ']')):
  3776. return False
  3777. return url
  3778. with contextlib.closing(batch_fd) as fd:
  3779. return [url for url in map(fixup, fd) if url]
  3780. def urlencode_postdata(*args, **kargs):
  3781. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3782. def update_url(url, **kwargs):
  3783. """Replace URL components specified by kwargs
  3784. url: compat_str or parsed URL tuple
  3785. if query_update is in kwargs, update query with
  3786. its value instead of replacing (overrides any `query`)
  3787. NB: query_update expects parse_qs() format: [key: value_list, ...]
  3788. returns: compat_str
  3789. """
  3790. if not kwargs:
  3791. return compat_urllib_parse.urlunparse(url) if isinstance(url, tuple) else url
  3792. if not isinstance(url, tuple):
  3793. url = compat_urllib_parse.urlparse(url)
  3794. query = kwargs.pop('query_update', None)
  3795. if query:
  3796. qs = compat_parse_qs(url.query)
  3797. qs.update(query)
  3798. kwargs['query'] = compat_urllib_parse_urlencode(qs, True)
  3799. kwargs = compat_kwargs(kwargs)
  3800. return compat_urllib_parse.urlunparse(url._replace(**kwargs))
  3801. def update_url_query(url, query):
  3802. return update_url(url, query_update=query)
  3803. def update_Request(req, url=None, data=None, headers={}, query={}):
  3804. req_headers = req.headers.copy()
  3805. req_headers.update(headers)
  3806. req_data = data if data is not None else req.data
  3807. req_url = update_url_query(url or req.get_full_url(), query)
  3808. req_type = {'HEAD': HEADRequest, 'PUT': PUTRequest}.get(
  3809. req.get_method(), compat_urllib_request.Request)
  3810. new_req = req_type(
  3811. req_url, data=req_data, headers=req_headers,
  3812. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3813. if hasattr(req, 'timeout'):
  3814. new_req.timeout = req.timeout
  3815. return new_req
  3816. def _multipart_encode_impl(data, boundary):
  3817. content_type = 'multipart/form-data; boundary=%s' % boundary
  3818. out = b''
  3819. for k, v in data.items():
  3820. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3821. k = _encode_compat_str(k, 'utf-8')
  3822. v = _encode_compat_str(v, 'utf-8')
  3823. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3824. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3825. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3826. if boundary.encode('ascii') in content:
  3827. raise ValueError('Boundary overlaps with data')
  3828. out += content
  3829. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3830. return out, content_type
  3831. def multipart_encode(data, boundary=None):
  3832. '''
  3833. Encode a dict to RFC 7578-compliant form-data
  3834. data:
  3835. A dict where keys and values can be either Unicode or bytes-like
  3836. objects.
  3837. boundary:
  3838. If specified a Unicode object, it's used as the boundary. Otherwise
  3839. a random boundary is generated.
  3840. Reference: https://tools.ietf.org/html/rfc7578
  3841. '''
  3842. has_specified_boundary = boundary is not None
  3843. while True:
  3844. if boundary is None:
  3845. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3846. try:
  3847. out, content_type = _multipart_encode_impl(data, boundary)
  3848. break
  3849. except ValueError:
  3850. if has_specified_boundary:
  3851. raise
  3852. boundary = None
  3853. return out, content_type
  3854. def is_iterable_like(x, allowed_types=compat_collections_abc.Iterable, blocked_types=NO_DEFAULT):
  3855. if blocked_types is NO_DEFAULT:
  3856. blocked_types = (compat_str, bytes, compat_collections_abc.Mapping)
  3857. return isinstance(x, allowed_types) and not isinstance(x, blocked_types)
  3858. def variadic(x, allowed_types=NO_DEFAULT):
  3859. if isinstance(allowed_types, compat_collections_abc.Iterable):
  3860. allowed_types = tuple(allowed_types)
  3861. return x if is_iterable_like(x, blocked_types=allowed_types) else (x,)
  3862. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3863. exp = (lambda x: x or None) if skip_false_values else IDENTITY
  3864. return traverse_obj(d, *variadic(key_or_keys), expected_type=exp,
  3865. default=default, get_all=False)
  3866. def try_call(*funcs, **kwargs):
  3867. # parameter defaults
  3868. expected_type = kwargs.get('expected_type')
  3869. fargs = kwargs.get('args', [])
  3870. fkwargs = kwargs.get('kwargs', {})
  3871. for f in funcs:
  3872. try:
  3873. val = f(*fargs, **fkwargs)
  3874. except (AttributeError, KeyError, TypeError, IndexError, ZeroDivisionError):
  3875. pass
  3876. else:
  3877. if expected_type is None or isinstance(val, expected_type):
  3878. return val
  3879. def try_get(src, getter, expected_type=None):
  3880. if not isinstance(getter, (list, tuple)):
  3881. getter = [getter]
  3882. for get in getter:
  3883. try:
  3884. v = get(src)
  3885. except (AttributeError, KeyError, TypeError, IndexError):
  3886. pass
  3887. else:
  3888. if expected_type is None or isinstance(v, expected_type):
  3889. return v
  3890. def filter_dict(dct, cndn=lambda _, v: v is not None):
  3891. # NB: don't use dict comprehension for python 2.6 compatibility
  3892. return dict((k, v) for k, v in dct.items() if cndn(k, v))
  3893. def merge_dicts(*dicts, **kwargs):
  3894. """
  3895. Merge the `dict`s in `dicts` using the first valid value for each key.
  3896. Normally valid: not None and not an empty string
  3897. Keyword-only args:
  3898. unblank: allow empty string if False (default True)
  3899. rev: merge dicts in reverse order (default False)
  3900. merge_dicts(dct1, dct2, ..., unblank=False, rev=True)
  3901. matches {**dct1, **dct2, ...}
  3902. However, merge_dicts(dct1, dct2, ..., rev=True) may often be better.
  3903. """
  3904. unblank = kwargs.get('unblank', True)
  3905. rev = kwargs.get('rev', False)
  3906. if unblank:
  3907. def can_merge_str(k, v, to_dict):
  3908. return (isinstance(v, compat_str) and v
  3909. and isinstance(to_dict[k], compat_str)
  3910. and not to_dict[k])
  3911. else:
  3912. can_merge_str = lambda k, v, to_dict: False
  3913. merged = {}
  3914. for a_dict in reversed(dicts) if rev else dicts:
  3915. for k, v in a_dict.items():
  3916. if v is None:
  3917. continue
  3918. if (k not in merged) or can_merge_str(k, v, merged):
  3919. merged[k] = v
  3920. return merged
  3921. # very poor choice of name, as if Python string encodings weren't confusing enough
  3922. def encode_compat_str(s, encoding=preferredencoding(), errors='strict'):
  3923. assert isinstance(s, compat_basestring)
  3924. return s if isinstance(s, compat_str) else compat_str(s, encoding, errors)
  3925. # what it could have been
  3926. def _decode_compat_str(s, encoding=preferredencoding(), errors='strict', or_none=False):
  3927. if not or_none:
  3928. assert isinstance(s, compat_basestring)
  3929. return (
  3930. s if isinstance(s, compat_str)
  3931. else compat_str(s, encoding, errors) if isinstance(s, compat_basestring)
  3932. else None)
  3933. # the real encode_compat_str, but only for internal use
  3934. def _encode_compat_str(s, encoding=preferredencoding(), errors='strict'):
  3935. assert isinstance(s, compat_basestring)
  3936. return s.encode(encoding, errors) if isinstance(s, compat_str) else s
  3937. US_RATINGS = {
  3938. 'G': 0,
  3939. 'PG': 10,
  3940. 'PG-13': 13,
  3941. 'R': 16,
  3942. 'NC': 18,
  3943. }
  3944. TV_PARENTAL_GUIDELINES = {
  3945. 'TV-Y': 0,
  3946. 'TV-Y7': 7,
  3947. 'TV-G': 0,
  3948. 'TV-PG': 0,
  3949. 'TV-14': 14,
  3950. 'TV-MA': 17,
  3951. }
  3952. def parse_age_limit(s):
  3953. if not isinstance(s, bool):
  3954. age = int_or_none(s)
  3955. if age is not None:
  3956. return age if 0 <= age <= 21 else None
  3957. if not isinstance(s, compat_basestring):
  3958. return None
  3959. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3960. if m:
  3961. return int(m.group('age'))
  3962. if s in US_RATINGS:
  3963. return US_RATINGS[s]
  3964. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3965. if m:
  3966. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3967. return None
  3968. def strip_jsonp(code):
  3969. return re.sub(
  3970. r'''(?sx)^
  3971. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3972. (?:\s*&&\s*(?P=func_name))?
  3973. \s*\(\s*(?P<callback_data>.*)\);?
  3974. \s*?(?://[^\n]*)*$''',
  3975. r'\g<callback_data>', code)
  3976. def js_to_json(code, *args, **kwargs):
  3977. # vars is a dict of (var, val) pairs to substitute
  3978. vars = args[0] if len(args) > 0 else kwargs.get('vars', {})
  3979. strict = kwargs.get('strict', False)
  3980. STRING_QUOTES = '\'"`'
  3981. STRING_RE = '|'.join(r'{0}(?:\\.|[^\\{0}])*{0}'.format(q) for q in STRING_QUOTES)
  3982. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
  3983. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3984. INTEGER_TABLE = (
  3985. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3986. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3987. (r'(?s)^(\d+){skip}:?$'.format(skip=SKIP_RE), 10),
  3988. )
  3989. # compat candidate
  3990. JSONDecodeError = json.JSONDecodeError if 'JSONDecodeError' in dir(json) else ValueError
  3991. def process_escape(match):
  3992. JSON_PASSTHROUGH_ESCAPES = r'"\bfnrtu'
  3993. escape = match.group(1) or match.group(2)
  3994. return ('\\' + escape if escape in JSON_PASSTHROUGH_ESCAPES
  3995. else '\\u00' if escape == 'x'
  3996. else '' if escape == '\n'
  3997. else escape)
  3998. def template_substitute(match):
  3999. evaluated = js_to_json(match.group(1), vars, strict=strict)
  4000. if evaluated[0] == '"':
  4001. return json.loads(evaluated)
  4002. return evaluated
  4003. def fix_kv(m):
  4004. v = m.group(0)
  4005. if v in ('true', 'false', 'null'):
  4006. return v
  4007. elif v in ('undefined', 'void 0'):
  4008. return 'null'
  4009. elif v.startswith('/*') or v.startswith('//') or v == ',':
  4010. return ''
  4011. if v[0] in STRING_QUOTES:
  4012. v = re.sub(r'(?s)\${([^}]+)}', template_substitute, v[1:-1]) if v[0] == '`' else v[1:-1]
  4013. escaped = re.sub(r'(?s)(")|\\(.)', process_escape, v)
  4014. return '"{0}"'.format(escaped)
  4015. inv = IDENTITY
  4016. im = re.split(r'^!+', v)
  4017. if len(im) > 1 and not im[-1].endswith(':'):
  4018. if (len(v) - len(im[1])) % 2 == 1:
  4019. inv = lambda x: 'true' if x == 0 else 'false'
  4020. else:
  4021. inv = lambda x: 'false' if x == 0 else 'true'
  4022. if not any(x for x in im):
  4023. return
  4024. v = im[-1]
  4025. for regex, base in INTEGER_TABLE:
  4026. im = re.match(regex, v)
  4027. if im:
  4028. i = int(im.group(1), base)
  4029. return ('"%s":' if v.endswith(':') else '%s') % inv(i)
  4030. if v in vars:
  4031. try:
  4032. if not strict:
  4033. json.loads(vars[v])
  4034. except JSONDecodeError:
  4035. return inv(json.dumps(vars[v]))
  4036. else:
  4037. return inv(vars[v])
  4038. if not strict:
  4039. v = try_call(inv, args=(v,), default=v)
  4040. if v in ('true', 'false'):
  4041. return v
  4042. return '"{0}"'.format(v)
  4043. raise ValueError('Unknown value: ' + v)
  4044. def create_map(mobj):
  4045. return json.dumps(dict(json.loads(js_to_json(mobj.group(1) or '[]', vars=vars))))
  4046. code = re.sub(r'new Map\((\[.*?\])?\)', create_map, code)
  4047. if not strict:
  4048. code = re.sub(r'new Date\((".+")\)', r'\g<1>', code)
  4049. code = re.sub(r'new \w+\((.*?)\)', lambda m: json.dumps(m.group(0)), code)
  4050. code = re.sub(r'parseInt\([^\d]+(\d+)[^\d]+\)', r'\1', code)
  4051. code = re.sub(r'\(function\([^)]*\)\s*\{[^}]*\}\s*\)\s*\(\s*(["\'][^)]*["\'])\s*\)', r'\1', code)
  4052. return re.sub(r'''(?sx)
  4053. {str_}|
  4054. {comment}|
  4055. ,(?={skip}[\]}}])|
  4056. void\s0|
  4057. !*(?:(?<!\d)[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
  4058. (?:\b|!+)0(?:[xX][\da-fA-F]+|[0-7]+)(?:{skip}:)?|
  4059. !+\d+(?:\.\d*)?(?:{skip}:)?|
  4060. [0-9]+(?:{skip}:)|
  4061. !+
  4062. '''.format(comment=COMMENT_RE, skip=SKIP_RE, str_=STRING_RE), fix_kv, code)
  4063. def qualities(quality_ids):
  4064. """ Get a numeric quality value out of a list of possible values """
  4065. def q(qid):
  4066. try:
  4067. return quality_ids.index(qid)
  4068. except ValueError:
  4069. return -1
  4070. return q
  4071. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  4072. def limit_length(s, length):
  4073. """ Add ellipses to overly long strings """
  4074. if s is None:
  4075. return None
  4076. ELLIPSES = '...'
  4077. if len(s) > length:
  4078. return s[:length - len(ELLIPSES)] + ELLIPSES
  4079. return s
  4080. def version_tuple(v):
  4081. return tuple(int(e) for e in re.split(r'[-.]', v))
  4082. def is_outdated_version(version, limit, assume_new=True):
  4083. if not version:
  4084. return not assume_new
  4085. try:
  4086. return version_tuple(version) < version_tuple(limit)
  4087. except ValueError:
  4088. return not assume_new
  4089. def ytdl_is_updateable():
  4090. """ Returns if youtube-dl can be updated with -U """
  4091. from zipimport import zipimporter
  4092. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  4093. def args_to_str(args):
  4094. # Get a short string representation for a subprocess command
  4095. return ' '.join(compat_shlex_quote(a) for a in args)
  4096. def error_to_compat_str(err):
  4097. return _decode_compat_str(str(err))
  4098. def mimetype2ext(mt):
  4099. if mt is None:
  4100. return None
  4101. ext = {
  4102. 'audio/mp4': 'm4a',
  4103. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  4104. # it's the most popular one
  4105. 'audio/mpeg': 'mp3',
  4106. }.get(mt)
  4107. if ext is not None:
  4108. return ext
  4109. _, _, res = mt.rpartition('/')
  4110. res = res.split(';')[0].strip().lower()
  4111. return {
  4112. '3gpp': '3gp',
  4113. 'smptett+xml': 'tt',
  4114. 'ttaf+xml': 'dfxp',
  4115. 'ttml+xml': 'ttml',
  4116. 'x-flv': 'flv',
  4117. 'x-mp4-fragmented': 'mp4',
  4118. 'x-ms-sami': 'sami',
  4119. 'x-ms-wmv': 'wmv',
  4120. 'mpegurl': 'm3u8',
  4121. 'x-mpegurl': 'm3u8',
  4122. 'vnd.apple.mpegurl': 'm3u8',
  4123. 'dash+xml': 'mpd',
  4124. 'f4m+xml': 'f4m',
  4125. 'hds+xml': 'f4m',
  4126. 'vnd.ms-sstr+xml': 'ism',
  4127. 'quicktime': 'mov',
  4128. 'mp2t': 'ts',
  4129. 'x-wav': 'wav',
  4130. }.get(res, res)
  4131. def parse_codecs(codecs_str):
  4132. # http://tools.ietf.org/html/rfc6381
  4133. if not codecs_str:
  4134. return {}
  4135. split_codecs = list(filter(None, map(
  4136. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  4137. vcodec, acodec = None, None
  4138. for full_codec in split_codecs:
  4139. codec = full_codec.split('.')[0]
  4140. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  4141. if not vcodec:
  4142. vcodec = full_codec
  4143. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  4144. if not acodec:
  4145. acodec = full_codec
  4146. else:
  4147. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  4148. if not vcodec and not acodec:
  4149. if len(split_codecs) == 2:
  4150. return {
  4151. 'vcodec': split_codecs[0],
  4152. 'acodec': split_codecs[1],
  4153. }
  4154. else:
  4155. return {
  4156. 'vcodec': vcodec or 'none',
  4157. 'acodec': acodec or 'none',
  4158. }
  4159. return {}
  4160. def urlhandle_detect_ext(url_handle):
  4161. getheader = url_handle.headers.get
  4162. cd = getheader('Content-Disposition')
  4163. if cd:
  4164. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  4165. if m:
  4166. e = determine_ext(m.group('filename'), default_ext=None)
  4167. if e:
  4168. return e
  4169. return mimetype2ext(getheader('Content-Type'))
  4170. def encode_data_uri(data, mime_type):
  4171. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  4172. def age_restricted(content_limit, age_limit):
  4173. """ Returns True iff the content should be blocked """
  4174. if age_limit is None: # No limit set
  4175. return False
  4176. if content_limit is None:
  4177. return False # Content available for everyone
  4178. return age_limit < content_limit
  4179. def is_html(first_bytes):
  4180. """ Detect whether a file contains HTML by examining its first bytes. """
  4181. BOMS = [
  4182. (b'\xef\xbb\xbf', 'utf-8'),
  4183. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  4184. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  4185. (b'\xff\xfe', 'utf-16-le'),
  4186. (b'\xfe\xff', 'utf-16-be'),
  4187. ]
  4188. for bom, enc in BOMS:
  4189. if first_bytes.startswith(bom):
  4190. s = first_bytes[len(bom):].decode(enc, 'replace')
  4191. break
  4192. else:
  4193. s = first_bytes.decode('utf-8', 'replace')
  4194. return re.match(r'^\s*<', s)
  4195. def determine_protocol(info_dict):
  4196. protocol = info_dict.get('protocol')
  4197. if protocol is not None:
  4198. return protocol
  4199. url = info_dict['url']
  4200. if url.startswith('rtmp'):
  4201. return 'rtmp'
  4202. elif url.startswith('mms'):
  4203. return 'mms'
  4204. elif url.startswith('rtsp'):
  4205. return 'rtsp'
  4206. ext = determine_ext(url)
  4207. if ext == 'm3u8':
  4208. return 'm3u8'
  4209. elif ext == 'f4m':
  4210. return 'f4m'
  4211. return compat_urllib_parse_urlparse(url).scheme
  4212. def render_table(header_row, data):
  4213. """ Render a list of rows, each as a list of values """
  4214. table = [header_row] + data
  4215. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  4216. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  4217. return '\n'.join(format_str % tuple(row) for row in table)
  4218. def _match_one(filter_part, dct):
  4219. COMPARISON_OPERATORS = {
  4220. '<': operator.lt,
  4221. '<=': operator.le,
  4222. '>': operator.gt,
  4223. '>=': operator.ge,
  4224. '=': operator.eq,
  4225. '!=': operator.ne,
  4226. }
  4227. operator_rex = re.compile(r'''(?x)\s*
  4228. (?P<key>[a-z_]+)
  4229. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  4230. (?:
  4231. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  4232. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  4233. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  4234. )
  4235. \s*$
  4236. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  4237. m = operator_rex.search(filter_part)
  4238. if m:
  4239. op = COMPARISON_OPERATORS[m.group('op')]
  4240. actual_value = dct.get(m.group('key'))
  4241. if (m.group('quotedstrval') is not None
  4242. or m.group('strval') is not None
  4243. # If the original field is a string and matching comparisonvalue is
  4244. # a number we should respect the origin of the original field
  4245. # and process comparison value as a string (see
  4246. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  4247. or actual_value is not None and m.group('intval') is not None
  4248. and isinstance(actual_value, compat_str)):
  4249. if m.group('op') not in ('=', '!='):
  4250. raise ValueError(
  4251. 'Operator %s does not support string values!' % m.group('op'))
  4252. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  4253. quote = m.group('quote')
  4254. if quote is not None:
  4255. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  4256. else:
  4257. try:
  4258. comparison_value = int(m.group('intval'))
  4259. except ValueError:
  4260. comparison_value = parse_filesize(m.group('intval'))
  4261. if comparison_value is None:
  4262. comparison_value = parse_filesize(m.group('intval') + 'B')
  4263. if comparison_value is None:
  4264. raise ValueError(
  4265. 'Invalid integer value %r in filter part %r' % (
  4266. m.group('intval'), filter_part))
  4267. if actual_value is None:
  4268. return m.group('none_inclusive')
  4269. return op(actual_value, comparison_value)
  4270. UNARY_OPERATORS = {
  4271. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  4272. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  4273. }
  4274. operator_rex = re.compile(r'''(?x)\s*
  4275. (?P<op>%s)\s*(?P<key>[a-z_]+)
  4276. \s*$
  4277. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  4278. m = operator_rex.search(filter_part)
  4279. if m:
  4280. op = UNARY_OPERATORS[m.group('op')]
  4281. actual_value = dct.get(m.group('key'))
  4282. return op(actual_value)
  4283. raise ValueError('Invalid filter part %r' % filter_part)
  4284. def match_str(filter_str, dct):
  4285. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  4286. return all(
  4287. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  4288. def match_filter_func(filter_str):
  4289. def _match_func(info_dict):
  4290. if match_str(filter_str, info_dict):
  4291. return None
  4292. else:
  4293. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  4294. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  4295. return _match_func
  4296. def parse_dfxp_time_expr(time_expr):
  4297. if not time_expr:
  4298. return
  4299. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  4300. if mobj:
  4301. return float(mobj.group('time_offset'))
  4302. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  4303. if mobj:
  4304. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  4305. def srt_subtitles_timecode(seconds):
  4306. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  4307. def dfxp2srt(dfxp_data):
  4308. '''
  4309. @param dfxp_data A bytes-like object containing DFXP data
  4310. @returns A unicode object containing converted SRT data
  4311. '''
  4312. LEGACY_NAMESPACES = (
  4313. (b'http://www.w3.org/ns/ttml', [
  4314. b'http://www.w3.org/2004/11/ttaf1',
  4315. b'http://www.w3.org/2006/04/ttaf1',
  4316. b'http://www.w3.org/2006/10/ttaf1',
  4317. ]),
  4318. (b'http://www.w3.org/ns/ttml#styling', [
  4319. b'http://www.w3.org/ns/ttml#style',
  4320. ]),
  4321. )
  4322. SUPPORTED_STYLING = [
  4323. 'color',
  4324. 'fontFamily',
  4325. 'fontSize',
  4326. 'fontStyle',
  4327. 'fontWeight',
  4328. 'textDecoration'
  4329. ]
  4330. _x = functools.partial(xpath_with_ns, ns_map={
  4331. 'xml': 'http://www.w3.org/XML/1998/namespace',
  4332. 'ttml': 'http://www.w3.org/ns/ttml',
  4333. 'tts': 'http://www.w3.org/ns/ttml#styling',
  4334. })
  4335. styles = {}
  4336. default_style = {}
  4337. class TTMLPElementParser(object):
  4338. _out = ''
  4339. _unclosed_elements = []
  4340. _applied_styles = []
  4341. def start(self, tag, attrib):
  4342. if tag in (_x('ttml:br'), 'br'):
  4343. self._out += '\n'
  4344. else:
  4345. unclosed_elements = []
  4346. style = {}
  4347. element_style_id = attrib.get('style')
  4348. if default_style:
  4349. style.update(default_style)
  4350. if element_style_id:
  4351. style.update(styles.get(element_style_id, {}))
  4352. for prop in SUPPORTED_STYLING:
  4353. prop_val = attrib.get(_x('tts:' + prop))
  4354. if prop_val:
  4355. style[prop] = prop_val
  4356. if style:
  4357. font = ''
  4358. for k, v in sorted(style.items()):
  4359. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  4360. continue
  4361. if k == 'color':
  4362. font += ' color="%s"' % v
  4363. elif k == 'fontSize':
  4364. font += ' size="%s"' % v
  4365. elif k == 'fontFamily':
  4366. font += ' face="%s"' % v
  4367. elif k == 'fontWeight' and v == 'bold':
  4368. self._out += '<b>'
  4369. unclosed_elements.append('b')
  4370. elif k == 'fontStyle' and v == 'italic':
  4371. self._out += '<i>'
  4372. unclosed_elements.append('i')
  4373. elif k == 'textDecoration' and v == 'underline':
  4374. self._out += '<u>'
  4375. unclosed_elements.append('u')
  4376. if font:
  4377. self._out += '<font' + font + '>'
  4378. unclosed_elements.append('font')
  4379. applied_style = {}
  4380. if self._applied_styles:
  4381. applied_style.update(self._applied_styles[-1])
  4382. applied_style.update(style)
  4383. self._applied_styles.append(applied_style)
  4384. self._unclosed_elements.append(unclosed_elements)
  4385. def end(self, tag):
  4386. if tag not in (_x('ttml:br'), 'br'):
  4387. unclosed_elements = self._unclosed_elements.pop()
  4388. for element in reversed(unclosed_elements):
  4389. self._out += '</%s>' % element
  4390. if unclosed_elements and self._applied_styles:
  4391. self._applied_styles.pop()
  4392. def data(self, data):
  4393. self._out += data
  4394. def close(self):
  4395. return self._out.strip()
  4396. def parse_node(node):
  4397. target = TTMLPElementParser()
  4398. parser = xml.etree.ElementTree.XMLParser(target=target)
  4399. parser.feed(xml.etree.ElementTree.tostring(node))
  4400. return parser.close()
  4401. for k, v in LEGACY_NAMESPACES:
  4402. for ns in v:
  4403. dfxp_data = dfxp_data.replace(ns, k)
  4404. dfxp = compat_etree_fromstring(dfxp_data)
  4405. out = []
  4406. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  4407. if not paras:
  4408. raise ValueError('Invalid dfxp/TTML subtitle')
  4409. repeat = False
  4410. while True:
  4411. for style in dfxp.findall(_x('.//ttml:style')):
  4412. style_id = style.get('id') or style.get(_x('xml:id'))
  4413. if not style_id:
  4414. continue
  4415. parent_style_id = style.get('style')
  4416. if parent_style_id:
  4417. if parent_style_id not in styles:
  4418. repeat = True
  4419. continue
  4420. styles[style_id] = styles[parent_style_id].copy()
  4421. for prop in SUPPORTED_STYLING:
  4422. prop_val = style.get(_x('tts:' + prop))
  4423. if prop_val:
  4424. styles.setdefault(style_id, {})[prop] = prop_val
  4425. if repeat:
  4426. repeat = False
  4427. else:
  4428. break
  4429. for p in ('body', 'div'):
  4430. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  4431. if ele is None:
  4432. continue
  4433. style = styles.get(ele.get('style'))
  4434. if not style:
  4435. continue
  4436. default_style.update(style)
  4437. for para, index in zip(paras, itertools.count(1)):
  4438. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  4439. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  4440. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  4441. if begin_time is None:
  4442. continue
  4443. if not end_time:
  4444. if not dur:
  4445. continue
  4446. end_time = begin_time + dur
  4447. out.append('%d\n%s --> %s\n%s\n\n' % (
  4448. index,
  4449. srt_subtitles_timecode(begin_time),
  4450. srt_subtitles_timecode(end_time),
  4451. parse_node(para)))
  4452. return ''.join(out)
  4453. def cli_option(params, command_option, param):
  4454. param = params.get(param)
  4455. if param:
  4456. param = compat_str(param)
  4457. return [command_option, param] if param is not None else []
  4458. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  4459. param = params.get(param)
  4460. if param is None:
  4461. return []
  4462. assert isinstance(param, bool)
  4463. if separator:
  4464. return [command_option + separator + (true_value if param else false_value)]
  4465. return [command_option, true_value if param else false_value]
  4466. def cli_valueless_option(params, command_option, param, expected_value=True):
  4467. param = params.get(param)
  4468. return [command_option] if param == expected_value else []
  4469. def cli_configuration_args(params, param, default=[]):
  4470. ex_args = params.get(param)
  4471. if ex_args is None:
  4472. return default
  4473. assert isinstance(ex_args, list)
  4474. return ex_args
  4475. class ISO639Utils(object):
  4476. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  4477. _lang_map = {
  4478. 'aa': 'aar',
  4479. 'ab': 'abk',
  4480. 'ae': 'ave',
  4481. 'af': 'afr',
  4482. 'ak': 'aka',
  4483. 'am': 'amh',
  4484. 'an': 'arg',
  4485. 'ar': 'ara',
  4486. 'as': 'asm',
  4487. 'av': 'ava',
  4488. 'ay': 'aym',
  4489. 'az': 'aze',
  4490. 'ba': 'bak',
  4491. 'be': 'bel',
  4492. 'bg': 'bul',
  4493. 'bh': 'bih',
  4494. 'bi': 'bis',
  4495. 'bm': 'bam',
  4496. 'bn': 'ben',
  4497. 'bo': 'bod',
  4498. 'br': 'bre',
  4499. 'bs': 'bos',
  4500. 'ca': 'cat',
  4501. 'ce': 'che',
  4502. 'ch': 'cha',
  4503. 'co': 'cos',
  4504. 'cr': 'cre',
  4505. 'cs': 'ces',
  4506. 'cu': 'chu',
  4507. 'cv': 'chv',
  4508. 'cy': 'cym',
  4509. 'da': 'dan',
  4510. 'de': 'deu',
  4511. 'dv': 'div',
  4512. 'dz': 'dzo',
  4513. 'ee': 'ewe',
  4514. 'el': 'ell',
  4515. 'en': 'eng',
  4516. 'eo': 'epo',
  4517. 'es': 'spa',
  4518. 'et': 'est',
  4519. 'eu': 'eus',
  4520. 'fa': 'fas',
  4521. 'ff': 'ful',
  4522. 'fi': 'fin',
  4523. 'fj': 'fij',
  4524. 'fo': 'fao',
  4525. 'fr': 'fra',
  4526. 'fy': 'fry',
  4527. 'ga': 'gle',
  4528. 'gd': 'gla',
  4529. 'gl': 'glg',
  4530. 'gn': 'grn',
  4531. 'gu': 'guj',
  4532. 'gv': 'glv',
  4533. 'ha': 'hau',
  4534. 'he': 'heb',
  4535. 'iw': 'heb', # Replaced by he in 1989 revision
  4536. 'hi': 'hin',
  4537. 'ho': 'hmo',
  4538. 'hr': 'hrv',
  4539. 'ht': 'hat',
  4540. 'hu': 'hun',
  4541. 'hy': 'hye',
  4542. 'hz': 'her',
  4543. 'ia': 'ina',
  4544. 'id': 'ind',
  4545. 'in': 'ind', # Replaced by id in 1989 revision
  4546. 'ie': 'ile',
  4547. 'ig': 'ibo',
  4548. 'ii': 'iii',
  4549. 'ik': 'ipk',
  4550. 'io': 'ido',
  4551. 'is': 'isl',
  4552. 'it': 'ita',
  4553. 'iu': 'iku',
  4554. 'ja': 'jpn',
  4555. 'jv': 'jav',
  4556. 'ka': 'kat',
  4557. 'kg': 'kon',
  4558. 'ki': 'kik',
  4559. 'kj': 'kua',
  4560. 'kk': 'kaz',
  4561. 'kl': 'kal',
  4562. 'km': 'khm',
  4563. 'kn': 'kan',
  4564. 'ko': 'kor',
  4565. 'kr': 'kau',
  4566. 'ks': 'kas',
  4567. 'ku': 'kur',
  4568. 'kv': 'kom',
  4569. 'kw': 'cor',
  4570. 'ky': 'kir',
  4571. 'la': 'lat',
  4572. 'lb': 'ltz',
  4573. 'lg': 'lug',
  4574. 'li': 'lim',
  4575. 'ln': 'lin',
  4576. 'lo': 'lao',
  4577. 'lt': 'lit',
  4578. 'lu': 'lub',
  4579. 'lv': 'lav',
  4580. 'mg': 'mlg',
  4581. 'mh': 'mah',
  4582. 'mi': 'mri',
  4583. 'mk': 'mkd',
  4584. 'ml': 'mal',
  4585. 'mn': 'mon',
  4586. 'mr': 'mar',
  4587. 'ms': 'msa',
  4588. 'mt': 'mlt',
  4589. 'my': 'mya',
  4590. 'na': 'nau',
  4591. 'nb': 'nob',
  4592. 'nd': 'nde',
  4593. 'ne': 'nep',
  4594. 'ng': 'ndo',
  4595. 'nl': 'nld',
  4596. 'nn': 'nno',
  4597. 'no': 'nor',
  4598. 'nr': 'nbl',
  4599. 'nv': 'nav',
  4600. 'ny': 'nya',
  4601. 'oc': 'oci',
  4602. 'oj': 'oji',
  4603. 'om': 'orm',
  4604. 'or': 'ori',
  4605. 'os': 'oss',
  4606. 'pa': 'pan',
  4607. 'pi': 'pli',
  4608. 'pl': 'pol',
  4609. 'ps': 'pus',
  4610. 'pt': 'por',
  4611. 'qu': 'que',
  4612. 'rm': 'roh',
  4613. 'rn': 'run',
  4614. 'ro': 'ron',
  4615. 'ru': 'rus',
  4616. 'rw': 'kin',
  4617. 'sa': 'san',
  4618. 'sc': 'srd',
  4619. 'sd': 'snd',
  4620. 'se': 'sme',
  4621. 'sg': 'sag',
  4622. 'si': 'sin',
  4623. 'sk': 'slk',
  4624. 'sl': 'slv',
  4625. 'sm': 'smo',
  4626. 'sn': 'sna',
  4627. 'so': 'som',
  4628. 'sq': 'sqi',
  4629. 'sr': 'srp',
  4630. 'ss': 'ssw',
  4631. 'st': 'sot',
  4632. 'su': 'sun',
  4633. 'sv': 'swe',
  4634. 'sw': 'swa',
  4635. 'ta': 'tam',
  4636. 'te': 'tel',
  4637. 'tg': 'tgk',
  4638. 'th': 'tha',
  4639. 'ti': 'tir',
  4640. 'tk': 'tuk',
  4641. 'tl': 'tgl',
  4642. 'tn': 'tsn',
  4643. 'to': 'ton',
  4644. 'tr': 'tur',
  4645. 'ts': 'tso',
  4646. 'tt': 'tat',
  4647. 'tw': 'twi',
  4648. 'ty': 'tah',
  4649. 'ug': 'uig',
  4650. 'uk': 'ukr',
  4651. 'ur': 'urd',
  4652. 'uz': 'uzb',
  4653. 've': 'ven',
  4654. 'vi': 'vie',
  4655. 'vo': 'vol',
  4656. 'wa': 'wln',
  4657. 'wo': 'wol',
  4658. 'xh': 'xho',
  4659. 'yi': 'yid',
  4660. 'ji': 'yid', # Replaced by yi in 1989 revision
  4661. 'yo': 'yor',
  4662. 'za': 'zha',
  4663. 'zh': 'zho',
  4664. 'zu': 'zul',
  4665. }
  4666. @classmethod
  4667. def short2long(cls, code):
  4668. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4669. return cls._lang_map.get(code[:2])
  4670. @classmethod
  4671. def long2short(cls, code):
  4672. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4673. for short_name, long_name in cls._lang_map.items():
  4674. if long_name == code:
  4675. return short_name
  4676. class ISO3166Utils(object):
  4677. # From http://data.okfn.org/data/core/country-list
  4678. _country_map = {
  4679. 'AF': 'Afghanistan',
  4680. 'AX': 'Åland Islands',
  4681. 'AL': 'Albania',
  4682. 'DZ': 'Algeria',
  4683. 'AS': 'American Samoa',
  4684. 'AD': 'Andorra',
  4685. 'AO': 'Angola',
  4686. 'AI': 'Anguilla',
  4687. 'AQ': 'Antarctica',
  4688. 'AG': 'Antigua and Barbuda',
  4689. 'AR': 'Argentina',
  4690. 'AM': 'Armenia',
  4691. 'AW': 'Aruba',
  4692. 'AU': 'Australia',
  4693. 'AT': 'Austria',
  4694. 'AZ': 'Azerbaijan',
  4695. 'BS': 'Bahamas',
  4696. 'BH': 'Bahrain',
  4697. 'BD': 'Bangladesh',
  4698. 'BB': 'Barbados',
  4699. 'BY': 'Belarus',
  4700. 'BE': 'Belgium',
  4701. 'BZ': 'Belize',
  4702. 'BJ': 'Benin',
  4703. 'BM': 'Bermuda',
  4704. 'BT': 'Bhutan',
  4705. 'BO': 'Bolivia, Plurinational State of',
  4706. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4707. 'BA': 'Bosnia and Herzegovina',
  4708. 'BW': 'Botswana',
  4709. 'BV': 'Bouvet Island',
  4710. 'BR': 'Brazil',
  4711. 'IO': 'British Indian Ocean Territory',
  4712. 'BN': 'Brunei Darussalam',
  4713. 'BG': 'Bulgaria',
  4714. 'BF': 'Burkina Faso',
  4715. 'BI': 'Burundi',
  4716. 'KH': 'Cambodia',
  4717. 'CM': 'Cameroon',
  4718. 'CA': 'Canada',
  4719. 'CV': 'Cape Verde',
  4720. 'KY': 'Cayman Islands',
  4721. 'CF': 'Central African Republic',
  4722. 'TD': 'Chad',
  4723. 'CL': 'Chile',
  4724. 'CN': 'China',
  4725. 'CX': 'Christmas Island',
  4726. 'CC': 'Cocos (Keeling) Islands',
  4727. 'CO': 'Colombia',
  4728. 'KM': 'Comoros',
  4729. 'CG': 'Congo',
  4730. 'CD': 'Congo, the Democratic Republic of the',
  4731. 'CK': 'Cook Islands',
  4732. 'CR': 'Costa Rica',
  4733. 'CI': 'Côte d\'Ivoire',
  4734. 'HR': 'Croatia',
  4735. 'CU': 'Cuba',
  4736. 'CW': 'Curaçao',
  4737. 'CY': 'Cyprus',
  4738. 'CZ': 'Czech Republic',
  4739. 'DK': 'Denmark',
  4740. 'DJ': 'Djibouti',
  4741. 'DM': 'Dominica',
  4742. 'DO': 'Dominican Republic',
  4743. 'EC': 'Ecuador',
  4744. 'EG': 'Egypt',
  4745. 'SV': 'El Salvador',
  4746. 'GQ': 'Equatorial Guinea',
  4747. 'ER': 'Eritrea',
  4748. 'EE': 'Estonia',
  4749. 'ET': 'Ethiopia',
  4750. 'FK': 'Falkland Islands (Malvinas)',
  4751. 'FO': 'Faroe Islands',
  4752. 'FJ': 'Fiji',
  4753. 'FI': 'Finland',
  4754. 'FR': 'France',
  4755. 'GF': 'French Guiana',
  4756. 'PF': 'French Polynesia',
  4757. 'TF': 'French Southern Territories',
  4758. 'GA': 'Gabon',
  4759. 'GM': 'Gambia',
  4760. 'GE': 'Georgia',
  4761. 'DE': 'Germany',
  4762. 'GH': 'Ghana',
  4763. 'GI': 'Gibraltar',
  4764. 'GR': 'Greece',
  4765. 'GL': 'Greenland',
  4766. 'GD': 'Grenada',
  4767. 'GP': 'Guadeloupe',
  4768. 'GU': 'Guam',
  4769. 'GT': 'Guatemala',
  4770. 'GG': 'Guernsey',
  4771. 'GN': 'Guinea',
  4772. 'GW': 'Guinea-Bissau',
  4773. 'GY': 'Guyana',
  4774. 'HT': 'Haiti',
  4775. 'HM': 'Heard Island and McDonald Islands',
  4776. 'VA': 'Holy See (Vatican City State)',
  4777. 'HN': 'Honduras',
  4778. 'HK': 'Hong Kong',
  4779. 'HU': 'Hungary',
  4780. 'IS': 'Iceland',
  4781. 'IN': 'India',
  4782. 'ID': 'Indonesia',
  4783. 'IR': 'Iran, Islamic Republic of',
  4784. 'IQ': 'Iraq',
  4785. 'IE': 'Ireland',
  4786. 'IM': 'Isle of Man',
  4787. 'IL': 'Israel',
  4788. 'IT': 'Italy',
  4789. 'JM': 'Jamaica',
  4790. 'JP': 'Japan',
  4791. 'JE': 'Jersey',
  4792. 'JO': 'Jordan',
  4793. 'KZ': 'Kazakhstan',
  4794. 'KE': 'Kenya',
  4795. 'KI': 'Kiribati',
  4796. 'KP': 'Korea, Democratic People\'s Republic of',
  4797. 'KR': 'Korea, Republic of',
  4798. 'KW': 'Kuwait',
  4799. 'KG': 'Kyrgyzstan',
  4800. 'LA': 'Lao People\'s Democratic Republic',
  4801. 'LV': 'Latvia',
  4802. 'LB': 'Lebanon',
  4803. 'LS': 'Lesotho',
  4804. 'LR': 'Liberia',
  4805. 'LY': 'Libya',
  4806. 'LI': 'Liechtenstein',
  4807. 'LT': 'Lithuania',
  4808. 'LU': 'Luxembourg',
  4809. 'MO': 'Macao',
  4810. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4811. 'MG': 'Madagascar',
  4812. 'MW': 'Malawi',
  4813. 'MY': 'Malaysia',
  4814. 'MV': 'Maldives',
  4815. 'ML': 'Mali',
  4816. 'MT': 'Malta',
  4817. 'MH': 'Marshall Islands',
  4818. 'MQ': 'Martinique',
  4819. 'MR': 'Mauritania',
  4820. 'MU': 'Mauritius',
  4821. 'YT': 'Mayotte',
  4822. 'MX': 'Mexico',
  4823. 'FM': 'Micronesia, Federated States of',
  4824. 'MD': 'Moldova, Republic of',
  4825. 'MC': 'Monaco',
  4826. 'MN': 'Mongolia',
  4827. 'ME': 'Montenegro',
  4828. 'MS': 'Montserrat',
  4829. 'MA': 'Morocco',
  4830. 'MZ': 'Mozambique',
  4831. 'MM': 'Myanmar',
  4832. 'NA': 'Namibia',
  4833. 'NR': 'Nauru',
  4834. 'NP': 'Nepal',
  4835. 'NL': 'Netherlands',
  4836. 'NC': 'New Caledonia',
  4837. 'NZ': 'New Zealand',
  4838. 'NI': 'Nicaragua',
  4839. 'NE': 'Niger',
  4840. 'NG': 'Nigeria',
  4841. 'NU': 'Niue',
  4842. 'NF': 'Norfolk Island',
  4843. 'MP': 'Northern Mariana Islands',
  4844. 'NO': 'Norway',
  4845. 'OM': 'Oman',
  4846. 'PK': 'Pakistan',
  4847. 'PW': 'Palau',
  4848. 'PS': 'Palestine, State of',
  4849. 'PA': 'Panama',
  4850. 'PG': 'Papua New Guinea',
  4851. 'PY': 'Paraguay',
  4852. 'PE': 'Peru',
  4853. 'PH': 'Philippines',
  4854. 'PN': 'Pitcairn',
  4855. 'PL': 'Poland',
  4856. 'PT': 'Portugal',
  4857. 'PR': 'Puerto Rico',
  4858. 'QA': 'Qatar',
  4859. 'RE': 'Réunion',
  4860. 'RO': 'Romania',
  4861. 'RU': 'Russian Federation',
  4862. 'RW': 'Rwanda',
  4863. 'BL': 'Saint Barthélemy',
  4864. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4865. 'KN': 'Saint Kitts and Nevis',
  4866. 'LC': 'Saint Lucia',
  4867. 'MF': 'Saint Martin (French part)',
  4868. 'PM': 'Saint Pierre and Miquelon',
  4869. 'VC': 'Saint Vincent and the Grenadines',
  4870. 'WS': 'Samoa',
  4871. 'SM': 'San Marino',
  4872. 'ST': 'Sao Tome and Principe',
  4873. 'SA': 'Saudi Arabia',
  4874. 'SN': 'Senegal',
  4875. 'RS': 'Serbia',
  4876. 'SC': 'Seychelles',
  4877. 'SL': 'Sierra Leone',
  4878. 'SG': 'Singapore',
  4879. 'SX': 'Sint Maarten (Dutch part)',
  4880. 'SK': 'Slovakia',
  4881. 'SI': 'Slovenia',
  4882. 'SB': 'Solomon Islands',
  4883. 'SO': 'Somalia',
  4884. 'ZA': 'South Africa',
  4885. 'GS': 'South Georgia and the South Sandwich Islands',
  4886. 'SS': 'South Sudan',
  4887. 'ES': 'Spain',
  4888. 'LK': 'Sri Lanka',
  4889. 'SD': 'Sudan',
  4890. 'SR': 'Suriname',
  4891. 'SJ': 'Svalbard and Jan Mayen',
  4892. 'SZ': 'Swaziland',
  4893. 'SE': 'Sweden',
  4894. 'CH': 'Switzerland',
  4895. 'SY': 'Syrian Arab Republic',
  4896. 'TW': 'Taiwan, Province of China',
  4897. 'TJ': 'Tajikistan',
  4898. 'TZ': 'Tanzania, United Republic of',
  4899. 'TH': 'Thailand',
  4900. 'TL': 'Timor-Leste',
  4901. 'TG': 'Togo',
  4902. 'TK': 'Tokelau',
  4903. 'TO': 'Tonga',
  4904. 'TT': 'Trinidad and Tobago',
  4905. 'TN': 'Tunisia',
  4906. 'TR': 'Turkey',
  4907. 'TM': 'Turkmenistan',
  4908. 'TC': 'Turks and Caicos Islands',
  4909. 'TV': 'Tuvalu',
  4910. 'UG': 'Uganda',
  4911. 'UA': 'Ukraine',
  4912. 'AE': 'United Arab Emirates',
  4913. 'GB': 'United Kingdom',
  4914. 'US': 'United States',
  4915. 'UM': 'United States Minor Outlying Islands',
  4916. 'UY': 'Uruguay',
  4917. 'UZ': 'Uzbekistan',
  4918. 'VU': 'Vanuatu',
  4919. 'VE': 'Venezuela, Bolivarian Republic of',
  4920. 'VN': 'Viet Nam',
  4921. 'VG': 'Virgin Islands, British',
  4922. 'VI': 'Virgin Islands, U.S.',
  4923. 'WF': 'Wallis and Futuna',
  4924. 'EH': 'Western Sahara',
  4925. 'YE': 'Yemen',
  4926. 'ZM': 'Zambia',
  4927. 'ZW': 'Zimbabwe',
  4928. }
  4929. @classmethod
  4930. def short2full(cls, code):
  4931. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4932. return cls._country_map.get(code.upper())
  4933. class GeoUtils(object):
  4934. # Major IPv4 address blocks per country
  4935. _country_ip_map = {
  4936. 'AD': '46.172.224.0/19',
  4937. 'AE': '94.200.0.0/13',
  4938. 'AF': '149.54.0.0/17',
  4939. 'AG': '209.59.64.0/18',
  4940. 'AI': '204.14.248.0/21',
  4941. 'AL': '46.99.0.0/16',
  4942. 'AM': '46.70.0.0/15',
  4943. 'AO': '105.168.0.0/13',
  4944. 'AP': '182.50.184.0/21',
  4945. 'AQ': '23.154.160.0/24',
  4946. 'AR': '181.0.0.0/12',
  4947. 'AS': '202.70.112.0/20',
  4948. 'AT': '77.116.0.0/14',
  4949. 'AU': '1.128.0.0/11',
  4950. 'AW': '181.41.0.0/18',
  4951. 'AX': '185.217.4.0/22',
  4952. 'AZ': '5.197.0.0/16',
  4953. 'BA': '31.176.128.0/17',
  4954. 'BB': '65.48.128.0/17',
  4955. 'BD': '114.130.0.0/16',
  4956. 'BE': '57.0.0.0/8',
  4957. 'BF': '102.178.0.0/15',
  4958. 'BG': '95.42.0.0/15',
  4959. 'BH': '37.131.0.0/17',
  4960. 'BI': '154.117.192.0/18',
  4961. 'BJ': '137.255.0.0/16',
  4962. 'BL': '185.212.72.0/23',
  4963. 'BM': '196.12.64.0/18',
  4964. 'BN': '156.31.0.0/16',
  4965. 'BO': '161.56.0.0/16',
  4966. 'BQ': '161.0.80.0/20',
  4967. 'BR': '191.128.0.0/12',
  4968. 'BS': '24.51.64.0/18',
  4969. 'BT': '119.2.96.0/19',
  4970. 'BW': '168.167.0.0/16',
  4971. 'BY': '178.120.0.0/13',
  4972. 'BZ': '179.42.192.0/18',
  4973. 'CA': '99.224.0.0/11',
  4974. 'CD': '41.243.0.0/16',
  4975. 'CF': '197.242.176.0/21',
  4976. 'CG': '160.113.0.0/16',
  4977. 'CH': '85.0.0.0/13',
  4978. 'CI': '102.136.0.0/14',
  4979. 'CK': '202.65.32.0/19',
  4980. 'CL': '152.172.0.0/14',
  4981. 'CM': '102.244.0.0/14',
  4982. 'CN': '36.128.0.0/10',
  4983. 'CO': '181.240.0.0/12',
  4984. 'CR': '201.192.0.0/12',
  4985. 'CU': '152.206.0.0/15',
  4986. 'CV': '165.90.96.0/19',
  4987. 'CW': '190.88.128.0/17',
  4988. 'CY': '31.153.0.0/16',
  4989. 'CZ': '88.100.0.0/14',
  4990. 'DE': '53.0.0.0/8',
  4991. 'DJ': '197.241.0.0/17',
  4992. 'DK': '87.48.0.0/12',
  4993. 'DM': '192.243.48.0/20',
  4994. 'DO': '152.166.0.0/15',
  4995. 'DZ': '41.96.0.0/12',
  4996. 'EC': '186.68.0.0/15',
  4997. 'EE': '90.190.0.0/15',
  4998. 'EG': '156.160.0.0/11',
  4999. 'ER': '196.200.96.0/20',
  5000. 'ES': '88.0.0.0/11',
  5001. 'ET': '196.188.0.0/14',
  5002. 'EU': '2.16.0.0/13',
  5003. 'FI': '91.152.0.0/13',
  5004. 'FJ': '144.120.0.0/16',
  5005. 'FK': '80.73.208.0/21',
  5006. 'FM': '119.252.112.0/20',
  5007. 'FO': '88.85.32.0/19',
  5008. 'FR': '90.0.0.0/9',
  5009. 'GA': '41.158.0.0/15',
  5010. 'GB': '25.0.0.0/8',
  5011. 'GD': '74.122.88.0/21',
  5012. 'GE': '31.146.0.0/16',
  5013. 'GF': '161.22.64.0/18',
  5014. 'GG': '62.68.160.0/19',
  5015. 'GH': '154.160.0.0/12',
  5016. 'GI': '95.164.0.0/16',
  5017. 'GL': '88.83.0.0/19',
  5018. 'GM': '160.182.0.0/15',
  5019. 'GN': '197.149.192.0/18',
  5020. 'GP': '104.250.0.0/19',
  5021. 'GQ': '105.235.224.0/20',
  5022. 'GR': '94.64.0.0/13',
  5023. 'GT': '168.234.0.0/16',
  5024. 'GU': '168.123.0.0/16',
  5025. 'GW': '197.214.80.0/20',
  5026. 'GY': '181.41.64.0/18',
  5027. 'HK': '113.252.0.0/14',
  5028. 'HN': '181.210.0.0/16',
  5029. 'HR': '93.136.0.0/13',
  5030. 'HT': '148.102.128.0/17',
  5031. 'HU': '84.0.0.0/14',
  5032. 'ID': '39.192.0.0/10',
  5033. 'IE': '87.32.0.0/12',
  5034. 'IL': '79.176.0.0/13',
  5035. 'IM': '5.62.80.0/20',
  5036. 'IN': '117.192.0.0/10',
  5037. 'IO': '203.83.48.0/21',
  5038. 'IQ': '37.236.0.0/14',
  5039. 'IR': '2.176.0.0/12',
  5040. 'IS': '82.221.0.0/16',
  5041. 'IT': '79.0.0.0/10',
  5042. 'JE': '87.244.64.0/18',
  5043. 'JM': '72.27.0.0/17',
  5044. 'JO': '176.29.0.0/16',
  5045. 'JP': '133.0.0.0/8',
  5046. 'KE': '105.48.0.0/12',
  5047. 'KG': '158.181.128.0/17',
  5048. 'KH': '36.37.128.0/17',
  5049. 'KI': '103.25.140.0/22',
  5050. 'KM': '197.255.224.0/20',
  5051. 'KN': '198.167.192.0/19',
  5052. 'KP': '175.45.176.0/22',
  5053. 'KR': '175.192.0.0/10',
  5054. 'KW': '37.36.0.0/14',
  5055. 'KY': '64.96.0.0/15',
  5056. 'KZ': '2.72.0.0/13',
  5057. 'LA': '115.84.64.0/18',
  5058. 'LB': '178.135.0.0/16',
  5059. 'LC': '24.92.144.0/20',
  5060. 'LI': '82.117.0.0/19',
  5061. 'LK': '112.134.0.0/15',
  5062. 'LR': '102.183.0.0/16',
  5063. 'LS': '129.232.0.0/17',
  5064. 'LT': '78.56.0.0/13',
  5065. 'LU': '188.42.0.0/16',
  5066. 'LV': '46.109.0.0/16',
  5067. 'LY': '41.252.0.0/14',
  5068. 'MA': '105.128.0.0/11',
  5069. 'MC': '88.209.64.0/18',
  5070. 'MD': '37.246.0.0/16',
  5071. 'ME': '178.175.0.0/17',
  5072. 'MF': '74.112.232.0/21',
  5073. 'MG': '154.126.0.0/17',
  5074. 'MH': '117.103.88.0/21',
  5075. 'MK': '77.28.0.0/15',
  5076. 'ML': '154.118.128.0/18',
  5077. 'MM': '37.111.0.0/17',
  5078. 'MN': '49.0.128.0/17',
  5079. 'MO': '60.246.0.0/16',
  5080. 'MP': '202.88.64.0/20',
  5081. 'MQ': '109.203.224.0/19',
  5082. 'MR': '41.188.64.0/18',
  5083. 'MS': '208.90.112.0/22',
  5084. 'MT': '46.11.0.0/16',
  5085. 'MU': '105.16.0.0/12',
  5086. 'MV': '27.114.128.0/18',
  5087. 'MW': '102.70.0.0/15',
  5088. 'MX': '187.192.0.0/11',
  5089. 'MY': '175.136.0.0/13',
  5090. 'MZ': '197.218.0.0/15',
  5091. 'NA': '41.182.0.0/16',
  5092. 'NC': '101.101.0.0/18',
  5093. 'NE': '197.214.0.0/18',
  5094. 'NF': '203.17.240.0/22',
  5095. 'NG': '105.112.0.0/12',
  5096. 'NI': '186.76.0.0/15',
  5097. 'NL': '145.96.0.0/11',
  5098. 'NO': '84.208.0.0/13',
  5099. 'NP': '36.252.0.0/15',
  5100. 'NR': '203.98.224.0/19',
  5101. 'NU': '49.156.48.0/22',
  5102. 'NZ': '49.224.0.0/14',
  5103. 'OM': '5.36.0.0/15',
  5104. 'PA': '186.72.0.0/15',
  5105. 'PE': '186.160.0.0/14',
  5106. 'PF': '123.50.64.0/18',
  5107. 'PG': '124.240.192.0/19',
  5108. 'PH': '49.144.0.0/13',
  5109. 'PK': '39.32.0.0/11',
  5110. 'PL': '83.0.0.0/11',
  5111. 'PM': '70.36.0.0/20',
  5112. 'PR': '66.50.0.0/16',
  5113. 'PS': '188.161.0.0/16',
  5114. 'PT': '85.240.0.0/13',
  5115. 'PW': '202.124.224.0/20',
  5116. 'PY': '181.120.0.0/14',
  5117. 'QA': '37.210.0.0/15',
  5118. 'RE': '102.35.0.0/16',
  5119. 'RO': '79.112.0.0/13',
  5120. 'RS': '93.86.0.0/15',
  5121. 'RU': '5.136.0.0/13',
  5122. 'RW': '41.186.0.0/16',
  5123. 'SA': '188.48.0.0/13',
  5124. 'SB': '202.1.160.0/19',
  5125. 'SC': '154.192.0.0/11',
  5126. 'SD': '102.120.0.0/13',
  5127. 'SE': '78.64.0.0/12',
  5128. 'SG': '8.128.0.0/10',
  5129. 'SI': '188.196.0.0/14',
  5130. 'SK': '78.98.0.0/15',
  5131. 'SL': '102.143.0.0/17',
  5132. 'SM': '89.186.32.0/19',
  5133. 'SN': '41.82.0.0/15',
  5134. 'SO': '154.115.192.0/18',
  5135. 'SR': '186.179.128.0/17',
  5136. 'SS': '105.235.208.0/21',
  5137. 'ST': '197.159.160.0/19',
  5138. 'SV': '168.243.0.0/16',
  5139. 'SX': '190.102.0.0/20',
  5140. 'SY': '5.0.0.0/16',
  5141. 'SZ': '41.84.224.0/19',
  5142. 'TC': '65.255.48.0/20',
  5143. 'TD': '154.68.128.0/19',
  5144. 'TG': '196.168.0.0/14',
  5145. 'TH': '171.96.0.0/13',
  5146. 'TJ': '85.9.128.0/18',
  5147. 'TK': '27.96.24.0/21',
  5148. 'TL': '180.189.160.0/20',
  5149. 'TM': '95.85.96.0/19',
  5150. 'TN': '197.0.0.0/11',
  5151. 'TO': '175.176.144.0/21',
  5152. 'TR': '78.160.0.0/11',
  5153. 'TT': '186.44.0.0/15',
  5154. 'TV': '202.2.96.0/19',
  5155. 'TW': '120.96.0.0/11',
  5156. 'TZ': '156.156.0.0/14',
  5157. 'UA': '37.52.0.0/14',
  5158. 'UG': '102.80.0.0/13',
  5159. 'US': '6.0.0.0/8',
  5160. 'UY': '167.56.0.0/13',
  5161. 'UZ': '84.54.64.0/18',
  5162. 'VA': '212.77.0.0/19',
  5163. 'VC': '207.191.240.0/21',
  5164. 'VE': '186.88.0.0/13',
  5165. 'VG': '66.81.192.0/20',
  5166. 'VI': '146.226.0.0/16',
  5167. 'VN': '14.160.0.0/11',
  5168. 'VU': '202.80.32.0/20',
  5169. 'WF': '117.20.32.0/21',
  5170. 'WS': '202.4.32.0/19',
  5171. 'YE': '134.35.0.0/16',
  5172. 'YT': '41.242.116.0/22',
  5173. 'ZA': '41.0.0.0/11',
  5174. 'ZM': '102.144.0.0/13',
  5175. 'ZW': '102.177.192.0/18',
  5176. }
  5177. @classmethod
  5178. def random_ipv4(cls, code_or_block):
  5179. if len(code_or_block) == 2:
  5180. block = cls._country_ip_map.get(code_or_block.upper())
  5181. if not block:
  5182. return None
  5183. else:
  5184. block = code_or_block
  5185. addr, preflen = block.split('/')
  5186. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  5187. addr_max = addr_min | (0xffffffff >> int(preflen))
  5188. return compat_str(socket.inet_ntoa(
  5189. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  5190. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  5191. def __init__(self, proxies=None):
  5192. # Set default handlers
  5193. for type in ('http', 'https'):
  5194. setattr(self, '%s_open' % type,
  5195. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  5196. meth(r, proxy, type))
  5197. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  5198. def proxy_open(self, req, proxy, type):
  5199. req_proxy = req.headers.get('Ytdl-request-proxy')
  5200. if req_proxy is not None:
  5201. proxy = req_proxy
  5202. del req.headers['Ytdl-request-proxy']
  5203. if proxy == '__noproxy__':
  5204. return None # No Proxy
  5205. if compat_urllib_parse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  5206. req.add_header('Ytdl-socks-proxy', proxy)
  5207. # youtube-dl's http/https handlers do wrapping the socket with socks
  5208. return None
  5209. return compat_urllib_request.ProxyHandler.proxy_open(
  5210. self, req, proxy, type)
  5211. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  5212. # released into Public Domain
  5213. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  5214. def long_to_bytes(n, blocksize=0):
  5215. """long_to_bytes(n:long, blocksize:int) : string
  5216. Convert a long integer to a byte string.
  5217. If optional blocksize is given and greater than zero, pad the front of the
  5218. byte string with binary zeros so that the length is a multiple of
  5219. blocksize.
  5220. """
  5221. # after much testing, this algorithm was deemed to be the fastest
  5222. s = b''
  5223. n = int(n)
  5224. while n > 0:
  5225. s = compat_struct_pack('>I', n & 0xffffffff) + s
  5226. n = n >> 32
  5227. # strip off leading zeros
  5228. for i in range(len(s)):
  5229. if s[i] != b'\000'[0]:
  5230. break
  5231. else:
  5232. # only happens when n == 0
  5233. s = b'\000'
  5234. i = 0
  5235. s = s[i:]
  5236. # add back some pad bytes. this could be done more efficiently w.r.t. the
  5237. # de-padding being done above, but sigh...
  5238. if blocksize > 0 and len(s) % blocksize:
  5239. s = (blocksize - len(s) % blocksize) * b'\000' + s
  5240. return s
  5241. def bytes_to_long(s):
  5242. """bytes_to_long(string) : long
  5243. Convert a byte string to a long integer.
  5244. This is (essentially) the inverse of long_to_bytes().
  5245. """
  5246. acc = 0
  5247. length = len(s)
  5248. if length % 4:
  5249. extra = (4 - length % 4)
  5250. s = b'\000' * extra + s
  5251. length = length + extra
  5252. for i in range(0, length, 4):
  5253. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  5254. return acc
  5255. def ohdave_rsa_encrypt(data, exponent, modulus):
  5256. '''
  5257. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  5258. Input:
  5259. data: data to encrypt, bytes-like object
  5260. exponent, modulus: parameter e and N of RSA algorithm, both integer
  5261. Output: hex string of encrypted data
  5262. Limitation: supports one block encryption only
  5263. '''
  5264. payload = int(binascii.hexlify(data[::-1]), 16)
  5265. encrypted = pow(payload, exponent, modulus)
  5266. return '%x' % encrypted
  5267. def pkcs1pad(data, length):
  5268. """
  5269. Padding input data with PKCS#1 scheme
  5270. @param {int[]} data input data
  5271. @param {int} length target length
  5272. @returns {int[]} padded data
  5273. """
  5274. if len(data) > length - 11:
  5275. raise ValueError('Input data too long for PKCS#1 padding')
  5276. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  5277. return [0, 2] + pseudo_random + [0] + data
  5278. def encode_base_n(num, n, table=None):
  5279. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  5280. if not table:
  5281. table = FULL_TABLE[:n]
  5282. if n > len(table):
  5283. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  5284. if num == 0:
  5285. return table[0]
  5286. ret = ''
  5287. while num:
  5288. ret = table[num % n] + ret
  5289. num = num // n
  5290. return ret
  5291. def decode_packed_codes(code):
  5292. mobj = re.search(PACKED_CODES_RE, code)
  5293. obfuscated_code, base, count, symbols = mobj.groups()
  5294. base = int(base)
  5295. count = int(count)
  5296. symbols = symbols.split('|')
  5297. symbol_table = {}
  5298. while count:
  5299. count -= 1
  5300. base_n_count = encode_base_n(count, base)
  5301. symbol_table[base_n_count] = symbols[count] or base_n_count
  5302. return re.sub(
  5303. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  5304. obfuscated_code)
  5305. def caesar(s, alphabet, shift):
  5306. if shift == 0:
  5307. return s
  5308. l = len(alphabet)
  5309. return ''.join(
  5310. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  5311. for c in s)
  5312. def rot47(s):
  5313. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  5314. def parse_m3u8_attributes(attrib):
  5315. info = {}
  5316. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  5317. if val.startswith('"'):
  5318. val = val[1:-1]
  5319. info[key] = val
  5320. return info
  5321. def urshift(val, n):
  5322. return val >> n if val >= 0 else (val + 0x100000000) >> n
  5323. # Based on png2str() written by @gdkchan and improved by @yokrysty
  5324. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  5325. def decode_png(png_data):
  5326. # Reference: https://www.w3.org/TR/PNG/
  5327. header = png_data[8:]
  5328. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  5329. raise IOError('Not a valid PNG file.')
  5330. int_map = {1: '>B', 2: '>H', 4: '>I'}
  5331. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  5332. chunks = []
  5333. while header:
  5334. length = unpack_integer(header[:4])
  5335. header = header[4:]
  5336. chunk_type = header[:4]
  5337. header = header[4:]
  5338. chunk_data = header[:length]
  5339. header = header[length:]
  5340. header = header[4:] # Skip CRC
  5341. chunks.append({
  5342. 'type': chunk_type,
  5343. 'length': length,
  5344. 'data': chunk_data
  5345. })
  5346. ihdr = chunks[0]['data']
  5347. width = unpack_integer(ihdr[:4])
  5348. height = unpack_integer(ihdr[4:8])
  5349. idat = b''
  5350. for chunk in chunks:
  5351. if chunk['type'] == b'IDAT':
  5352. idat += chunk['data']
  5353. if not idat:
  5354. raise IOError('Unable to read PNG data.')
  5355. decompressed_data = bytearray(zlib.decompress(idat))
  5356. stride = width * 3
  5357. pixels = []
  5358. def _get_pixel(idx):
  5359. x = idx % stride
  5360. y = idx // stride
  5361. return pixels[y][x]
  5362. for y in range(height):
  5363. basePos = y * (1 + stride)
  5364. filter_type = decompressed_data[basePos]
  5365. current_row = []
  5366. pixels.append(current_row)
  5367. for x in range(stride):
  5368. color = decompressed_data[1 + basePos + x]
  5369. basex = y * stride + x
  5370. left = 0
  5371. up = 0
  5372. if x > 2:
  5373. left = _get_pixel(basex - 3)
  5374. if y > 0:
  5375. up = _get_pixel(basex - stride)
  5376. if filter_type == 1: # Sub
  5377. color = (color + left) & 0xff
  5378. elif filter_type == 2: # Up
  5379. color = (color + up) & 0xff
  5380. elif filter_type == 3: # Average
  5381. color = (color + ((left + up) >> 1)) & 0xff
  5382. elif filter_type == 4: # Paeth
  5383. a = left
  5384. b = up
  5385. c = 0
  5386. if x > 2 and y > 0:
  5387. c = _get_pixel(basex - stride - 3)
  5388. p = a + b - c
  5389. pa = abs(p - a)
  5390. pb = abs(p - b)
  5391. pc = abs(p - c)
  5392. if pa <= pb and pa <= pc:
  5393. color = (color + a) & 0xff
  5394. elif pb <= pc:
  5395. color = (color + b) & 0xff
  5396. else:
  5397. color = (color + c) & 0xff
  5398. current_row.append(color)
  5399. return width, height, pixels
  5400. def write_xattr(path, key, value):
  5401. # This mess below finds the best xattr tool for the job
  5402. try:
  5403. # try the pyxattr module...
  5404. import xattr
  5405. if hasattr(xattr, 'set'): # pyxattr
  5406. # Unicode arguments are not supported in python-pyxattr until
  5407. # version 0.5.0
  5408. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  5409. pyxattr_required_version = '0.5.0'
  5410. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  5411. # TODO: fallback to CLI tools
  5412. raise XAttrUnavailableError(
  5413. 'python-pyxattr is detected but is too old. '
  5414. 'youtube-dl requires %s or above while your version is %s. '
  5415. 'Falling back to other xattr implementations' % (
  5416. pyxattr_required_version, xattr.__version__))
  5417. setxattr = xattr.set
  5418. else: # xattr
  5419. setxattr = xattr.setxattr
  5420. try:
  5421. setxattr(path, key, value)
  5422. except EnvironmentError as e:
  5423. raise XAttrMetadataError(e.errno, e.strerror)
  5424. except ImportError:
  5425. if compat_os_name == 'nt':
  5426. # Write xattrs to NTFS Alternate Data Streams:
  5427. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  5428. assert ':' not in key
  5429. assert os.path.exists(path)
  5430. ads_fn = path + ':' + key
  5431. try:
  5432. with open(ads_fn, 'wb') as f:
  5433. f.write(value)
  5434. except EnvironmentError as e:
  5435. raise XAttrMetadataError(e.errno, e.strerror)
  5436. else:
  5437. user_has_setfattr = check_executable('setfattr', ['--version'])
  5438. user_has_xattr = check_executable('xattr', ['-h'])
  5439. if user_has_setfattr or user_has_xattr:
  5440. value = value.decode('utf-8')
  5441. if user_has_setfattr:
  5442. executable = 'setfattr'
  5443. opts = ['-n', key, '-v', value]
  5444. elif user_has_xattr:
  5445. executable = 'xattr'
  5446. opts = ['-w', key, value]
  5447. cmd = ([encodeFilename(executable, True)]
  5448. + [encodeArgument(o) for o in opts]
  5449. + [encodeFilename(path, True)])
  5450. try:
  5451. p = subprocess.Popen(
  5452. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5453. except EnvironmentError as e:
  5454. raise XAttrMetadataError(e.errno, e.strerror)
  5455. stdout, stderr = process_communicate_or_kill(p)
  5456. stderr = stderr.decode('utf-8', 'replace')
  5457. if p.returncode != 0:
  5458. raise XAttrMetadataError(p.returncode, stderr)
  5459. else:
  5460. # On Unix, and can't find pyxattr, setfattr, or xattr.
  5461. if sys.platform.startswith('linux'):
  5462. raise XAttrUnavailableError(
  5463. "Couldn't find a tool to set the xattrs. "
  5464. "Install either the python 'pyxattr' or 'xattr' "
  5465. "modules, or the GNU 'attr' package "
  5466. "(which contains the 'setfattr' tool).")
  5467. else:
  5468. raise XAttrUnavailableError(
  5469. "Couldn't find a tool to set the xattrs. "
  5470. "Install either the python 'xattr' module, "
  5471. "or the 'xattr' binary.")
  5472. def random_birthday(year_field, month_field, day_field):
  5473. start_date = datetime.date(1950, 1, 1)
  5474. end_date = datetime.date(1995, 12, 31)
  5475. offset = random.randint(0, (end_date - start_date).days)
  5476. random_date = start_date + datetime.timedelta(offset)
  5477. return {
  5478. year_field: str(random_date.year),
  5479. month_field: str(random_date.month),
  5480. day_field: str(random_date.day),
  5481. }
  5482. def clean_podcast_url(url):
  5483. return re.sub(r'''(?x)
  5484. (?:
  5485. (?:
  5486. chtbl\.com/track|
  5487. media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
  5488. play\.podtrac\.com
  5489. )/[^/]+|
  5490. (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
  5491. flex\.acast\.com|
  5492. pd(?:
  5493. cn\.co| # https://podcorn.com/analytics-prefix/
  5494. st\.fm # https://podsights.com/docs/
  5495. )/e
  5496. )/''', '', url)
  5497. if __debug__:
  5498. # Raise TypeError if args can't be bound
  5499. # needs compat owing to unstable inspect API, thanks PSF :-(
  5500. try:
  5501. inspect.signature
  5502. def _try_bind_args(fn, *args, **kwargs):
  5503. inspect.signature(fn).bind(*args, **kwargs)
  5504. except AttributeError:
  5505. # Py < 3.3
  5506. def _try_bind_args(fn, *args, **kwargs):
  5507. fn_args = inspect.getargspec(fn)
  5508. # Py2: ArgInfo(args, varargs, keywords, defaults)
  5509. # Py3: ArgSpec(args, varargs, keywords, defaults)
  5510. if not fn_args.keywords:
  5511. for k in kwargs:
  5512. if k not in (fn_args.args or []):
  5513. raise TypeError("got an unexpected keyword argument: '{0}'".format(k))
  5514. if not fn_args.varargs:
  5515. args_to_bind = len(args)
  5516. bindable = len(fn_args.args or [])
  5517. if args_to_bind > bindable:
  5518. raise TypeError('too many positional arguments')
  5519. bindable -= len(fn_args.defaults or [])
  5520. if args_to_bind < bindable:
  5521. if kwargs:
  5522. bindable -= len(set(fn_args.args or []) & set(kwargs))
  5523. if bindable > args_to_bind:
  5524. raise TypeError("missing a required argument: '{0}'".format(fn_args.args[args_to_bind]))
  5525. def traverse_obj(obj, *paths, **kwargs):
  5526. """
  5527. Safely traverse nested `dict`s and `Iterable`s, etc
  5528. >>> obj = [{}, {"key": "value"}]
  5529. >>> traverse_obj(obj, (1, "key"))
  5530. 'value'
  5531. Each of the provided `paths` is tested and the first producing a valid result will be returned.
  5532. The next path will also be tested if the path branched but no results could be found.
  5533. Supported values for traversal are `Mapping`, `Iterable`, `re.Match`, `xml.etree.ElementTree`
  5534. (xpath) and `http.cookies.Morsel`.
  5535. Unhelpful values (`{}`, `None`) are treated as the absence of a value and discarded.
  5536. The paths will be wrapped in `variadic`, so that `'key'` is conveniently the same as `('key', )`.
  5537. The keys in the path can be one of:
  5538. - `None`: Return the current object.
  5539. - `set`: Requires the only item in the set to be a type or function,
  5540. like `{type}`/`{type, type, ...}`/`{func}`. If one or more `type`s,
  5541. return only values that have one of the types. If a function,
  5542. return `func(obj)`.
  5543. - `str`/`int`: Return `obj[key]`. For `re.Match`, return `obj.group(key)`.
  5544. - `slice`: Branch out and return all values in `obj[key]`.
  5545. - `Ellipsis`: Branch out and return a list of all values.
  5546. - `tuple`/`list`: Branch out and return a list of all matching values.
  5547. Read as: `[traverse_obj(obj, branch) for branch in branches]`.
  5548. - `function`: Branch out and return values filtered by the function.
  5549. Read as: `[value for key, value in obj if function(key, value)]`.
  5550. For `Sequence`s, `key` is the index of the value.
  5551. For `Iterable`s, `key` is the enumeration count of the value.
  5552. For `re.Match`es, `key` is the group number (0 = full match)
  5553. as well as additionally any group names, if given.
  5554. - `dict`: Transform the current object and return a matching dict.
  5555. Read as: `{key: traverse_obj(obj, path) for key, path in dct.items()}`.
  5556. - `any`-builtin: Take the first matching object and return it, resetting branching.
  5557. - `all`-builtin: Take all matching objects and return them as a list, resetting branching.
  5558. `tuple`, `list`, and `dict` all support nested paths and branches.
  5559. @params paths Paths which to traverse by.
  5560. Keyword arguments:
  5561. @param default Value to return if the paths do not match.
  5562. If the last key in the path is a `dict`, it will apply to each value inside
  5563. the dict instead, depth first. Try to avoid if using nested `dict` keys.
  5564. @param expected_type If a `type`, only accept final values of this type.
  5565. If any other callable, try to call the function on each result.
  5566. If the last key in the path is a `dict`, it will apply to each value inside
  5567. the dict instead, recursively. This does respect branching paths.
  5568. @param get_all If `False`, return the first matching result, otherwise all matching ones.
  5569. @param casesense If `False`, consider string dictionary keys as case insensitive.
  5570. The following is only meant to be used by YoutubeDL.prepare_outtmpl and is not part of the API
  5571. @param _traverse_string Whether to traverse into objects as strings.
  5572. If `True`, any non-compatible object will first be
  5573. converted into a string and then traversed into.
  5574. The return value of that path will be a string instead,
  5575. not respecting any further branching.
  5576. @returns The result of the object traversal.
  5577. If successful, `get_all=True`, and the path branches at least once,
  5578. then a list of results is returned instead.
  5579. A list is always returned if the last path branches and no `default` is given.
  5580. If a path ends on a `dict` that result will always be a `dict`.
  5581. """
  5582. # parameter defaults
  5583. default = kwargs.get('default', NO_DEFAULT)
  5584. expected_type = kwargs.get('expected_type')
  5585. get_all = kwargs.get('get_all', True)
  5586. casesense = kwargs.get('casesense', True)
  5587. _traverse_string = kwargs.get('_traverse_string', False)
  5588. # instant compat
  5589. str = compat_str
  5590. casefold = lambda k: compat_casefold(k) if isinstance(k, str) else k
  5591. if isinstance(expected_type, type):
  5592. type_test = lambda val: val if isinstance(val, expected_type) else None
  5593. else:
  5594. type_test = lambda val: try_call(expected_type or IDENTITY, args=(val,))
  5595. def lookup_or_none(v, k, getter=None):
  5596. with compat_contextlib_suppress(LookupError):
  5597. return getter(v, k) if getter else v[k]
  5598. def from_iterable(iterables):
  5599. # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
  5600. for it in iterables:
  5601. for item in it:
  5602. yield item
  5603. def apply_key(key, obj, is_last):
  5604. branching = False
  5605. if obj is None and _traverse_string:
  5606. if key is Ellipsis or callable(key) or isinstance(key, slice):
  5607. branching = True
  5608. result = ()
  5609. else:
  5610. result = None
  5611. elif key is None:
  5612. result = obj
  5613. elif isinstance(key, set):
  5614. assert len(key) >= 1, 'At least one item is required in a `set` key'
  5615. if all(isinstance(item, type) for item in key):
  5616. result = obj if isinstance(obj, tuple(key)) else None
  5617. else:
  5618. item = next(iter(key))
  5619. assert len(key) == 1, 'Multiple items in a `set` key must all be types'
  5620. result = try_call(item, args=(obj,)) if not isinstance(item, type) else None
  5621. elif isinstance(key, (list, tuple)):
  5622. branching = True
  5623. result = from_iterable(
  5624. apply_path(obj, branch, is_last)[0] for branch in key)
  5625. elif key is Ellipsis:
  5626. branching = True
  5627. if isinstance(obj, compat_http_cookies.Morsel):
  5628. obj = dict(obj, key=obj.key, value=obj.value)
  5629. if isinstance(obj, compat_collections_abc.Mapping):
  5630. result = obj.values()
  5631. elif is_iterable_like(obj, (compat_collections_abc.Iterable, compat_etree_Element)):
  5632. result = obj
  5633. elif isinstance(obj, compat_re_Match):
  5634. result = obj.groups()
  5635. elif _traverse_string:
  5636. branching = False
  5637. result = str(obj)
  5638. else:
  5639. result = ()
  5640. elif callable(key):
  5641. branching = True
  5642. if isinstance(obj, compat_http_cookies.Morsel):
  5643. obj = dict(obj, key=obj.key, value=obj.value)
  5644. if isinstance(obj, compat_collections_abc.Mapping):
  5645. iter_obj = obj.items()
  5646. elif is_iterable_like(obj, (compat_collections_abc.Iterable, compat_etree_Element)):
  5647. iter_obj = enumerate(obj)
  5648. elif isinstance(obj, compat_re_Match):
  5649. iter_obj = itertools.chain(
  5650. enumerate(itertools.chain((obj.group(),), obj.groups())),
  5651. obj.groupdict().items())
  5652. elif _traverse_string:
  5653. branching = False
  5654. iter_obj = enumerate(str(obj))
  5655. else:
  5656. iter_obj = ()
  5657. result = (v for k, v in iter_obj if try_call(key, args=(k, v)))
  5658. if not branching: # string traversal
  5659. result = ''.join(result)
  5660. elif isinstance(key, dict):
  5661. iter_obj = ((k, _traverse_obj(obj, v, False, is_last)) for k, v in key.items())
  5662. result = dict((k, v if v is not None else default) for k, v in iter_obj
  5663. if v is not None or default is not NO_DEFAULT) or None
  5664. elif isinstance(obj, compat_collections_abc.Mapping):
  5665. if isinstance(obj, compat_http_cookies.Morsel):
  5666. obj = dict(obj, key=obj.key, value=obj.value)
  5667. result = (try_call(obj.get, args=(key,))
  5668. if casesense or try_call(obj.__contains__, args=(key,))
  5669. else next((v for k, v in obj.items() if casefold(k) == key), None))
  5670. elif isinstance(obj, compat_re_Match):
  5671. result = None
  5672. if isinstance(key, int) or casesense:
  5673. # Py 2.6 doesn't have methods in the Match class/type
  5674. result = lookup_or_none(obj, key, getter=lambda _, k: obj.group(k))
  5675. elif isinstance(key, str):
  5676. result = next((v for k, v in obj.groupdict().items()
  5677. if casefold(k) == key), None)
  5678. else:
  5679. result = None
  5680. if isinstance(key, (int, slice)):
  5681. if is_iterable_like(obj, (compat_collections_abc.Sequence, compat_etree_Element)):
  5682. branching = isinstance(key, slice)
  5683. result = lookup_or_none(obj, key)
  5684. elif _traverse_string:
  5685. result = lookup_or_none(str(obj), key)
  5686. elif isinstance(obj, compat_etree_Element) and isinstance(key, str):
  5687. xpath, _, special = key.rpartition('/')
  5688. if not special.startswith('@') and not special.endswith('()'):
  5689. xpath = key
  5690. special = None
  5691. # Allow abbreviations of relative paths, absolute paths error
  5692. if xpath.startswith('/'):
  5693. xpath = '.' + xpath
  5694. elif xpath and not xpath.startswith('./'):
  5695. xpath = './' + xpath
  5696. def apply_specials(element):
  5697. if special is None:
  5698. return element
  5699. if special == '@':
  5700. return element.attrib
  5701. if special.startswith('@'):
  5702. return try_call(element.attrib.get, args=(special[1:],))
  5703. if special == 'text()':
  5704. return element.text
  5705. raise SyntaxError('apply_specials is missing case for {0!r}'.format(special))
  5706. if xpath:
  5707. result = list(map(apply_specials, compat_etree_iterfind(obj, xpath)))
  5708. else:
  5709. result = apply_specials(obj)
  5710. return branching, result if branching else (result,)
  5711. def lazy_last(iterable):
  5712. iterator = iter(iterable)
  5713. prev = next(iterator, NO_DEFAULT)
  5714. if prev is NO_DEFAULT:
  5715. return
  5716. for item in iterator:
  5717. yield False, prev
  5718. prev = item
  5719. yield True, prev
  5720. def apply_path(start_obj, path, test_type):
  5721. objs = (start_obj,)
  5722. has_branched = False
  5723. key = None
  5724. for last, key in lazy_last(variadic(path, (str, bytes, dict, set))):
  5725. if not casesense and isinstance(key, str):
  5726. key = compat_casefold(key)
  5727. if key in (any, all):
  5728. has_branched = False
  5729. filtered_objs = (obj for obj in objs if obj not in (None, {}))
  5730. if key is any:
  5731. objs = (next(filtered_objs, None),)
  5732. else:
  5733. objs = (list(filtered_objs),)
  5734. continue
  5735. if __debug__ and callable(key):
  5736. # Verify function signature
  5737. _try_bind_args(key, None, None)
  5738. new_objs = []
  5739. for obj in objs:
  5740. branching, results = apply_key(key, obj, last)
  5741. has_branched |= branching
  5742. new_objs.append(results)
  5743. objs = from_iterable(new_objs)
  5744. if test_type and not isinstance(key, (dict, list, tuple)):
  5745. objs = map(type_test, objs)
  5746. return objs, has_branched, isinstance(key, dict)
  5747. def _traverse_obj(obj, path, allow_empty, test_type):
  5748. results, has_branched, is_dict = apply_path(obj, path, test_type)
  5749. results = LazyList(x for x in results if x not in (None, {}))
  5750. if get_all and has_branched:
  5751. if results:
  5752. return results.exhaust()
  5753. if allow_empty:
  5754. return [] if default is NO_DEFAULT else default
  5755. return None
  5756. return results[0] if results else {} if allow_empty and is_dict else None
  5757. for index, path in enumerate(paths, 1):
  5758. result = _traverse_obj(obj, path, index == len(paths), True)
  5759. if result is not None:
  5760. return result
  5761. return None if default is NO_DEFAULT else default
  5762. def T(*x):
  5763. """ For use in yt-dl instead of {type, ...} or set((type, ...)) """
  5764. return set(x)
  5765. def get_first(obj, keys, **kwargs):
  5766. return traverse_obj(obj, (Ellipsis,) + tuple(variadic(keys)), get_all=False, **kwargs)
  5767. def join_nonempty(*values, **kwargs):
  5768. # parameter defaults
  5769. delim = kwargs.get('delim', '-')
  5770. from_dict = kwargs.get('from_dict')
  5771. if from_dict is not None:
  5772. values = (traverse_obj(from_dict, variadic(v)) for v in values)
  5773. return delim.join(map(compat_str, filter(None, values)))