utils.py 205 KB

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