utils.py 183 KB

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