utils.py 197 KB

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