utils.py 183 KB

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