utils.py 168 KB

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