utils.py 195 KB

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