utils.py 203 KB

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