utils.py 182 KB

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