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