utils.py 167 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775
  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 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. opts_no_check_certificate = params.get('nocheckcertificate', False)
  2170. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  2171. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  2172. if opts_no_check_certificate:
  2173. context.check_hostname = False
  2174. context.verify_mode = ssl.CERT_NONE
  2175. try:
  2176. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2177. except TypeError:
  2178. # Python 2.7.8
  2179. # (create_default_context present but HTTPSHandler has no context=)
  2180. pass
  2181. if sys.version_info < (3, 2):
  2182. return YoutubeDLHTTPSHandler(params, **kwargs)
  2183. else: # Python < 3.4
  2184. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  2185. context.verify_mode = (ssl.CERT_NONE
  2186. if opts_no_check_certificate
  2187. else ssl.CERT_REQUIRED)
  2188. context.set_default_verify_paths()
  2189. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  2190. def bug_reports_message():
  2191. if ytdl_is_updateable():
  2192. update_cmd = 'type youtube-dl -U to update'
  2193. else:
  2194. update_cmd = 'see https://yt-dl.org/update on how to update'
  2195. msg = '; please report this issue on https://yt-dl.org/bug .'
  2196. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  2197. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  2198. return msg
  2199. class YoutubeDLError(Exception):
  2200. """Base exception for YoutubeDL errors."""
  2201. pass
  2202. class ExtractorError(YoutubeDLError):
  2203. """Error during info extraction."""
  2204. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  2205. """ tb, if given, is the original traceback (so that it can be printed out).
  2206. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  2207. """
  2208. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  2209. expected = True
  2210. if video_id is not None:
  2211. msg = video_id + ': ' + msg
  2212. if cause:
  2213. msg += ' (caused by %r)' % cause
  2214. if not expected:
  2215. msg += bug_reports_message()
  2216. super(ExtractorError, self).__init__(msg)
  2217. self.traceback = tb
  2218. self.exc_info = sys.exc_info() # preserve original exception
  2219. self.cause = cause
  2220. self.video_id = video_id
  2221. def format_traceback(self):
  2222. if self.traceback is None:
  2223. return None
  2224. return ''.join(traceback.format_tb(self.traceback))
  2225. class UnsupportedError(ExtractorError):
  2226. def __init__(self, url):
  2227. super(UnsupportedError, self).__init__(
  2228. 'Unsupported URL: %s' % url, expected=True)
  2229. self.url = url
  2230. class RegexNotFoundError(ExtractorError):
  2231. """Error when a regex didn't match"""
  2232. pass
  2233. class GeoRestrictedError(ExtractorError):
  2234. """Geographic restriction Error exception.
  2235. This exception may be thrown when a video is not available from your
  2236. geographic location due to geographic restrictions imposed by a website.
  2237. """
  2238. def __init__(self, msg, countries=None):
  2239. super(GeoRestrictedError, self).__init__(msg, expected=True)
  2240. self.msg = msg
  2241. self.countries = countries
  2242. class DownloadError(YoutubeDLError):
  2243. """Download Error exception.
  2244. This exception may be thrown by FileDownloader objects if they are not
  2245. configured to continue on errors. They will contain the appropriate
  2246. error message.
  2247. """
  2248. def __init__(self, msg, exc_info=None):
  2249. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  2250. super(DownloadError, self).__init__(msg)
  2251. self.exc_info = exc_info
  2252. class SameFileError(YoutubeDLError):
  2253. """Same File exception.
  2254. This exception will be thrown by FileDownloader objects if they detect
  2255. multiple files would have to be downloaded to the same file on disk.
  2256. """
  2257. pass
  2258. class PostProcessingError(YoutubeDLError):
  2259. """Post Processing exception.
  2260. This exception may be raised by PostProcessor's .run() method to
  2261. indicate an error in the postprocessing task.
  2262. """
  2263. def __init__(self, msg):
  2264. super(PostProcessingError, self).__init__(msg)
  2265. self.msg = msg
  2266. class MaxDownloadsReached(YoutubeDLError):
  2267. """ --max-downloads limit has been reached. """
  2268. pass
  2269. class UnavailableVideoError(YoutubeDLError):
  2270. """Unavailable Format exception.
  2271. This exception will be thrown when a video is requested
  2272. in a format that is not available for that video.
  2273. """
  2274. pass
  2275. class ContentTooShortError(YoutubeDLError):
  2276. """Content Too Short exception.
  2277. This exception may be raised by FileDownloader objects when a file they
  2278. download is too small for what the server announced first, indicating
  2279. the connection was probably interrupted.
  2280. """
  2281. def __init__(self, downloaded, expected):
  2282. super(ContentTooShortError, self).__init__(
  2283. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  2284. )
  2285. # Both in bytes
  2286. self.downloaded = downloaded
  2287. self.expected = expected
  2288. class XAttrMetadataError(YoutubeDLError):
  2289. def __init__(self, code=None, msg='Unknown error'):
  2290. super(XAttrMetadataError, self).__init__(msg)
  2291. self.code = code
  2292. self.msg = msg
  2293. # Parsing code and msg
  2294. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  2295. or 'No space left' in self.msg or 'Disk quota exceeded' in self.msg):
  2296. self.reason = 'NO_SPACE'
  2297. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  2298. self.reason = 'VALUE_TOO_LONG'
  2299. else:
  2300. self.reason = 'NOT_SUPPORTED'
  2301. class XAttrUnavailableError(YoutubeDLError):
  2302. pass
  2303. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  2304. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  2305. # expected HTTP responses to meet HTTP/1.0 or later (see also
  2306. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  2307. if sys.version_info < (3, 0):
  2308. kwargs['strict'] = True
  2309. hc = http_class(*args, **compat_kwargs(kwargs))
  2310. source_address = ydl_handler._params.get('source_address')
  2311. if source_address is not None:
  2312. # This is to workaround _create_connection() from socket where it will try all
  2313. # address data from getaddrinfo() including IPv6. This filters the result from
  2314. # getaddrinfo() based on the source_address value.
  2315. # This is based on the cpython socket.create_connection() function.
  2316. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  2317. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  2318. host, port = address
  2319. err = None
  2320. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  2321. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  2322. ip_addrs = [addr for addr in addrs if addr[0] == af]
  2323. if addrs and not ip_addrs:
  2324. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  2325. raise socket.error(
  2326. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  2327. % (ip_version, source_address[0]))
  2328. for res in ip_addrs:
  2329. af, socktype, proto, canonname, sa = res
  2330. sock = None
  2331. try:
  2332. sock = socket.socket(af, socktype, proto)
  2333. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  2334. sock.settimeout(timeout)
  2335. sock.bind(source_address)
  2336. sock.connect(sa)
  2337. err = None # Explicitly break reference cycle
  2338. return sock
  2339. except socket.error as _:
  2340. err = _
  2341. if sock is not None:
  2342. sock.close()
  2343. if err is not None:
  2344. raise err
  2345. else:
  2346. raise socket.error('getaddrinfo returns an empty list')
  2347. if hasattr(hc, '_create_connection'):
  2348. hc._create_connection = _create_connection
  2349. sa = (source_address, 0)
  2350. if hasattr(hc, 'source_address'): # Python 2.7+
  2351. hc.source_address = sa
  2352. else: # Python 2.6
  2353. def _hc_connect(self, *args, **kwargs):
  2354. sock = _create_connection(
  2355. (self.host, self.port), self.timeout, sa)
  2356. if is_https:
  2357. self.sock = ssl.wrap_socket(
  2358. sock, self.key_file, self.cert_file,
  2359. ssl_version=ssl.PROTOCOL_TLSv1)
  2360. else:
  2361. self.sock = sock
  2362. hc.connect = functools.partial(_hc_connect, hc)
  2363. return hc
  2364. def handle_youtubedl_headers(headers):
  2365. filtered_headers = headers
  2366. if 'Youtubedl-no-compression' in filtered_headers:
  2367. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  2368. del filtered_headers['Youtubedl-no-compression']
  2369. return filtered_headers
  2370. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  2371. """Handler for HTTP requests and responses.
  2372. This class, when installed with an OpenerDirector, automatically adds
  2373. the standard headers to every HTTP request and handles gzipped and
  2374. deflated responses from web servers. If compression is to be avoided in
  2375. a particular request, the original request in the program code only has
  2376. to include the HTTP header "Youtubedl-no-compression", which will be
  2377. removed before making the real request.
  2378. Part of this code was copied from:
  2379. http://techknack.net/python-urllib2-handlers/
  2380. Andrew Rowls, the author of that code, agreed to release it to the
  2381. public domain.
  2382. """
  2383. def __init__(self, params, *args, **kwargs):
  2384. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  2385. self._params = params
  2386. def http_open(self, req):
  2387. conn_class = compat_http_client.HTTPConnection
  2388. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2389. if socks_proxy:
  2390. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2391. del req.headers['Ytdl-socks-proxy']
  2392. return self.do_open(functools.partial(
  2393. _create_http_connection, self, conn_class, False),
  2394. req)
  2395. @staticmethod
  2396. def deflate(data):
  2397. try:
  2398. return zlib.decompress(data, -zlib.MAX_WBITS)
  2399. except zlib.error:
  2400. return zlib.decompress(data)
  2401. def http_request(self, req):
  2402. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  2403. # always respected by websites, some tend to give out URLs with non percent-encoded
  2404. # non-ASCII characters (see telemb.py, ard.py [#3412])
  2405. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  2406. # To work around aforementioned issue we will replace request's original URL with
  2407. # percent-encoded one
  2408. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  2409. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  2410. url = req.get_full_url()
  2411. url_escaped = escape_url(url)
  2412. # Substitute URL if any change after escaping
  2413. if url != url_escaped:
  2414. req = update_Request(req, url=url_escaped)
  2415. for h, v in std_headers.items():
  2416. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  2417. # The dict keys are capitalized because of this bug by urllib
  2418. if h.capitalize() not in req.headers:
  2419. req.add_header(h, v)
  2420. req.headers = handle_youtubedl_headers(req.headers)
  2421. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  2422. # Python 2.6 is brain-dead when it comes to fragments
  2423. req._Request__original = req._Request__original.partition('#')[0]
  2424. req._Request__r_type = req._Request__r_type.partition('#')[0]
  2425. return req
  2426. def http_response(self, req, resp):
  2427. old_resp = resp
  2428. # gzip
  2429. if resp.headers.get('Content-encoding', '') == 'gzip':
  2430. content = resp.read()
  2431. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  2432. try:
  2433. uncompressed = io.BytesIO(gz.read())
  2434. except IOError as original_ioerror:
  2435. # There may be junk add the end of the file
  2436. # See http://stackoverflow.com/q/4928560/35070 for details
  2437. for i in range(1, 1024):
  2438. try:
  2439. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  2440. uncompressed = io.BytesIO(gz.read())
  2441. except IOError:
  2442. continue
  2443. break
  2444. else:
  2445. raise original_ioerror
  2446. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  2447. resp.msg = old_resp.msg
  2448. del resp.headers['Content-encoding']
  2449. # deflate
  2450. if resp.headers.get('Content-encoding', '') == 'deflate':
  2451. gz = io.BytesIO(self.deflate(resp.read()))
  2452. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  2453. resp.msg = old_resp.msg
  2454. del resp.headers['Content-encoding']
  2455. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  2456. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  2457. if 300 <= resp.code < 400:
  2458. location = resp.headers.get('Location')
  2459. if location:
  2460. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  2461. if sys.version_info >= (3, 0):
  2462. location = location.encode('iso-8859-1').decode('utf-8')
  2463. else:
  2464. location = location.decode('utf-8')
  2465. location_escaped = escape_url(location)
  2466. if location != location_escaped:
  2467. del resp.headers['Location']
  2468. if sys.version_info < (3, 0):
  2469. location_escaped = location_escaped.encode('utf-8')
  2470. resp.headers['Location'] = location_escaped
  2471. return resp
  2472. https_request = http_request
  2473. https_response = http_response
  2474. def make_socks_conn_class(base_class, socks_proxy):
  2475. assert issubclass(base_class, (
  2476. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  2477. url_components = compat_urlparse.urlparse(socks_proxy)
  2478. if url_components.scheme.lower() == 'socks5':
  2479. socks_type = ProxyType.SOCKS5
  2480. elif url_components.scheme.lower() in ('socks', 'socks4'):
  2481. socks_type = ProxyType.SOCKS4
  2482. elif url_components.scheme.lower() == 'socks4a':
  2483. socks_type = ProxyType.SOCKS4A
  2484. def unquote_if_non_empty(s):
  2485. if not s:
  2486. return s
  2487. return compat_urllib_parse_unquote_plus(s)
  2488. proxy_args = (
  2489. socks_type,
  2490. url_components.hostname, url_components.port or 1080,
  2491. True, # Remote DNS
  2492. unquote_if_non_empty(url_components.username),
  2493. unquote_if_non_empty(url_components.password),
  2494. )
  2495. class SocksConnection(base_class):
  2496. def connect(self):
  2497. self.sock = sockssocket()
  2498. self.sock.setproxy(*proxy_args)
  2499. if type(self.timeout) in (int, float):
  2500. self.sock.settimeout(self.timeout)
  2501. self.sock.connect((self.host, self.port))
  2502. if isinstance(self, compat_http_client.HTTPSConnection):
  2503. if hasattr(self, '_context'): # Python > 2.6
  2504. self.sock = self._context.wrap_socket(
  2505. self.sock, server_hostname=self.host)
  2506. else:
  2507. self.sock = ssl.wrap_socket(self.sock)
  2508. return SocksConnection
  2509. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  2510. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  2511. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  2512. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  2513. self._params = params
  2514. def https_open(self, req):
  2515. kwargs = {}
  2516. conn_class = self._https_conn_class
  2517. if hasattr(self, '_context'): # python > 2.6
  2518. kwargs['context'] = self._context
  2519. if hasattr(self, '_check_hostname'): # python 3.x
  2520. kwargs['check_hostname'] = self._check_hostname
  2521. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  2522. if socks_proxy:
  2523. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  2524. del req.headers['Ytdl-socks-proxy']
  2525. return self.do_open(functools.partial(
  2526. _create_http_connection, self, conn_class, True),
  2527. req, **kwargs)
  2528. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  2529. """
  2530. See [1] for cookie file format.
  2531. 1. https://curl.haxx.se/docs/http-cookies.html
  2532. """
  2533. _HTTPONLY_PREFIX = '#HttpOnly_'
  2534. _ENTRY_LEN = 7
  2535. _HEADER = '''# Netscape HTTP Cookie File
  2536. # This file is generated by youtube-dl. Do not edit.
  2537. '''
  2538. _CookieFileEntry = collections.namedtuple(
  2539. 'CookieFileEntry',
  2540. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  2541. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  2542. """
  2543. Save cookies to a file.
  2544. Most of the code is taken from CPython 3.8 and slightly adapted
  2545. to support cookie files with UTF-8 in both python 2 and 3.
  2546. """
  2547. if filename is None:
  2548. if self.filename is not None:
  2549. filename = self.filename
  2550. else:
  2551. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2552. # Store session cookies with `expires` set to 0 instead of an empty
  2553. # string
  2554. for cookie in self:
  2555. if cookie.expires is None:
  2556. cookie.expires = 0
  2557. with io.open(filename, 'w', encoding='utf-8') as f:
  2558. f.write(self._HEADER)
  2559. now = time.time()
  2560. for cookie in self:
  2561. if not ignore_discard and cookie.discard:
  2562. continue
  2563. if not ignore_expires and cookie.is_expired(now):
  2564. continue
  2565. if cookie.secure:
  2566. secure = 'TRUE'
  2567. else:
  2568. secure = 'FALSE'
  2569. if cookie.domain.startswith('.'):
  2570. initial_dot = 'TRUE'
  2571. else:
  2572. initial_dot = 'FALSE'
  2573. if cookie.expires is not None:
  2574. expires = compat_str(cookie.expires)
  2575. else:
  2576. expires = ''
  2577. if cookie.value is None:
  2578. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  2579. # with no name, whereas http.cookiejar regards it as a
  2580. # cookie with no value.
  2581. name = ''
  2582. value = cookie.name
  2583. else:
  2584. name = cookie.name
  2585. value = cookie.value
  2586. f.write(
  2587. '\t'.join([cookie.domain, initial_dot, cookie.path,
  2588. secure, expires, name, value]) + '\n')
  2589. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  2590. """Load cookies from a file."""
  2591. if filename is None:
  2592. if self.filename is not None:
  2593. filename = self.filename
  2594. else:
  2595. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  2596. def prepare_line(line):
  2597. if line.startswith(self._HTTPONLY_PREFIX):
  2598. line = line[len(self._HTTPONLY_PREFIX):]
  2599. # comments and empty lines are fine
  2600. if line.startswith('#') or not line.strip():
  2601. return line
  2602. cookie_list = line.split('\t')
  2603. if len(cookie_list) != self._ENTRY_LEN:
  2604. raise compat_cookiejar.LoadError('invalid length %d' % len(cookie_list))
  2605. cookie = self._CookieFileEntry(*cookie_list)
  2606. if cookie.expires_at and not cookie.expires_at.isdigit():
  2607. raise compat_cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
  2608. return line
  2609. cf = io.StringIO()
  2610. with io.open(filename, encoding='utf-8') as f:
  2611. for line in f:
  2612. try:
  2613. cf.write(prepare_line(line))
  2614. except compat_cookiejar.LoadError as e:
  2615. write_string(
  2616. 'WARNING: skipping cookie file entry due to %s: %r\n'
  2617. % (e, line), sys.stderr)
  2618. continue
  2619. cf.seek(0)
  2620. self._really_load(cf, filename, ignore_discard, ignore_expires)
  2621. # Session cookies are denoted by either `expires` field set to
  2622. # an empty string or 0. MozillaCookieJar only recognizes the former
  2623. # (see [1]). So we need force the latter to be recognized as session
  2624. # cookies on our own.
  2625. # Session cookies may be important for cookies-based authentication,
  2626. # e.g. usually, when user does not check 'Remember me' check box while
  2627. # logging in on a site, some important cookies are stored as session
  2628. # cookies so that not recognizing them will result in failed login.
  2629. # 1. https://bugs.python.org/issue17164
  2630. for cookie in self:
  2631. # Treat `expires=0` cookies as session cookies
  2632. if cookie.expires == 0:
  2633. cookie.expires = None
  2634. cookie.discard = True
  2635. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  2636. def __init__(self, cookiejar=None):
  2637. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  2638. def http_response(self, request, response):
  2639. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  2640. # characters in Set-Cookie HTTP header of last response (see
  2641. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  2642. # In order to at least prevent crashing we will percent encode Set-Cookie
  2643. # header before HTTPCookieProcessor starts processing it.
  2644. # if sys.version_info < (3, 0) and response.headers:
  2645. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  2646. # set_cookie = response.headers.get(set_cookie_header)
  2647. # if set_cookie:
  2648. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  2649. # if set_cookie != set_cookie_escaped:
  2650. # del response.headers[set_cookie_header]
  2651. # response.headers[set_cookie_header] = set_cookie_escaped
  2652. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  2653. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  2654. https_response = http_response
  2655. class YoutubeDLRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  2656. """YoutubeDL redirect handler
  2657. The code is based on HTTPRedirectHandler implementation from CPython [1].
  2658. This redirect handler solves two issues:
  2659. - ensures redirect URL is always unicode under python 2
  2660. - introduces support for experimental HTTP response status code
  2661. 308 Permanent Redirect [2] used by some sites [3]
  2662. 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
  2663. 2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
  2664. 3. https://github.com/ytdl-org/youtube-dl/issues/28768
  2665. """
  2666. http_error_301 = http_error_303 = http_error_307 = http_error_308 = compat_urllib_request.HTTPRedirectHandler.http_error_302
  2667. def redirect_request(self, req, fp, code, msg, headers, newurl):
  2668. """Return a Request or None in response to a redirect.
  2669. This is called by the http_error_30x methods when a
  2670. redirection response is received. If a redirection should
  2671. take place, return a new Request to allow http_error_30x to
  2672. perform the redirect. Otherwise, raise HTTPError if no-one
  2673. else should try to handle this url. Return None if you can't
  2674. but another Handler might.
  2675. """
  2676. m = req.get_method()
  2677. if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD")
  2678. or code in (301, 302, 303) and m == "POST")):
  2679. raise compat_HTTPError(req.full_url, code, msg, headers, fp)
  2680. # Strictly (according to RFC 2616), 301 or 302 in response to
  2681. # a POST MUST NOT cause a redirection without confirmation
  2682. # from the user (of urllib.request, in this case). In practice,
  2683. # essentially all clients do redirect in this case, so we do
  2684. # the same.
  2685. # On python 2 urlh.geturl() may sometimes return redirect URL
  2686. # as byte string instead of unicode. This workaround allows
  2687. # to force it always return unicode.
  2688. if sys.version_info[0] < 3:
  2689. newurl = compat_str(newurl)
  2690. # Be conciliant with URIs containing a space. This is mainly
  2691. # redundant with the more complete encoding done in http_error_302(),
  2692. # but it is kept for compatibility with other callers.
  2693. newurl = newurl.replace(' ', '%20')
  2694. CONTENT_HEADERS = ("content-length", "content-type")
  2695. # NB: don't use dict comprehension for python 2.6 compatibility
  2696. newheaders = dict((k, v) for k, v in req.headers.items()
  2697. if k.lower() not in CONTENT_HEADERS)
  2698. return compat_urllib_request.Request(
  2699. newurl, headers=newheaders, origin_req_host=req.origin_req_host,
  2700. unverifiable=True)
  2701. def extract_timezone(date_str):
  2702. m = re.search(
  2703. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  2704. date_str)
  2705. if not m:
  2706. timezone = datetime.timedelta()
  2707. else:
  2708. date_str = date_str[:-len(m.group('tz'))]
  2709. if not m.group('sign'):
  2710. timezone = datetime.timedelta()
  2711. else:
  2712. sign = 1 if m.group('sign') == '+' else -1
  2713. timezone = datetime.timedelta(
  2714. hours=sign * int(m.group('hours')),
  2715. minutes=sign * int(m.group('minutes')))
  2716. return timezone, date_str
  2717. def parse_iso8601(date_str, delimiter='T', timezone=None):
  2718. """ Return a UNIX timestamp from the given date """
  2719. if date_str is None:
  2720. return None
  2721. date_str = re.sub(r'\.[0-9]+', '', date_str)
  2722. if timezone is None:
  2723. timezone, date_str = extract_timezone(date_str)
  2724. try:
  2725. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  2726. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  2727. return calendar.timegm(dt.timetuple())
  2728. except ValueError:
  2729. pass
  2730. def date_formats(day_first=True):
  2731. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  2732. def unified_strdate(date_str, day_first=True):
  2733. """Return a string with the date in the format YYYYMMDD"""
  2734. if date_str is None:
  2735. return None
  2736. upload_date = None
  2737. # Replace commas
  2738. date_str = date_str.replace(',', ' ')
  2739. # Remove AM/PM + timezone
  2740. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2741. _, date_str = extract_timezone(date_str)
  2742. for expression in date_formats(day_first):
  2743. try:
  2744. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  2745. except ValueError:
  2746. pass
  2747. if upload_date is None:
  2748. timetuple = email.utils.parsedate_tz(date_str)
  2749. if timetuple:
  2750. try:
  2751. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  2752. except ValueError:
  2753. pass
  2754. if upload_date is not None:
  2755. return compat_str(upload_date)
  2756. def unified_timestamp(date_str, day_first=True):
  2757. if date_str is None:
  2758. return None
  2759. date_str = re.sub(r'[,|]', '', date_str)
  2760. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  2761. timezone, date_str = extract_timezone(date_str)
  2762. # Remove AM/PM + timezone
  2763. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  2764. # Remove unrecognized timezones from ISO 8601 alike timestamps
  2765. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  2766. if m:
  2767. date_str = date_str[:-len(m.group('tz'))]
  2768. # Python only supports microseconds, so remove nanoseconds
  2769. 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)
  2770. if m:
  2771. date_str = m.group(1)
  2772. for expression in date_formats(day_first):
  2773. try:
  2774. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  2775. return calendar.timegm(dt.timetuple())
  2776. except ValueError:
  2777. pass
  2778. timetuple = email.utils.parsedate_tz(date_str)
  2779. if timetuple:
  2780. return calendar.timegm(timetuple) + pm_delta * 3600
  2781. def determine_ext(url, default_ext='unknown_video'):
  2782. if url is None or '.' not in url:
  2783. return default_ext
  2784. guess = url.partition('?')[0].rpartition('.')[2]
  2785. if re.match(r'^[A-Za-z0-9]+$', guess):
  2786. return guess
  2787. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  2788. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  2789. return guess.rstrip('/')
  2790. else:
  2791. return default_ext
  2792. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  2793. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  2794. def date_from_str(date_str):
  2795. """
  2796. Return a datetime object from a string in the format YYYYMMDD or
  2797. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  2798. today = datetime.date.today()
  2799. if date_str in ('now', 'today'):
  2800. return today
  2801. if date_str == 'yesterday':
  2802. return today - datetime.timedelta(days=1)
  2803. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  2804. if match is not None:
  2805. sign = match.group('sign')
  2806. time = int(match.group('time'))
  2807. if sign == '-':
  2808. time = -time
  2809. unit = match.group('unit')
  2810. # A bad approximation?
  2811. if unit == 'month':
  2812. unit = 'day'
  2813. time *= 30
  2814. elif unit == 'year':
  2815. unit = 'day'
  2816. time *= 365
  2817. unit += 's'
  2818. delta = datetime.timedelta(**{unit: time})
  2819. return today + delta
  2820. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  2821. def hyphenate_date(date_str):
  2822. """
  2823. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  2824. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  2825. if match is not None:
  2826. return '-'.join(match.groups())
  2827. else:
  2828. return date_str
  2829. class DateRange(object):
  2830. """Represents a time interval between two dates"""
  2831. def __init__(self, start=None, end=None):
  2832. """start and end must be strings in the format accepted by date"""
  2833. if start is not None:
  2834. self.start = date_from_str(start)
  2835. else:
  2836. self.start = datetime.datetime.min.date()
  2837. if end is not None:
  2838. self.end = date_from_str(end)
  2839. else:
  2840. self.end = datetime.datetime.max.date()
  2841. if self.start > self.end:
  2842. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  2843. @classmethod
  2844. def day(cls, day):
  2845. """Returns a range that only contains the given day"""
  2846. return cls(day, day)
  2847. def __contains__(self, date):
  2848. """Check if the date is in the range"""
  2849. if not isinstance(date, datetime.date):
  2850. date = date_from_str(date)
  2851. return self.start <= date <= self.end
  2852. def __str__(self):
  2853. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  2854. def platform_name():
  2855. """ Returns the platform name as a compat_str """
  2856. res = platform.platform()
  2857. if isinstance(res, bytes):
  2858. res = res.decode(preferredencoding())
  2859. assert isinstance(res, compat_str)
  2860. return res
  2861. def _windows_write_string(s, out):
  2862. """ Returns True if the string was written using special methods,
  2863. False if it has yet to be written out."""
  2864. # Adapted from http://stackoverflow.com/a/3259271/35070
  2865. import ctypes
  2866. import ctypes.wintypes
  2867. WIN_OUTPUT_IDS = {
  2868. 1: -11,
  2869. 2: -12,
  2870. }
  2871. try:
  2872. fileno = out.fileno()
  2873. except AttributeError:
  2874. # If the output stream doesn't have a fileno, it's virtual
  2875. return False
  2876. except io.UnsupportedOperation:
  2877. # Some strange Windows pseudo files?
  2878. return False
  2879. if fileno not in WIN_OUTPUT_IDS:
  2880. return False
  2881. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  2882. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  2883. ('GetStdHandle', ctypes.windll.kernel32))
  2884. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  2885. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  2886. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  2887. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  2888. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  2889. written = ctypes.wintypes.DWORD(0)
  2890. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  2891. FILE_TYPE_CHAR = 0x0002
  2892. FILE_TYPE_REMOTE = 0x8000
  2893. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  2894. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  2895. ctypes.POINTER(ctypes.wintypes.DWORD))(
  2896. ('GetConsoleMode', ctypes.windll.kernel32))
  2897. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  2898. def not_a_console(handle):
  2899. if handle == INVALID_HANDLE_VALUE or handle is None:
  2900. return True
  2901. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  2902. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  2903. if not_a_console(h):
  2904. return False
  2905. def next_nonbmp_pos(s):
  2906. try:
  2907. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  2908. except StopIteration:
  2909. return len(s)
  2910. while s:
  2911. count = min(next_nonbmp_pos(s), 1024)
  2912. ret = WriteConsoleW(
  2913. h, s, count if count else 2, ctypes.byref(written), None)
  2914. if ret == 0:
  2915. raise OSError('Failed to write string')
  2916. if not count: # We just wrote a non-BMP character
  2917. assert written.value == 2
  2918. s = s[1:]
  2919. else:
  2920. assert written.value > 0
  2921. s = s[written.value:]
  2922. return True
  2923. def write_string(s, out=None, encoding=None):
  2924. if out is None:
  2925. out = sys.stderr
  2926. assert type(s) == compat_str
  2927. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  2928. if _windows_write_string(s, out):
  2929. return
  2930. if ('b' in getattr(out, 'mode', '')
  2931. or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  2932. byt = s.encode(encoding or preferredencoding(), 'ignore')
  2933. out.write(byt)
  2934. elif hasattr(out, 'buffer'):
  2935. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  2936. byt = s.encode(enc, 'ignore')
  2937. out.buffer.write(byt)
  2938. else:
  2939. out.write(s)
  2940. out.flush()
  2941. def bytes_to_intlist(bs):
  2942. if not bs:
  2943. return []
  2944. if isinstance(bs[0], int): # Python 3
  2945. return list(bs)
  2946. else:
  2947. return [ord(c) for c in bs]
  2948. def intlist_to_bytes(xs):
  2949. if not xs:
  2950. return b''
  2951. return compat_struct_pack('%dB' % len(xs), *xs)
  2952. # Cross-platform file locking
  2953. if sys.platform == 'win32':
  2954. import ctypes.wintypes
  2955. import msvcrt
  2956. class OVERLAPPED(ctypes.Structure):
  2957. _fields_ = [
  2958. ('Internal', ctypes.wintypes.LPVOID),
  2959. ('InternalHigh', ctypes.wintypes.LPVOID),
  2960. ('Offset', ctypes.wintypes.DWORD),
  2961. ('OffsetHigh', ctypes.wintypes.DWORD),
  2962. ('hEvent', ctypes.wintypes.HANDLE),
  2963. ]
  2964. kernel32 = ctypes.windll.kernel32
  2965. LockFileEx = kernel32.LockFileEx
  2966. LockFileEx.argtypes = [
  2967. ctypes.wintypes.HANDLE, # hFile
  2968. ctypes.wintypes.DWORD, # dwFlags
  2969. ctypes.wintypes.DWORD, # dwReserved
  2970. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2971. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2972. ctypes.POINTER(OVERLAPPED) # Overlapped
  2973. ]
  2974. LockFileEx.restype = ctypes.wintypes.BOOL
  2975. UnlockFileEx = kernel32.UnlockFileEx
  2976. UnlockFileEx.argtypes = [
  2977. ctypes.wintypes.HANDLE, # hFile
  2978. ctypes.wintypes.DWORD, # dwReserved
  2979. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  2980. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  2981. ctypes.POINTER(OVERLAPPED) # Overlapped
  2982. ]
  2983. UnlockFileEx.restype = ctypes.wintypes.BOOL
  2984. whole_low = 0xffffffff
  2985. whole_high = 0x7fffffff
  2986. def _lock_file(f, exclusive):
  2987. overlapped = OVERLAPPED()
  2988. overlapped.Offset = 0
  2989. overlapped.OffsetHigh = 0
  2990. overlapped.hEvent = 0
  2991. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  2992. handle = msvcrt.get_osfhandle(f.fileno())
  2993. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  2994. whole_low, whole_high, f._lock_file_overlapped_p):
  2995. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  2996. def _unlock_file(f):
  2997. assert f._lock_file_overlapped_p
  2998. handle = msvcrt.get_osfhandle(f.fileno())
  2999. if not UnlockFileEx(handle, 0,
  3000. whole_low, whole_high, f._lock_file_overlapped_p):
  3001. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  3002. else:
  3003. # Some platforms, such as Jython, is missing fcntl
  3004. try:
  3005. import fcntl
  3006. def _lock_file(f, exclusive):
  3007. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  3008. def _unlock_file(f):
  3009. fcntl.flock(f, fcntl.LOCK_UN)
  3010. except ImportError:
  3011. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  3012. def _lock_file(f, exclusive):
  3013. raise IOError(UNSUPPORTED_MSG)
  3014. def _unlock_file(f):
  3015. raise IOError(UNSUPPORTED_MSG)
  3016. class locked_file(object):
  3017. def __init__(self, filename, mode, encoding=None):
  3018. assert mode in ['r', 'a', 'w']
  3019. self.f = io.open(filename, mode, encoding=encoding)
  3020. self.mode = mode
  3021. def __enter__(self):
  3022. exclusive = self.mode != 'r'
  3023. try:
  3024. _lock_file(self.f, exclusive)
  3025. except IOError:
  3026. self.f.close()
  3027. raise
  3028. return self
  3029. def __exit__(self, etype, value, traceback):
  3030. try:
  3031. _unlock_file(self.f)
  3032. finally:
  3033. self.f.close()
  3034. def __iter__(self):
  3035. return iter(self.f)
  3036. def write(self, *args):
  3037. return self.f.write(*args)
  3038. def read(self, *args):
  3039. return self.f.read(*args)
  3040. def get_filesystem_encoding():
  3041. encoding = sys.getfilesystemencoding()
  3042. return encoding if encoding is not None else 'utf-8'
  3043. def shell_quote(args):
  3044. quoted_args = []
  3045. encoding = get_filesystem_encoding()
  3046. for a in args:
  3047. if isinstance(a, bytes):
  3048. # We may get a filename encoded with 'encodeFilename'
  3049. a = a.decode(encoding)
  3050. quoted_args.append(compat_shlex_quote(a))
  3051. return ' '.join(quoted_args)
  3052. def smuggle_url(url, data):
  3053. """ Pass additional data in a URL for internal use. """
  3054. url, idata = unsmuggle_url(url, {})
  3055. data.update(idata)
  3056. sdata = compat_urllib_parse_urlencode(
  3057. {'__youtubedl_smuggle': json.dumps(data)})
  3058. return url + '#' + sdata
  3059. def unsmuggle_url(smug_url, default=None):
  3060. if '#__youtubedl_smuggle' not in smug_url:
  3061. return smug_url, default
  3062. url, _, sdata = smug_url.rpartition('#')
  3063. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  3064. data = json.loads(jsond)
  3065. return url, data
  3066. def format_bytes(bytes):
  3067. if bytes is None:
  3068. return 'N/A'
  3069. if type(bytes) is str:
  3070. bytes = float(bytes)
  3071. if bytes == 0.0:
  3072. exponent = 0
  3073. else:
  3074. exponent = int(math.log(bytes, 1024.0))
  3075. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  3076. converted = float(bytes) / float(1024 ** exponent)
  3077. return '%.2f%s' % (converted, suffix)
  3078. def lookup_unit_table(unit_table, s):
  3079. units_re = '|'.join(re.escape(u) for u in unit_table)
  3080. m = re.match(
  3081. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  3082. if not m:
  3083. return None
  3084. num_str = m.group('num').replace(',', '.')
  3085. mult = unit_table[m.group('unit')]
  3086. return int(float(num_str) * mult)
  3087. def parse_filesize(s):
  3088. if s is None:
  3089. return None
  3090. # The lower-case forms are of course incorrect and unofficial,
  3091. # but we support those too
  3092. _UNIT_TABLE = {
  3093. 'B': 1,
  3094. 'b': 1,
  3095. 'bytes': 1,
  3096. 'KiB': 1024,
  3097. 'KB': 1000,
  3098. 'kB': 1024,
  3099. 'Kb': 1000,
  3100. 'kb': 1000,
  3101. 'kilobytes': 1000,
  3102. 'kibibytes': 1024,
  3103. 'MiB': 1024 ** 2,
  3104. 'MB': 1000 ** 2,
  3105. 'mB': 1024 ** 2,
  3106. 'Mb': 1000 ** 2,
  3107. 'mb': 1000 ** 2,
  3108. 'megabytes': 1000 ** 2,
  3109. 'mebibytes': 1024 ** 2,
  3110. 'GiB': 1024 ** 3,
  3111. 'GB': 1000 ** 3,
  3112. 'gB': 1024 ** 3,
  3113. 'Gb': 1000 ** 3,
  3114. 'gb': 1000 ** 3,
  3115. 'gigabytes': 1000 ** 3,
  3116. 'gibibytes': 1024 ** 3,
  3117. 'TiB': 1024 ** 4,
  3118. 'TB': 1000 ** 4,
  3119. 'tB': 1024 ** 4,
  3120. 'Tb': 1000 ** 4,
  3121. 'tb': 1000 ** 4,
  3122. 'terabytes': 1000 ** 4,
  3123. 'tebibytes': 1024 ** 4,
  3124. 'PiB': 1024 ** 5,
  3125. 'PB': 1000 ** 5,
  3126. 'pB': 1024 ** 5,
  3127. 'Pb': 1000 ** 5,
  3128. 'pb': 1000 ** 5,
  3129. 'petabytes': 1000 ** 5,
  3130. 'pebibytes': 1024 ** 5,
  3131. 'EiB': 1024 ** 6,
  3132. 'EB': 1000 ** 6,
  3133. 'eB': 1024 ** 6,
  3134. 'Eb': 1000 ** 6,
  3135. 'eb': 1000 ** 6,
  3136. 'exabytes': 1000 ** 6,
  3137. 'exbibytes': 1024 ** 6,
  3138. 'ZiB': 1024 ** 7,
  3139. 'ZB': 1000 ** 7,
  3140. 'zB': 1024 ** 7,
  3141. 'Zb': 1000 ** 7,
  3142. 'zb': 1000 ** 7,
  3143. 'zettabytes': 1000 ** 7,
  3144. 'zebibytes': 1024 ** 7,
  3145. 'YiB': 1024 ** 8,
  3146. 'YB': 1000 ** 8,
  3147. 'yB': 1024 ** 8,
  3148. 'Yb': 1000 ** 8,
  3149. 'yb': 1000 ** 8,
  3150. 'yottabytes': 1000 ** 8,
  3151. 'yobibytes': 1024 ** 8,
  3152. }
  3153. return lookup_unit_table(_UNIT_TABLE, s)
  3154. def parse_count(s):
  3155. if s is None:
  3156. return None
  3157. s = s.strip()
  3158. if re.match(r'^[\d,.]+$', s):
  3159. return str_to_int(s)
  3160. _UNIT_TABLE = {
  3161. 'k': 1000,
  3162. 'K': 1000,
  3163. 'm': 1000 ** 2,
  3164. 'M': 1000 ** 2,
  3165. 'kk': 1000 ** 2,
  3166. 'KK': 1000 ** 2,
  3167. }
  3168. return lookup_unit_table(_UNIT_TABLE, s)
  3169. def parse_resolution(s):
  3170. if s is None:
  3171. return {}
  3172. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  3173. if mobj:
  3174. return {
  3175. 'width': int(mobj.group('w')),
  3176. 'height': int(mobj.group('h')),
  3177. }
  3178. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  3179. if mobj:
  3180. return {'height': int(mobj.group(1))}
  3181. mobj = re.search(r'\b([48])[kK]\b', s)
  3182. if mobj:
  3183. return {'height': int(mobj.group(1)) * 540}
  3184. return {}
  3185. def parse_bitrate(s):
  3186. if not isinstance(s, compat_str):
  3187. return
  3188. mobj = re.search(r'\b(\d+)\s*kbps', s)
  3189. if mobj:
  3190. return int(mobj.group(1))
  3191. def month_by_name(name, lang='en'):
  3192. """ Return the number of a month by (locale-independently) English name """
  3193. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  3194. try:
  3195. return month_names.index(name) + 1
  3196. except ValueError:
  3197. return None
  3198. def month_by_abbreviation(abbrev):
  3199. """ Return the number of a month by (locale-independently) English
  3200. abbreviations """
  3201. try:
  3202. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  3203. except ValueError:
  3204. return None
  3205. def fix_xml_ampersands(xml_str):
  3206. """Replace all the '&' by '&amp;' in XML"""
  3207. return re.sub(
  3208. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  3209. '&amp;',
  3210. xml_str)
  3211. def setproctitle(title):
  3212. assert isinstance(title, compat_str)
  3213. # ctypes in Jython is not complete
  3214. # http://bugs.jython.org/issue2148
  3215. if sys.platform.startswith('java'):
  3216. return
  3217. try:
  3218. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  3219. except OSError:
  3220. return
  3221. except TypeError:
  3222. # LoadLibrary in Windows Python 2.7.13 only expects
  3223. # a bytestring, but since unicode_literals turns
  3224. # every string into a unicode string, it fails.
  3225. return
  3226. title_bytes = title.encode('utf-8')
  3227. buf = ctypes.create_string_buffer(len(title_bytes))
  3228. buf.value = title_bytes
  3229. try:
  3230. libc.prctl(15, buf, 0, 0, 0)
  3231. except AttributeError:
  3232. return # Strange libc, just skip this
  3233. def remove_start(s, start):
  3234. return s[len(start):] if s is not None and s.startswith(start) else s
  3235. def remove_end(s, end):
  3236. return s[:-len(end)] if s is not None and s.endswith(end) else s
  3237. def remove_quotes(s):
  3238. if s is None or len(s) < 2:
  3239. return s
  3240. for quote in ('"', "'", ):
  3241. if s[0] == quote and s[-1] == quote:
  3242. return s[1:-1]
  3243. return s
  3244. def url_basename(url):
  3245. path = compat_urlparse.urlparse(url).path
  3246. return path.strip('/').split('/')[-1]
  3247. def base_url(url):
  3248. return re.match(r'https?://[^?#&]+/', url).group()
  3249. def urljoin(base, path):
  3250. if isinstance(path, bytes):
  3251. path = path.decode('utf-8')
  3252. if not isinstance(path, compat_str) or not path:
  3253. return None
  3254. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  3255. return path
  3256. if isinstance(base, bytes):
  3257. base = base.decode('utf-8')
  3258. if not isinstance(base, compat_str) or not re.match(
  3259. r'^(?:https?:)?//', base):
  3260. return None
  3261. return compat_urlparse.urljoin(base, path)
  3262. class HEADRequest(compat_urllib_request.Request):
  3263. def get_method(self):
  3264. return 'HEAD'
  3265. class PUTRequest(compat_urllib_request.Request):
  3266. def get_method(self):
  3267. return 'PUT'
  3268. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  3269. if get_attr:
  3270. if v is not None:
  3271. v = getattr(v, get_attr, None)
  3272. if v == '':
  3273. v = None
  3274. if v is None:
  3275. return default
  3276. try:
  3277. return int(v) * invscale // scale
  3278. except (ValueError, TypeError):
  3279. return default
  3280. def str_or_none(v, default=None):
  3281. return default if v is None else compat_str(v)
  3282. def str_to_int(int_str):
  3283. """ A more relaxed version of int_or_none """
  3284. if isinstance(int_str, compat_integer_types):
  3285. return int_str
  3286. elif isinstance(int_str, compat_str):
  3287. int_str = re.sub(r'[,\.\+]', '', int_str)
  3288. return int_or_none(int_str)
  3289. def float_or_none(v, scale=1, invscale=1, default=None):
  3290. if v is None:
  3291. return default
  3292. try:
  3293. return float(v) * invscale / scale
  3294. except (ValueError, TypeError):
  3295. return default
  3296. def bool_or_none(v, default=None):
  3297. return v if isinstance(v, bool) else default
  3298. def strip_or_none(v, default=None):
  3299. return v.strip() if isinstance(v, compat_str) else default
  3300. def url_or_none(url):
  3301. if not url or not isinstance(url, compat_str):
  3302. return None
  3303. url = url.strip()
  3304. return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None
  3305. def parse_duration(s):
  3306. if not isinstance(s, compat_basestring):
  3307. return None
  3308. s = s.strip()
  3309. days, hours, mins, secs, ms = [None] * 5
  3310. 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)
  3311. if m:
  3312. days, hours, mins, secs, ms = m.groups()
  3313. else:
  3314. m = re.match(
  3315. r'''(?ix)(?:P?
  3316. (?:
  3317. [0-9]+\s*y(?:ears?)?\s*
  3318. )?
  3319. (?:
  3320. [0-9]+\s*m(?:onths?)?\s*
  3321. )?
  3322. (?:
  3323. [0-9]+\s*w(?:eeks?)?\s*
  3324. )?
  3325. (?:
  3326. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  3327. )?
  3328. T)?
  3329. (?:
  3330. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  3331. )?
  3332. (?:
  3333. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  3334. )?
  3335. (?:
  3336. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  3337. )?Z?$''', s)
  3338. if m:
  3339. days, hours, mins, secs, ms = m.groups()
  3340. else:
  3341. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  3342. if m:
  3343. hours, mins = m.groups()
  3344. else:
  3345. return None
  3346. duration = 0
  3347. if secs:
  3348. duration += float(secs)
  3349. if mins:
  3350. duration += float(mins) * 60
  3351. if hours:
  3352. duration += float(hours) * 60 * 60
  3353. if days:
  3354. duration += float(days) * 24 * 60 * 60
  3355. if ms:
  3356. duration += float(ms)
  3357. return duration
  3358. def prepend_extension(filename, ext, expected_real_ext=None):
  3359. name, real_ext = os.path.splitext(filename)
  3360. return (
  3361. '{0}.{1}{2}'.format(name, ext, real_ext)
  3362. if not expected_real_ext or real_ext[1:] == expected_real_ext
  3363. else '{0}.{1}'.format(filename, ext))
  3364. def replace_extension(filename, ext, expected_real_ext=None):
  3365. name, real_ext = os.path.splitext(filename)
  3366. return '{0}.{1}'.format(
  3367. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  3368. ext)
  3369. def check_executable(exe, args=[]):
  3370. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  3371. args can be a list of arguments for a short output (like -version) """
  3372. try:
  3373. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  3374. except OSError:
  3375. return False
  3376. return exe
  3377. def get_exe_version(exe, args=['--version'],
  3378. version_re=None, unrecognized='present'):
  3379. """ Returns the version of the specified executable,
  3380. or False if the executable is not present """
  3381. try:
  3382. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  3383. # SIGTTOU if youtube-dl is run in the background.
  3384. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  3385. out, _ = subprocess.Popen(
  3386. [encodeArgument(exe)] + args,
  3387. stdin=subprocess.PIPE,
  3388. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  3389. except OSError:
  3390. return False
  3391. if isinstance(out, bytes): # Python 2.x
  3392. out = out.decode('ascii', 'ignore')
  3393. return detect_exe_version(out, version_re, unrecognized)
  3394. def detect_exe_version(output, version_re=None, unrecognized='present'):
  3395. assert isinstance(output, compat_str)
  3396. if version_re is None:
  3397. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  3398. m = re.search(version_re, output)
  3399. if m:
  3400. return m.group(1)
  3401. else:
  3402. return unrecognized
  3403. class PagedList(object):
  3404. def __len__(self):
  3405. # This is only useful for tests
  3406. return len(self.getslice())
  3407. class OnDemandPagedList(PagedList):
  3408. def __init__(self, pagefunc, pagesize, use_cache=True):
  3409. self._pagefunc = pagefunc
  3410. self._pagesize = pagesize
  3411. self._use_cache = use_cache
  3412. if use_cache:
  3413. self._cache = {}
  3414. def getslice(self, start=0, end=None):
  3415. res = []
  3416. for pagenum in itertools.count(start // self._pagesize):
  3417. firstid = pagenum * self._pagesize
  3418. nextfirstid = pagenum * self._pagesize + self._pagesize
  3419. if start >= nextfirstid:
  3420. continue
  3421. page_results = None
  3422. if self._use_cache:
  3423. page_results = self._cache.get(pagenum)
  3424. if page_results is None:
  3425. page_results = list(self._pagefunc(pagenum))
  3426. if self._use_cache:
  3427. self._cache[pagenum] = page_results
  3428. startv = (
  3429. start % self._pagesize
  3430. if firstid <= start < nextfirstid
  3431. else 0)
  3432. endv = (
  3433. ((end - 1) % self._pagesize) + 1
  3434. if (end is not None and firstid <= end <= nextfirstid)
  3435. else None)
  3436. if startv != 0 or endv is not None:
  3437. page_results = page_results[startv:endv]
  3438. res.extend(page_results)
  3439. # A little optimization - if current page is not "full", ie. does
  3440. # not contain page_size videos then we can assume that this page
  3441. # is the last one - there are no more ids on further pages -
  3442. # i.e. no need to query again.
  3443. if len(page_results) + startv < self._pagesize:
  3444. break
  3445. # If we got the whole page, but the next page is not interesting,
  3446. # break out early as well
  3447. if end == nextfirstid:
  3448. break
  3449. return res
  3450. class InAdvancePagedList(PagedList):
  3451. def __init__(self, pagefunc, pagecount, pagesize):
  3452. self._pagefunc = pagefunc
  3453. self._pagecount = pagecount
  3454. self._pagesize = pagesize
  3455. def getslice(self, start=0, end=None):
  3456. res = []
  3457. start_page = start // self._pagesize
  3458. end_page = (
  3459. self._pagecount if end is None else (end // self._pagesize + 1))
  3460. skip_elems = start - start_page * self._pagesize
  3461. only_more = None if end is None else end - start
  3462. for pagenum in range(start_page, end_page):
  3463. page = list(self._pagefunc(pagenum))
  3464. if skip_elems:
  3465. page = page[skip_elems:]
  3466. skip_elems = None
  3467. if only_more is not None:
  3468. if len(page) < only_more:
  3469. only_more -= len(page)
  3470. else:
  3471. page = page[:only_more]
  3472. res.extend(page)
  3473. break
  3474. res.extend(page)
  3475. return res
  3476. def uppercase_escape(s):
  3477. unicode_escape = codecs.getdecoder('unicode_escape')
  3478. return re.sub(
  3479. r'\\U[0-9a-fA-F]{8}',
  3480. lambda m: unicode_escape(m.group(0))[0],
  3481. s)
  3482. def lowercase_escape(s):
  3483. unicode_escape = codecs.getdecoder('unicode_escape')
  3484. return re.sub(
  3485. r'\\u[0-9a-fA-F]{4}',
  3486. lambda m: unicode_escape(m.group(0))[0],
  3487. s)
  3488. def escape_rfc3986(s):
  3489. """Escape non-ASCII characters as suggested by RFC 3986"""
  3490. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  3491. s = s.encode('utf-8')
  3492. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  3493. def escape_url(url):
  3494. """Escape URL as suggested by RFC 3986"""
  3495. url_parsed = compat_urllib_parse_urlparse(url)
  3496. return url_parsed._replace(
  3497. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  3498. path=escape_rfc3986(url_parsed.path),
  3499. params=escape_rfc3986(url_parsed.params),
  3500. query=escape_rfc3986(url_parsed.query),
  3501. fragment=escape_rfc3986(url_parsed.fragment)
  3502. ).geturl()
  3503. def read_batch_urls(batch_fd):
  3504. def fixup(url):
  3505. if not isinstance(url, compat_str):
  3506. url = url.decode('utf-8', 'replace')
  3507. BOM_UTF8 = '\xef\xbb\xbf'
  3508. if url.startswith(BOM_UTF8):
  3509. url = url[len(BOM_UTF8):]
  3510. url = url.strip()
  3511. if url.startswith(('#', ';', ']')):
  3512. return False
  3513. return url
  3514. with contextlib.closing(batch_fd) as fd:
  3515. return [url for url in map(fixup, fd) if url]
  3516. def urlencode_postdata(*args, **kargs):
  3517. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  3518. def update_url_query(url, query):
  3519. if not query:
  3520. return url
  3521. parsed_url = compat_urlparse.urlparse(url)
  3522. qs = compat_parse_qs(parsed_url.query)
  3523. qs.update(query)
  3524. return compat_urlparse.urlunparse(parsed_url._replace(
  3525. query=compat_urllib_parse_urlencode(qs, True)))
  3526. def update_Request(req, url=None, data=None, headers={}, query={}):
  3527. req_headers = req.headers.copy()
  3528. req_headers.update(headers)
  3529. req_data = data or req.data
  3530. req_url = update_url_query(url or req.get_full_url(), query)
  3531. req_get_method = req.get_method()
  3532. if req_get_method == 'HEAD':
  3533. req_type = HEADRequest
  3534. elif req_get_method == 'PUT':
  3535. req_type = PUTRequest
  3536. else:
  3537. req_type = compat_urllib_request.Request
  3538. new_req = req_type(
  3539. req_url, data=req_data, headers=req_headers,
  3540. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  3541. if hasattr(req, 'timeout'):
  3542. new_req.timeout = req.timeout
  3543. return new_req
  3544. def _multipart_encode_impl(data, boundary):
  3545. content_type = 'multipart/form-data; boundary=%s' % boundary
  3546. out = b''
  3547. for k, v in data.items():
  3548. out += b'--' + boundary.encode('ascii') + b'\r\n'
  3549. if isinstance(k, compat_str):
  3550. k = k.encode('utf-8')
  3551. if isinstance(v, compat_str):
  3552. v = v.encode('utf-8')
  3553. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  3554. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  3555. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  3556. if boundary.encode('ascii') in content:
  3557. raise ValueError('Boundary overlaps with data')
  3558. out += content
  3559. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  3560. return out, content_type
  3561. def multipart_encode(data, boundary=None):
  3562. '''
  3563. Encode a dict to RFC 7578-compliant form-data
  3564. data:
  3565. A dict where keys and values can be either Unicode or bytes-like
  3566. objects.
  3567. boundary:
  3568. If specified a Unicode object, it's used as the boundary. Otherwise
  3569. a random boundary is generated.
  3570. Reference: https://tools.ietf.org/html/rfc7578
  3571. '''
  3572. has_specified_boundary = boundary is not None
  3573. while True:
  3574. if boundary is None:
  3575. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  3576. try:
  3577. out, content_type = _multipart_encode_impl(data, boundary)
  3578. break
  3579. except ValueError:
  3580. if has_specified_boundary:
  3581. raise
  3582. boundary = None
  3583. return out, content_type
  3584. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  3585. if isinstance(key_or_keys, (list, tuple)):
  3586. for key in key_or_keys:
  3587. if key not in d or d[key] is None or skip_false_values and not d[key]:
  3588. continue
  3589. return d[key]
  3590. return default
  3591. return d.get(key_or_keys, default)
  3592. def try_get(src, getter, expected_type=None):
  3593. if not isinstance(getter, (list, tuple)):
  3594. getter = [getter]
  3595. for get in getter:
  3596. try:
  3597. v = get(src)
  3598. except (AttributeError, KeyError, TypeError, IndexError):
  3599. pass
  3600. else:
  3601. if expected_type is None or isinstance(v, expected_type):
  3602. return v
  3603. def merge_dicts(*dicts):
  3604. merged = {}
  3605. for a_dict in dicts:
  3606. for k, v in a_dict.items():
  3607. if v is None:
  3608. continue
  3609. if (k not in merged
  3610. or (isinstance(v, compat_str) and v
  3611. and isinstance(merged[k], compat_str)
  3612. and not merged[k])):
  3613. merged[k] = v
  3614. return merged
  3615. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  3616. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  3617. US_RATINGS = {
  3618. 'G': 0,
  3619. 'PG': 10,
  3620. 'PG-13': 13,
  3621. 'R': 16,
  3622. 'NC': 18,
  3623. }
  3624. TV_PARENTAL_GUIDELINES = {
  3625. 'TV-Y': 0,
  3626. 'TV-Y7': 7,
  3627. 'TV-G': 0,
  3628. 'TV-PG': 0,
  3629. 'TV-14': 14,
  3630. 'TV-MA': 17,
  3631. }
  3632. def parse_age_limit(s):
  3633. if type(s) == int:
  3634. return s if 0 <= s <= 21 else None
  3635. if not isinstance(s, compat_basestring):
  3636. return None
  3637. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  3638. if m:
  3639. return int(m.group('age'))
  3640. if s in US_RATINGS:
  3641. return US_RATINGS[s]
  3642. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  3643. if m:
  3644. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  3645. return None
  3646. def strip_jsonp(code):
  3647. return re.sub(
  3648. r'''(?sx)^
  3649. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  3650. (?:\s*&&\s*(?P=func_name))?
  3651. \s*\(\s*(?P<callback_data>.*)\);?
  3652. \s*?(?://[^\n]*)*$''',
  3653. r'\g<callback_data>', code)
  3654. def js_to_json(code):
  3655. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  3656. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  3657. INTEGER_TABLE = (
  3658. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  3659. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  3660. )
  3661. def fix_kv(m):
  3662. v = m.group(0)
  3663. if v in ('true', 'false', 'null'):
  3664. return v
  3665. elif v.startswith('/*') or v.startswith('//') or v.startswith('!') or v == ',':
  3666. return ""
  3667. if v[0] in ("'", '"'):
  3668. v = re.sub(r'(?s)\\.|"', lambda m: {
  3669. '"': '\\"',
  3670. "\\'": "'",
  3671. '\\\n': '',
  3672. '\\x': '\\u00',
  3673. }.get(m.group(0), m.group(0)), v[1:-1])
  3674. else:
  3675. for regex, base in INTEGER_TABLE:
  3676. im = re.match(regex, v)
  3677. if im:
  3678. i = int(im.group(1), base)
  3679. return '"%d":' % i if v.endswith(':') else '%d' % i
  3680. return '"%s"' % v
  3681. return re.sub(r'''(?sx)
  3682. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  3683. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  3684. {comment}|,(?={skip}[\]}}])|
  3685. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  3686. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  3687. [0-9]+(?={skip}:)|
  3688. !+
  3689. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  3690. def qualities(quality_ids):
  3691. """ Get a numeric quality value out of a list of possible values """
  3692. def q(qid):
  3693. try:
  3694. return quality_ids.index(qid)
  3695. except ValueError:
  3696. return -1
  3697. return q
  3698. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  3699. def limit_length(s, length):
  3700. """ Add ellipses to overly long strings """
  3701. if s is None:
  3702. return None
  3703. ELLIPSES = '...'
  3704. if len(s) > length:
  3705. return s[:length - len(ELLIPSES)] + ELLIPSES
  3706. return s
  3707. def version_tuple(v):
  3708. return tuple(int(e) for e in re.split(r'[-.]', v))
  3709. def is_outdated_version(version, limit, assume_new=True):
  3710. if not version:
  3711. return not assume_new
  3712. try:
  3713. return version_tuple(version) < version_tuple(limit)
  3714. except ValueError:
  3715. return not assume_new
  3716. def ytdl_is_updateable():
  3717. """ Returns if youtube-dl can be updated with -U """
  3718. from zipimport import zipimporter
  3719. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  3720. def args_to_str(args):
  3721. # Get a short string representation for a subprocess command
  3722. return ' '.join(compat_shlex_quote(a) for a in args)
  3723. def error_to_compat_str(err):
  3724. err_str = str(err)
  3725. # On python 2 error byte string must be decoded with proper
  3726. # encoding rather than ascii
  3727. if sys.version_info[0] < 3:
  3728. err_str = err_str.decode(preferredencoding())
  3729. return err_str
  3730. def mimetype2ext(mt):
  3731. if mt is None:
  3732. return None
  3733. ext = {
  3734. 'audio/mp4': 'm4a',
  3735. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  3736. # it's the most popular one
  3737. 'audio/mpeg': 'mp3',
  3738. }.get(mt)
  3739. if ext is not None:
  3740. return ext
  3741. _, _, res = mt.rpartition('/')
  3742. res = res.split(';')[0].strip().lower()
  3743. return {
  3744. '3gpp': '3gp',
  3745. 'smptett+xml': 'tt',
  3746. 'ttaf+xml': 'dfxp',
  3747. 'ttml+xml': 'ttml',
  3748. 'x-flv': 'flv',
  3749. 'x-mp4-fragmented': 'mp4',
  3750. 'x-ms-sami': 'sami',
  3751. 'x-ms-wmv': 'wmv',
  3752. 'mpegurl': 'm3u8',
  3753. 'x-mpegurl': 'm3u8',
  3754. 'vnd.apple.mpegurl': 'm3u8',
  3755. 'dash+xml': 'mpd',
  3756. 'f4m+xml': 'f4m',
  3757. 'hds+xml': 'f4m',
  3758. 'vnd.ms-sstr+xml': 'ism',
  3759. 'quicktime': 'mov',
  3760. 'mp2t': 'ts',
  3761. 'x-wav': 'wav',
  3762. }.get(res, res)
  3763. def parse_codecs(codecs_str):
  3764. # http://tools.ietf.org/html/rfc6381
  3765. if not codecs_str:
  3766. return {}
  3767. split_codecs = list(filter(None, map(
  3768. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  3769. vcodec, acodec = None, None
  3770. for full_codec in split_codecs:
  3771. codec = full_codec.split('.')[0]
  3772. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01', 'theora'):
  3773. if not vcodec:
  3774. vcodec = full_codec
  3775. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  3776. if not acodec:
  3777. acodec = full_codec
  3778. else:
  3779. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  3780. if not vcodec and not acodec:
  3781. if len(split_codecs) == 2:
  3782. return {
  3783. 'vcodec': split_codecs[0],
  3784. 'acodec': split_codecs[1],
  3785. }
  3786. else:
  3787. return {
  3788. 'vcodec': vcodec or 'none',
  3789. 'acodec': acodec or 'none',
  3790. }
  3791. return {}
  3792. def urlhandle_detect_ext(url_handle):
  3793. getheader = url_handle.headers.get
  3794. cd = getheader('Content-Disposition')
  3795. if cd:
  3796. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  3797. if m:
  3798. e = determine_ext(m.group('filename'), default_ext=None)
  3799. if e:
  3800. return e
  3801. return mimetype2ext(getheader('Content-Type'))
  3802. def encode_data_uri(data, mime_type):
  3803. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  3804. def age_restricted(content_limit, age_limit):
  3805. """ Returns True iff the content should be blocked """
  3806. if age_limit is None: # No limit set
  3807. return False
  3808. if content_limit is None:
  3809. return False # Content available for everyone
  3810. return age_limit < content_limit
  3811. def is_html(first_bytes):
  3812. """ Detect whether a file contains HTML by examining its first bytes. """
  3813. BOMS = [
  3814. (b'\xef\xbb\xbf', 'utf-8'),
  3815. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  3816. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  3817. (b'\xff\xfe', 'utf-16-le'),
  3818. (b'\xfe\xff', 'utf-16-be'),
  3819. ]
  3820. for bom, enc in BOMS:
  3821. if first_bytes.startswith(bom):
  3822. s = first_bytes[len(bom):].decode(enc, 'replace')
  3823. break
  3824. else:
  3825. s = first_bytes.decode('utf-8', 'replace')
  3826. return re.match(r'^\s*<', s)
  3827. def determine_protocol(info_dict):
  3828. protocol = info_dict.get('protocol')
  3829. if protocol is not None:
  3830. return protocol
  3831. url = info_dict['url']
  3832. if url.startswith('rtmp'):
  3833. return 'rtmp'
  3834. elif url.startswith('mms'):
  3835. return 'mms'
  3836. elif url.startswith('rtsp'):
  3837. return 'rtsp'
  3838. ext = determine_ext(url)
  3839. if ext == 'm3u8':
  3840. return 'm3u8'
  3841. elif ext == 'f4m':
  3842. return 'f4m'
  3843. return compat_urllib_parse_urlparse(url).scheme
  3844. def render_table(header_row, data):
  3845. """ Render a list of rows, each as a list of values """
  3846. table = [header_row] + data
  3847. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  3848. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  3849. return '\n'.join(format_str % tuple(row) for row in table)
  3850. def _match_one(filter_part, dct):
  3851. COMPARISON_OPERATORS = {
  3852. '<': operator.lt,
  3853. '<=': operator.le,
  3854. '>': operator.gt,
  3855. '>=': operator.ge,
  3856. '=': operator.eq,
  3857. '!=': operator.ne,
  3858. }
  3859. operator_rex = re.compile(r'''(?x)\s*
  3860. (?P<key>[a-z_]+)
  3861. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  3862. (?:
  3863. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  3864. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  3865. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  3866. )
  3867. \s*$
  3868. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  3869. m = operator_rex.search(filter_part)
  3870. if m:
  3871. op = COMPARISON_OPERATORS[m.group('op')]
  3872. actual_value = dct.get(m.group('key'))
  3873. if (m.group('quotedstrval') is not None
  3874. or m.group('strval') is not None
  3875. # If the original field is a string and matching comparisonvalue is
  3876. # a number we should respect the origin of the original field
  3877. # and process comparison value as a string (see
  3878. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  3879. or actual_value is not None and m.group('intval') is not None
  3880. and isinstance(actual_value, compat_str)):
  3881. if m.group('op') not in ('=', '!='):
  3882. raise ValueError(
  3883. 'Operator %s does not support string values!' % m.group('op'))
  3884. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  3885. quote = m.group('quote')
  3886. if quote is not None:
  3887. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  3888. else:
  3889. try:
  3890. comparison_value = int(m.group('intval'))
  3891. except ValueError:
  3892. comparison_value = parse_filesize(m.group('intval'))
  3893. if comparison_value is None:
  3894. comparison_value = parse_filesize(m.group('intval') + 'B')
  3895. if comparison_value is None:
  3896. raise ValueError(
  3897. 'Invalid integer value %r in filter part %r' % (
  3898. m.group('intval'), filter_part))
  3899. if actual_value is None:
  3900. return m.group('none_inclusive')
  3901. return op(actual_value, comparison_value)
  3902. UNARY_OPERATORS = {
  3903. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  3904. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  3905. }
  3906. operator_rex = re.compile(r'''(?x)\s*
  3907. (?P<op>%s)\s*(?P<key>[a-z_]+)
  3908. \s*$
  3909. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  3910. m = operator_rex.search(filter_part)
  3911. if m:
  3912. op = UNARY_OPERATORS[m.group('op')]
  3913. actual_value = dct.get(m.group('key'))
  3914. return op(actual_value)
  3915. raise ValueError('Invalid filter part %r' % filter_part)
  3916. def match_str(filter_str, dct):
  3917. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  3918. return all(
  3919. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  3920. def match_filter_func(filter_str):
  3921. def _match_func(info_dict):
  3922. if match_str(filter_str, info_dict):
  3923. return None
  3924. else:
  3925. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  3926. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  3927. return _match_func
  3928. def parse_dfxp_time_expr(time_expr):
  3929. if not time_expr:
  3930. return
  3931. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  3932. if mobj:
  3933. return float(mobj.group('time_offset'))
  3934. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  3935. if mobj:
  3936. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  3937. def srt_subtitles_timecode(seconds):
  3938. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  3939. def dfxp2srt(dfxp_data):
  3940. '''
  3941. @param dfxp_data A bytes-like object containing DFXP data
  3942. @returns A unicode object containing converted SRT data
  3943. '''
  3944. LEGACY_NAMESPACES = (
  3945. (b'http://www.w3.org/ns/ttml', [
  3946. b'http://www.w3.org/2004/11/ttaf1',
  3947. b'http://www.w3.org/2006/04/ttaf1',
  3948. b'http://www.w3.org/2006/10/ttaf1',
  3949. ]),
  3950. (b'http://www.w3.org/ns/ttml#styling', [
  3951. b'http://www.w3.org/ns/ttml#style',
  3952. ]),
  3953. )
  3954. SUPPORTED_STYLING = [
  3955. 'color',
  3956. 'fontFamily',
  3957. 'fontSize',
  3958. 'fontStyle',
  3959. 'fontWeight',
  3960. 'textDecoration'
  3961. ]
  3962. _x = functools.partial(xpath_with_ns, ns_map={
  3963. 'xml': 'http://www.w3.org/XML/1998/namespace',
  3964. 'ttml': 'http://www.w3.org/ns/ttml',
  3965. 'tts': 'http://www.w3.org/ns/ttml#styling',
  3966. })
  3967. styles = {}
  3968. default_style = {}
  3969. class TTMLPElementParser(object):
  3970. _out = ''
  3971. _unclosed_elements = []
  3972. _applied_styles = []
  3973. def start(self, tag, attrib):
  3974. if tag in (_x('ttml:br'), 'br'):
  3975. self._out += '\n'
  3976. else:
  3977. unclosed_elements = []
  3978. style = {}
  3979. element_style_id = attrib.get('style')
  3980. if default_style:
  3981. style.update(default_style)
  3982. if element_style_id:
  3983. style.update(styles.get(element_style_id, {}))
  3984. for prop in SUPPORTED_STYLING:
  3985. prop_val = attrib.get(_x('tts:' + prop))
  3986. if prop_val:
  3987. style[prop] = prop_val
  3988. if style:
  3989. font = ''
  3990. for k, v in sorted(style.items()):
  3991. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  3992. continue
  3993. if k == 'color':
  3994. font += ' color="%s"' % v
  3995. elif k == 'fontSize':
  3996. font += ' size="%s"' % v
  3997. elif k == 'fontFamily':
  3998. font += ' face="%s"' % v
  3999. elif k == 'fontWeight' and v == 'bold':
  4000. self._out += '<b>'
  4001. unclosed_elements.append('b')
  4002. elif k == 'fontStyle' and v == 'italic':
  4003. self._out += '<i>'
  4004. unclosed_elements.append('i')
  4005. elif k == 'textDecoration' and v == 'underline':
  4006. self._out += '<u>'
  4007. unclosed_elements.append('u')
  4008. if font:
  4009. self._out += '<font' + font + '>'
  4010. unclosed_elements.append('font')
  4011. applied_style = {}
  4012. if self._applied_styles:
  4013. applied_style.update(self._applied_styles[-1])
  4014. applied_style.update(style)
  4015. self._applied_styles.append(applied_style)
  4016. self._unclosed_elements.append(unclosed_elements)
  4017. def end(self, tag):
  4018. if tag not in (_x('ttml:br'), 'br'):
  4019. unclosed_elements = self._unclosed_elements.pop()
  4020. for element in reversed(unclosed_elements):
  4021. self._out += '</%s>' % element
  4022. if unclosed_elements and self._applied_styles:
  4023. self._applied_styles.pop()
  4024. def data(self, data):
  4025. self._out += data
  4026. def close(self):
  4027. return self._out.strip()
  4028. def parse_node(node):
  4029. target = TTMLPElementParser()
  4030. parser = xml.etree.ElementTree.XMLParser(target=target)
  4031. parser.feed(xml.etree.ElementTree.tostring(node))
  4032. return parser.close()
  4033. for k, v in LEGACY_NAMESPACES:
  4034. for ns in v:
  4035. dfxp_data = dfxp_data.replace(ns, k)
  4036. dfxp = compat_etree_fromstring(dfxp_data)
  4037. out = []
  4038. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  4039. if not paras:
  4040. raise ValueError('Invalid dfxp/TTML subtitle')
  4041. repeat = False
  4042. while True:
  4043. for style in dfxp.findall(_x('.//ttml:style')):
  4044. style_id = style.get('id') or style.get(_x('xml:id'))
  4045. if not style_id:
  4046. continue
  4047. parent_style_id = style.get('style')
  4048. if parent_style_id:
  4049. if parent_style_id not in styles:
  4050. repeat = True
  4051. continue
  4052. styles[style_id] = styles[parent_style_id].copy()
  4053. for prop in SUPPORTED_STYLING:
  4054. prop_val = style.get(_x('tts:' + prop))
  4055. if prop_val:
  4056. styles.setdefault(style_id, {})[prop] = prop_val
  4057. if repeat:
  4058. repeat = False
  4059. else:
  4060. break
  4061. for p in ('body', 'div'):
  4062. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  4063. if ele is None:
  4064. continue
  4065. style = styles.get(ele.get('style'))
  4066. if not style:
  4067. continue
  4068. default_style.update(style)
  4069. for para, index in zip(paras, itertools.count(1)):
  4070. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  4071. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  4072. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  4073. if begin_time is None:
  4074. continue
  4075. if not end_time:
  4076. if not dur:
  4077. continue
  4078. end_time = begin_time + dur
  4079. out.append('%d\n%s --> %s\n%s\n\n' % (
  4080. index,
  4081. srt_subtitles_timecode(begin_time),
  4082. srt_subtitles_timecode(end_time),
  4083. parse_node(para)))
  4084. return ''.join(out)
  4085. def cli_option(params, command_option, param):
  4086. param = params.get(param)
  4087. if param:
  4088. param = compat_str(param)
  4089. return [command_option, param] if param is not None else []
  4090. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  4091. param = params.get(param)
  4092. if param is None:
  4093. return []
  4094. assert isinstance(param, bool)
  4095. if separator:
  4096. return [command_option + separator + (true_value if param else false_value)]
  4097. return [command_option, true_value if param else false_value]
  4098. def cli_valueless_option(params, command_option, param, expected_value=True):
  4099. param = params.get(param)
  4100. return [command_option] if param == expected_value else []
  4101. def cli_configuration_args(params, param, default=[]):
  4102. ex_args = params.get(param)
  4103. if ex_args is None:
  4104. return default
  4105. assert isinstance(ex_args, list)
  4106. return ex_args
  4107. class ISO639Utils(object):
  4108. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  4109. _lang_map = {
  4110. 'aa': 'aar',
  4111. 'ab': 'abk',
  4112. 'ae': 'ave',
  4113. 'af': 'afr',
  4114. 'ak': 'aka',
  4115. 'am': 'amh',
  4116. 'an': 'arg',
  4117. 'ar': 'ara',
  4118. 'as': 'asm',
  4119. 'av': 'ava',
  4120. 'ay': 'aym',
  4121. 'az': 'aze',
  4122. 'ba': 'bak',
  4123. 'be': 'bel',
  4124. 'bg': 'bul',
  4125. 'bh': 'bih',
  4126. 'bi': 'bis',
  4127. 'bm': 'bam',
  4128. 'bn': 'ben',
  4129. 'bo': 'bod',
  4130. 'br': 'bre',
  4131. 'bs': 'bos',
  4132. 'ca': 'cat',
  4133. 'ce': 'che',
  4134. 'ch': 'cha',
  4135. 'co': 'cos',
  4136. 'cr': 'cre',
  4137. 'cs': 'ces',
  4138. 'cu': 'chu',
  4139. 'cv': 'chv',
  4140. 'cy': 'cym',
  4141. 'da': 'dan',
  4142. 'de': 'deu',
  4143. 'dv': 'div',
  4144. 'dz': 'dzo',
  4145. 'ee': 'ewe',
  4146. 'el': 'ell',
  4147. 'en': 'eng',
  4148. 'eo': 'epo',
  4149. 'es': 'spa',
  4150. 'et': 'est',
  4151. 'eu': 'eus',
  4152. 'fa': 'fas',
  4153. 'ff': 'ful',
  4154. 'fi': 'fin',
  4155. 'fj': 'fij',
  4156. 'fo': 'fao',
  4157. 'fr': 'fra',
  4158. 'fy': 'fry',
  4159. 'ga': 'gle',
  4160. 'gd': 'gla',
  4161. 'gl': 'glg',
  4162. 'gn': 'grn',
  4163. 'gu': 'guj',
  4164. 'gv': 'glv',
  4165. 'ha': 'hau',
  4166. 'he': 'heb',
  4167. 'iw': 'heb', # Replaced by he in 1989 revision
  4168. 'hi': 'hin',
  4169. 'ho': 'hmo',
  4170. 'hr': 'hrv',
  4171. 'ht': 'hat',
  4172. 'hu': 'hun',
  4173. 'hy': 'hye',
  4174. 'hz': 'her',
  4175. 'ia': 'ina',
  4176. 'id': 'ind',
  4177. 'in': 'ind', # Replaced by id in 1989 revision
  4178. 'ie': 'ile',
  4179. 'ig': 'ibo',
  4180. 'ii': 'iii',
  4181. 'ik': 'ipk',
  4182. 'io': 'ido',
  4183. 'is': 'isl',
  4184. 'it': 'ita',
  4185. 'iu': 'iku',
  4186. 'ja': 'jpn',
  4187. 'jv': 'jav',
  4188. 'ka': 'kat',
  4189. 'kg': 'kon',
  4190. 'ki': 'kik',
  4191. 'kj': 'kua',
  4192. 'kk': 'kaz',
  4193. 'kl': 'kal',
  4194. 'km': 'khm',
  4195. 'kn': 'kan',
  4196. 'ko': 'kor',
  4197. 'kr': 'kau',
  4198. 'ks': 'kas',
  4199. 'ku': 'kur',
  4200. 'kv': 'kom',
  4201. 'kw': 'cor',
  4202. 'ky': 'kir',
  4203. 'la': 'lat',
  4204. 'lb': 'ltz',
  4205. 'lg': 'lug',
  4206. 'li': 'lim',
  4207. 'ln': 'lin',
  4208. 'lo': 'lao',
  4209. 'lt': 'lit',
  4210. 'lu': 'lub',
  4211. 'lv': 'lav',
  4212. 'mg': 'mlg',
  4213. 'mh': 'mah',
  4214. 'mi': 'mri',
  4215. 'mk': 'mkd',
  4216. 'ml': 'mal',
  4217. 'mn': 'mon',
  4218. 'mr': 'mar',
  4219. 'ms': 'msa',
  4220. 'mt': 'mlt',
  4221. 'my': 'mya',
  4222. 'na': 'nau',
  4223. 'nb': 'nob',
  4224. 'nd': 'nde',
  4225. 'ne': 'nep',
  4226. 'ng': 'ndo',
  4227. 'nl': 'nld',
  4228. 'nn': 'nno',
  4229. 'no': 'nor',
  4230. 'nr': 'nbl',
  4231. 'nv': 'nav',
  4232. 'ny': 'nya',
  4233. 'oc': 'oci',
  4234. 'oj': 'oji',
  4235. 'om': 'orm',
  4236. 'or': 'ori',
  4237. 'os': 'oss',
  4238. 'pa': 'pan',
  4239. 'pi': 'pli',
  4240. 'pl': 'pol',
  4241. 'ps': 'pus',
  4242. 'pt': 'por',
  4243. 'qu': 'que',
  4244. 'rm': 'roh',
  4245. 'rn': 'run',
  4246. 'ro': 'ron',
  4247. 'ru': 'rus',
  4248. 'rw': 'kin',
  4249. 'sa': 'san',
  4250. 'sc': 'srd',
  4251. 'sd': 'snd',
  4252. 'se': 'sme',
  4253. 'sg': 'sag',
  4254. 'si': 'sin',
  4255. 'sk': 'slk',
  4256. 'sl': 'slv',
  4257. 'sm': 'smo',
  4258. 'sn': 'sna',
  4259. 'so': 'som',
  4260. 'sq': 'sqi',
  4261. 'sr': 'srp',
  4262. 'ss': 'ssw',
  4263. 'st': 'sot',
  4264. 'su': 'sun',
  4265. 'sv': 'swe',
  4266. 'sw': 'swa',
  4267. 'ta': 'tam',
  4268. 'te': 'tel',
  4269. 'tg': 'tgk',
  4270. 'th': 'tha',
  4271. 'ti': 'tir',
  4272. 'tk': 'tuk',
  4273. 'tl': 'tgl',
  4274. 'tn': 'tsn',
  4275. 'to': 'ton',
  4276. 'tr': 'tur',
  4277. 'ts': 'tso',
  4278. 'tt': 'tat',
  4279. 'tw': 'twi',
  4280. 'ty': 'tah',
  4281. 'ug': 'uig',
  4282. 'uk': 'ukr',
  4283. 'ur': 'urd',
  4284. 'uz': 'uzb',
  4285. 've': 'ven',
  4286. 'vi': 'vie',
  4287. 'vo': 'vol',
  4288. 'wa': 'wln',
  4289. 'wo': 'wol',
  4290. 'xh': 'xho',
  4291. 'yi': 'yid',
  4292. 'ji': 'yid', # Replaced by yi in 1989 revision
  4293. 'yo': 'yor',
  4294. 'za': 'zha',
  4295. 'zh': 'zho',
  4296. 'zu': 'zul',
  4297. }
  4298. @classmethod
  4299. def short2long(cls, code):
  4300. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  4301. return cls._lang_map.get(code[:2])
  4302. @classmethod
  4303. def long2short(cls, code):
  4304. """Convert language code from ISO 639-2/T to ISO 639-1"""
  4305. for short_name, long_name in cls._lang_map.items():
  4306. if long_name == code:
  4307. return short_name
  4308. class ISO3166Utils(object):
  4309. # From http://data.okfn.org/data/core/country-list
  4310. _country_map = {
  4311. 'AF': 'Afghanistan',
  4312. 'AX': 'Åland Islands',
  4313. 'AL': 'Albania',
  4314. 'DZ': 'Algeria',
  4315. 'AS': 'American Samoa',
  4316. 'AD': 'Andorra',
  4317. 'AO': 'Angola',
  4318. 'AI': 'Anguilla',
  4319. 'AQ': 'Antarctica',
  4320. 'AG': 'Antigua and Barbuda',
  4321. 'AR': 'Argentina',
  4322. 'AM': 'Armenia',
  4323. 'AW': 'Aruba',
  4324. 'AU': 'Australia',
  4325. 'AT': 'Austria',
  4326. 'AZ': 'Azerbaijan',
  4327. 'BS': 'Bahamas',
  4328. 'BH': 'Bahrain',
  4329. 'BD': 'Bangladesh',
  4330. 'BB': 'Barbados',
  4331. 'BY': 'Belarus',
  4332. 'BE': 'Belgium',
  4333. 'BZ': 'Belize',
  4334. 'BJ': 'Benin',
  4335. 'BM': 'Bermuda',
  4336. 'BT': 'Bhutan',
  4337. 'BO': 'Bolivia, Plurinational State of',
  4338. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  4339. 'BA': 'Bosnia and Herzegovina',
  4340. 'BW': 'Botswana',
  4341. 'BV': 'Bouvet Island',
  4342. 'BR': 'Brazil',
  4343. 'IO': 'British Indian Ocean Territory',
  4344. 'BN': 'Brunei Darussalam',
  4345. 'BG': 'Bulgaria',
  4346. 'BF': 'Burkina Faso',
  4347. 'BI': 'Burundi',
  4348. 'KH': 'Cambodia',
  4349. 'CM': 'Cameroon',
  4350. 'CA': 'Canada',
  4351. 'CV': 'Cape Verde',
  4352. 'KY': 'Cayman Islands',
  4353. 'CF': 'Central African Republic',
  4354. 'TD': 'Chad',
  4355. 'CL': 'Chile',
  4356. 'CN': 'China',
  4357. 'CX': 'Christmas Island',
  4358. 'CC': 'Cocos (Keeling) Islands',
  4359. 'CO': 'Colombia',
  4360. 'KM': 'Comoros',
  4361. 'CG': 'Congo',
  4362. 'CD': 'Congo, the Democratic Republic of the',
  4363. 'CK': 'Cook Islands',
  4364. 'CR': 'Costa Rica',
  4365. 'CI': 'Côte d\'Ivoire',
  4366. 'HR': 'Croatia',
  4367. 'CU': 'Cuba',
  4368. 'CW': 'Curaçao',
  4369. 'CY': 'Cyprus',
  4370. 'CZ': 'Czech Republic',
  4371. 'DK': 'Denmark',
  4372. 'DJ': 'Djibouti',
  4373. 'DM': 'Dominica',
  4374. 'DO': 'Dominican Republic',
  4375. 'EC': 'Ecuador',
  4376. 'EG': 'Egypt',
  4377. 'SV': 'El Salvador',
  4378. 'GQ': 'Equatorial Guinea',
  4379. 'ER': 'Eritrea',
  4380. 'EE': 'Estonia',
  4381. 'ET': 'Ethiopia',
  4382. 'FK': 'Falkland Islands (Malvinas)',
  4383. 'FO': 'Faroe Islands',
  4384. 'FJ': 'Fiji',
  4385. 'FI': 'Finland',
  4386. 'FR': 'France',
  4387. 'GF': 'French Guiana',
  4388. 'PF': 'French Polynesia',
  4389. 'TF': 'French Southern Territories',
  4390. 'GA': 'Gabon',
  4391. 'GM': 'Gambia',
  4392. 'GE': 'Georgia',
  4393. 'DE': 'Germany',
  4394. 'GH': 'Ghana',
  4395. 'GI': 'Gibraltar',
  4396. 'GR': 'Greece',
  4397. 'GL': 'Greenland',
  4398. 'GD': 'Grenada',
  4399. 'GP': 'Guadeloupe',
  4400. 'GU': 'Guam',
  4401. 'GT': 'Guatemala',
  4402. 'GG': 'Guernsey',
  4403. 'GN': 'Guinea',
  4404. 'GW': 'Guinea-Bissau',
  4405. 'GY': 'Guyana',
  4406. 'HT': 'Haiti',
  4407. 'HM': 'Heard Island and McDonald Islands',
  4408. 'VA': 'Holy See (Vatican City State)',
  4409. 'HN': 'Honduras',
  4410. 'HK': 'Hong Kong',
  4411. 'HU': 'Hungary',
  4412. 'IS': 'Iceland',
  4413. 'IN': 'India',
  4414. 'ID': 'Indonesia',
  4415. 'IR': 'Iran, Islamic Republic of',
  4416. 'IQ': 'Iraq',
  4417. 'IE': 'Ireland',
  4418. 'IM': 'Isle of Man',
  4419. 'IL': 'Israel',
  4420. 'IT': 'Italy',
  4421. 'JM': 'Jamaica',
  4422. 'JP': 'Japan',
  4423. 'JE': 'Jersey',
  4424. 'JO': 'Jordan',
  4425. 'KZ': 'Kazakhstan',
  4426. 'KE': 'Kenya',
  4427. 'KI': 'Kiribati',
  4428. 'KP': 'Korea, Democratic People\'s Republic of',
  4429. 'KR': 'Korea, Republic of',
  4430. 'KW': 'Kuwait',
  4431. 'KG': 'Kyrgyzstan',
  4432. 'LA': 'Lao People\'s Democratic Republic',
  4433. 'LV': 'Latvia',
  4434. 'LB': 'Lebanon',
  4435. 'LS': 'Lesotho',
  4436. 'LR': 'Liberia',
  4437. 'LY': 'Libya',
  4438. 'LI': 'Liechtenstein',
  4439. 'LT': 'Lithuania',
  4440. 'LU': 'Luxembourg',
  4441. 'MO': 'Macao',
  4442. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  4443. 'MG': 'Madagascar',
  4444. 'MW': 'Malawi',
  4445. 'MY': 'Malaysia',
  4446. 'MV': 'Maldives',
  4447. 'ML': 'Mali',
  4448. 'MT': 'Malta',
  4449. 'MH': 'Marshall Islands',
  4450. 'MQ': 'Martinique',
  4451. 'MR': 'Mauritania',
  4452. 'MU': 'Mauritius',
  4453. 'YT': 'Mayotte',
  4454. 'MX': 'Mexico',
  4455. 'FM': 'Micronesia, Federated States of',
  4456. 'MD': 'Moldova, Republic of',
  4457. 'MC': 'Monaco',
  4458. 'MN': 'Mongolia',
  4459. 'ME': 'Montenegro',
  4460. 'MS': 'Montserrat',
  4461. 'MA': 'Morocco',
  4462. 'MZ': 'Mozambique',
  4463. 'MM': 'Myanmar',
  4464. 'NA': 'Namibia',
  4465. 'NR': 'Nauru',
  4466. 'NP': 'Nepal',
  4467. 'NL': 'Netherlands',
  4468. 'NC': 'New Caledonia',
  4469. 'NZ': 'New Zealand',
  4470. 'NI': 'Nicaragua',
  4471. 'NE': 'Niger',
  4472. 'NG': 'Nigeria',
  4473. 'NU': 'Niue',
  4474. 'NF': 'Norfolk Island',
  4475. 'MP': 'Northern Mariana Islands',
  4476. 'NO': 'Norway',
  4477. 'OM': 'Oman',
  4478. 'PK': 'Pakistan',
  4479. 'PW': 'Palau',
  4480. 'PS': 'Palestine, State of',
  4481. 'PA': 'Panama',
  4482. 'PG': 'Papua New Guinea',
  4483. 'PY': 'Paraguay',
  4484. 'PE': 'Peru',
  4485. 'PH': 'Philippines',
  4486. 'PN': 'Pitcairn',
  4487. 'PL': 'Poland',
  4488. 'PT': 'Portugal',
  4489. 'PR': 'Puerto Rico',
  4490. 'QA': 'Qatar',
  4491. 'RE': 'Réunion',
  4492. 'RO': 'Romania',
  4493. 'RU': 'Russian Federation',
  4494. 'RW': 'Rwanda',
  4495. 'BL': 'Saint Barthélemy',
  4496. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  4497. 'KN': 'Saint Kitts and Nevis',
  4498. 'LC': 'Saint Lucia',
  4499. 'MF': 'Saint Martin (French part)',
  4500. 'PM': 'Saint Pierre and Miquelon',
  4501. 'VC': 'Saint Vincent and the Grenadines',
  4502. 'WS': 'Samoa',
  4503. 'SM': 'San Marino',
  4504. 'ST': 'Sao Tome and Principe',
  4505. 'SA': 'Saudi Arabia',
  4506. 'SN': 'Senegal',
  4507. 'RS': 'Serbia',
  4508. 'SC': 'Seychelles',
  4509. 'SL': 'Sierra Leone',
  4510. 'SG': 'Singapore',
  4511. 'SX': 'Sint Maarten (Dutch part)',
  4512. 'SK': 'Slovakia',
  4513. 'SI': 'Slovenia',
  4514. 'SB': 'Solomon Islands',
  4515. 'SO': 'Somalia',
  4516. 'ZA': 'South Africa',
  4517. 'GS': 'South Georgia and the South Sandwich Islands',
  4518. 'SS': 'South Sudan',
  4519. 'ES': 'Spain',
  4520. 'LK': 'Sri Lanka',
  4521. 'SD': 'Sudan',
  4522. 'SR': 'Suriname',
  4523. 'SJ': 'Svalbard and Jan Mayen',
  4524. 'SZ': 'Swaziland',
  4525. 'SE': 'Sweden',
  4526. 'CH': 'Switzerland',
  4527. 'SY': 'Syrian Arab Republic',
  4528. 'TW': 'Taiwan, Province of China',
  4529. 'TJ': 'Tajikistan',
  4530. 'TZ': 'Tanzania, United Republic of',
  4531. 'TH': 'Thailand',
  4532. 'TL': 'Timor-Leste',
  4533. 'TG': 'Togo',
  4534. 'TK': 'Tokelau',
  4535. 'TO': 'Tonga',
  4536. 'TT': 'Trinidad and Tobago',
  4537. 'TN': 'Tunisia',
  4538. 'TR': 'Turkey',
  4539. 'TM': 'Turkmenistan',
  4540. 'TC': 'Turks and Caicos Islands',
  4541. 'TV': 'Tuvalu',
  4542. 'UG': 'Uganda',
  4543. 'UA': 'Ukraine',
  4544. 'AE': 'United Arab Emirates',
  4545. 'GB': 'United Kingdom',
  4546. 'US': 'United States',
  4547. 'UM': 'United States Minor Outlying Islands',
  4548. 'UY': 'Uruguay',
  4549. 'UZ': 'Uzbekistan',
  4550. 'VU': 'Vanuatu',
  4551. 'VE': 'Venezuela, Bolivarian Republic of',
  4552. 'VN': 'Viet Nam',
  4553. 'VG': 'Virgin Islands, British',
  4554. 'VI': 'Virgin Islands, U.S.',
  4555. 'WF': 'Wallis and Futuna',
  4556. 'EH': 'Western Sahara',
  4557. 'YE': 'Yemen',
  4558. 'ZM': 'Zambia',
  4559. 'ZW': 'Zimbabwe',
  4560. }
  4561. @classmethod
  4562. def short2full(cls, code):
  4563. """Convert an ISO 3166-2 country code to the corresponding full name"""
  4564. return cls._country_map.get(code.upper())
  4565. class GeoUtils(object):
  4566. # Major IPv4 address blocks per country
  4567. _country_ip_map = {
  4568. 'AD': '46.172.224.0/19',
  4569. 'AE': '94.200.0.0/13',
  4570. 'AF': '149.54.0.0/17',
  4571. 'AG': '209.59.64.0/18',
  4572. 'AI': '204.14.248.0/21',
  4573. 'AL': '46.99.0.0/16',
  4574. 'AM': '46.70.0.0/15',
  4575. 'AO': '105.168.0.0/13',
  4576. 'AP': '182.50.184.0/21',
  4577. 'AQ': '23.154.160.0/24',
  4578. 'AR': '181.0.0.0/12',
  4579. 'AS': '202.70.112.0/20',
  4580. 'AT': '77.116.0.0/14',
  4581. 'AU': '1.128.0.0/11',
  4582. 'AW': '181.41.0.0/18',
  4583. 'AX': '185.217.4.0/22',
  4584. 'AZ': '5.197.0.0/16',
  4585. 'BA': '31.176.128.0/17',
  4586. 'BB': '65.48.128.0/17',
  4587. 'BD': '114.130.0.0/16',
  4588. 'BE': '57.0.0.0/8',
  4589. 'BF': '102.178.0.0/15',
  4590. 'BG': '95.42.0.0/15',
  4591. 'BH': '37.131.0.0/17',
  4592. 'BI': '154.117.192.0/18',
  4593. 'BJ': '137.255.0.0/16',
  4594. 'BL': '185.212.72.0/23',
  4595. 'BM': '196.12.64.0/18',
  4596. 'BN': '156.31.0.0/16',
  4597. 'BO': '161.56.0.0/16',
  4598. 'BQ': '161.0.80.0/20',
  4599. 'BR': '191.128.0.0/12',
  4600. 'BS': '24.51.64.0/18',
  4601. 'BT': '119.2.96.0/19',
  4602. 'BW': '168.167.0.0/16',
  4603. 'BY': '178.120.0.0/13',
  4604. 'BZ': '179.42.192.0/18',
  4605. 'CA': '99.224.0.0/11',
  4606. 'CD': '41.243.0.0/16',
  4607. 'CF': '197.242.176.0/21',
  4608. 'CG': '160.113.0.0/16',
  4609. 'CH': '85.0.0.0/13',
  4610. 'CI': '102.136.0.0/14',
  4611. 'CK': '202.65.32.0/19',
  4612. 'CL': '152.172.0.0/14',
  4613. 'CM': '102.244.0.0/14',
  4614. 'CN': '36.128.0.0/10',
  4615. 'CO': '181.240.0.0/12',
  4616. 'CR': '201.192.0.0/12',
  4617. 'CU': '152.206.0.0/15',
  4618. 'CV': '165.90.96.0/19',
  4619. 'CW': '190.88.128.0/17',
  4620. 'CY': '31.153.0.0/16',
  4621. 'CZ': '88.100.0.0/14',
  4622. 'DE': '53.0.0.0/8',
  4623. 'DJ': '197.241.0.0/17',
  4624. 'DK': '87.48.0.0/12',
  4625. 'DM': '192.243.48.0/20',
  4626. 'DO': '152.166.0.0/15',
  4627. 'DZ': '41.96.0.0/12',
  4628. 'EC': '186.68.0.0/15',
  4629. 'EE': '90.190.0.0/15',
  4630. 'EG': '156.160.0.0/11',
  4631. 'ER': '196.200.96.0/20',
  4632. 'ES': '88.0.0.0/11',
  4633. 'ET': '196.188.0.0/14',
  4634. 'EU': '2.16.0.0/13',
  4635. 'FI': '91.152.0.0/13',
  4636. 'FJ': '144.120.0.0/16',
  4637. 'FK': '80.73.208.0/21',
  4638. 'FM': '119.252.112.0/20',
  4639. 'FO': '88.85.32.0/19',
  4640. 'FR': '90.0.0.0/9',
  4641. 'GA': '41.158.0.0/15',
  4642. 'GB': '25.0.0.0/8',
  4643. 'GD': '74.122.88.0/21',
  4644. 'GE': '31.146.0.0/16',
  4645. 'GF': '161.22.64.0/18',
  4646. 'GG': '62.68.160.0/19',
  4647. 'GH': '154.160.0.0/12',
  4648. 'GI': '95.164.0.0/16',
  4649. 'GL': '88.83.0.0/19',
  4650. 'GM': '160.182.0.0/15',
  4651. 'GN': '197.149.192.0/18',
  4652. 'GP': '104.250.0.0/19',
  4653. 'GQ': '105.235.224.0/20',
  4654. 'GR': '94.64.0.0/13',
  4655. 'GT': '168.234.0.0/16',
  4656. 'GU': '168.123.0.0/16',
  4657. 'GW': '197.214.80.0/20',
  4658. 'GY': '181.41.64.0/18',
  4659. 'HK': '113.252.0.0/14',
  4660. 'HN': '181.210.0.0/16',
  4661. 'HR': '93.136.0.0/13',
  4662. 'HT': '148.102.128.0/17',
  4663. 'HU': '84.0.0.0/14',
  4664. 'ID': '39.192.0.0/10',
  4665. 'IE': '87.32.0.0/12',
  4666. 'IL': '79.176.0.0/13',
  4667. 'IM': '5.62.80.0/20',
  4668. 'IN': '117.192.0.0/10',
  4669. 'IO': '203.83.48.0/21',
  4670. 'IQ': '37.236.0.0/14',
  4671. 'IR': '2.176.0.0/12',
  4672. 'IS': '82.221.0.0/16',
  4673. 'IT': '79.0.0.0/10',
  4674. 'JE': '87.244.64.0/18',
  4675. 'JM': '72.27.0.0/17',
  4676. 'JO': '176.29.0.0/16',
  4677. 'JP': '133.0.0.0/8',
  4678. 'KE': '105.48.0.0/12',
  4679. 'KG': '158.181.128.0/17',
  4680. 'KH': '36.37.128.0/17',
  4681. 'KI': '103.25.140.0/22',
  4682. 'KM': '197.255.224.0/20',
  4683. 'KN': '198.167.192.0/19',
  4684. 'KP': '175.45.176.0/22',
  4685. 'KR': '175.192.0.0/10',
  4686. 'KW': '37.36.0.0/14',
  4687. 'KY': '64.96.0.0/15',
  4688. 'KZ': '2.72.0.0/13',
  4689. 'LA': '115.84.64.0/18',
  4690. 'LB': '178.135.0.0/16',
  4691. 'LC': '24.92.144.0/20',
  4692. 'LI': '82.117.0.0/19',
  4693. 'LK': '112.134.0.0/15',
  4694. 'LR': '102.183.0.0/16',
  4695. 'LS': '129.232.0.0/17',
  4696. 'LT': '78.56.0.0/13',
  4697. 'LU': '188.42.0.0/16',
  4698. 'LV': '46.109.0.0/16',
  4699. 'LY': '41.252.0.0/14',
  4700. 'MA': '105.128.0.0/11',
  4701. 'MC': '88.209.64.0/18',
  4702. 'MD': '37.246.0.0/16',
  4703. 'ME': '178.175.0.0/17',
  4704. 'MF': '74.112.232.0/21',
  4705. 'MG': '154.126.0.0/17',
  4706. 'MH': '117.103.88.0/21',
  4707. 'MK': '77.28.0.0/15',
  4708. 'ML': '154.118.128.0/18',
  4709. 'MM': '37.111.0.0/17',
  4710. 'MN': '49.0.128.0/17',
  4711. 'MO': '60.246.0.0/16',
  4712. 'MP': '202.88.64.0/20',
  4713. 'MQ': '109.203.224.0/19',
  4714. 'MR': '41.188.64.0/18',
  4715. 'MS': '208.90.112.0/22',
  4716. 'MT': '46.11.0.0/16',
  4717. 'MU': '105.16.0.0/12',
  4718. 'MV': '27.114.128.0/18',
  4719. 'MW': '102.70.0.0/15',
  4720. 'MX': '187.192.0.0/11',
  4721. 'MY': '175.136.0.0/13',
  4722. 'MZ': '197.218.0.0/15',
  4723. 'NA': '41.182.0.0/16',
  4724. 'NC': '101.101.0.0/18',
  4725. 'NE': '197.214.0.0/18',
  4726. 'NF': '203.17.240.0/22',
  4727. 'NG': '105.112.0.0/12',
  4728. 'NI': '186.76.0.0/15',
  4729. 'NL': '145.96.0.0/11',
  4730. 'NO': '84.208.0.0/13',
  4731. 'NP': '36.252.0.0/15',
  4732. 'NR': '203.98.224.0/19',
  4733. 'NU': '49.156.48.0/22',
  4734. 'NZ': '49.224.0.0/14',
  4735. 'OM': '5.36.0.0/15',
  4736. 'PA': '186.72.0.0/15',
  4737. 'PE': '186.160.0.0/14',
  4738. 'PF': '123.50.64.0/18',
  4739. 'PG': '124.240.192.0/19',
  4740. 'PH': '49.144.0.0/13',
  4741. 'PK': '39.32.0.0/11',
  4742. 'PL': '83.0.0.0/11',
  4743. 'PM': '70.36.0.0/20',
  4744. 'PR': '66.50.0.0/16',
  4745. 'PS': '188.161.0.0/16',
  4746. 'PT': '85.240.0.0/13',
  4747. 'PW': '202.124.224.0/20',
  4748. 'PY': '181.120.0.0/14',
  4749. 'QA': '37.210.0.0/15',
  4750. 'RE': '102.35.0.0/16',
  4751. 'RO': '79.112.0.0/13',
  4752. 'RS': '93.86.0.0/15',
  4753. 'RU': '5.136.0.0/13',
  4754. 'RW': '41.186.0.0/16',
  4755. 'SA': '188.48.0.0/13',
  4756. 'SB': '202.1.160.0/19',
  4757. 'SC': '154.192.0.0/11',
  4758. 'SD': '102.120.0.0/13',
  4759. 'SE': '78.64.0.0/12',
  4760. 'SG': '8.128.0.0/10',
  4761. 'SI': '188.196.0.0/14',
  4762. 'SK': '78.98.0.0/15',
  4763. 'SL': '102.143.0.0/17',
  4764. 'SM': '89.186.32.0/19',
  4765. 'SN': '41.82.0.0/15',
  4766. 'SO': '154.115.192.0/18',
  4767. 'SR': '186.179.128.0/17',
  4768. 'SS': '105.235.208.0/21',
  4769. 'ST': '197.159.160.0/19',
  4770. 'SV': '168.243.0.0/16',
  4771. 'SX': '190.102.0.0/20',
  4772. 'SY': '5.0.0.0/16',
  4773. 'SZ': '41.84.224.0/19',
  4774. 'TC': '65.255.48.0/20',
  4775. 'TD': '154.68.128.0/19',
  4776. 'TG': '196.168.0.0/14',
  4777. 'TH': '171.96.0.0/13',
  4778. 'TJ': '85.9.128.0/18',
  4779. 'TK': '27.96.24.0/21',
  4780. 'TL': '180.189.160.0/20',
  4781. 'TM': '95.85.96.0/19',
  4782. 'TN': '197.0.0.0/11',
  4783. 'TO': '175.176.144.0/21',
  4784. 'TR': '78.160.0.0/11',
  4785. 'TT': '186.44.0.0/15',
  4786. 'TV': '202.2.96.0/19',
  4787. 'TW': '120.96.0.0/11',
  4788. 'TZ': '156.156.0.0/14',
  4789. 'UA': '37.52.0.0/14',
  4790. 'UG': '102.80.0.0/13',
  4791. 'US': '6.0.0.0/8',
  4792. 'UY': '167.56.0.0/13',
  4793. 'UZ': '84.54.64.0/18',
  4794. 'VA': '212.77.0.0/19',
  4795. 'VC': '207.191.240.0/21',
  4796. 'VE': '186.88.0.0/13',
  4797. 'VG': '66.81.192.0/20',
  4798. 'VI': '146.226.0.0/16',
  4799. 'VN': '14.160.0.0/11',
  4800. 'VU': '202.80.32.0/20',
  4801. 'WF': '117.20.32.0/21',
  4802. 'WS': '202.4.32.0/19',
  4803. 'YE': '134.35.0.0/16',
  4804. 'YT': '41.242.116.0/22',
  4805. 'ZA': '41.0.0.0/11',
  4806. 'ZM': '102.144.0.0/13',
  4807. 'ZW': '102.177.192.0/18',
  4808. }
  4809. @classmethod
  4810. def random_ipv4(cls, code_or_block):
  4811. if len(code_or_block) == 2:
  4812. block = cls._country_ip_map.get(code_or_block.upper())
  4813. if not block:
  4814. return None
  4815. else:
  4816. block = code_or_block
  4817. addr, preflen = block.split('/')
  4818. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  4819. addr_max = addr_min | (0xffffffff >> int(preflen))
  4820. return compat_str(socket.inet_ntoa(
  4821. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  4822. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  4823. def __init__(self, proxies=None):
  4824. # Set default handlers
  4825. for type in ('http', 'https'):
  4826. setattr(self, '%s_open' % type,
  4827. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  4828. meth(r, proxy, type))
  4829. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  4830. def proxy_open(self, req, proxy, type):
  4831. req_proxy = req.headers.get('Ytdl-request-proxy')
  4832. if req_proxy is not None:
  4833. proxy = req_proxy
  4834. del req.headers['Ytdl-request-proxy']
  4835. if proxy == '__noproxy__':
  4836. return None # No Proxy
  4837. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  4838. req.add_header('Ytdl-socks-proxy', proxy)
  4839. # youtube-dl's http/https handlers do wrapping the socket with socks
  4840. return None
  4841. return compat_urllib_request.ProxyHandler.proxy_open(
  4842. self, req, proxy, type)
  4843. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  4844. # released into Public Domain
  4845. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  4846. def long_to_bytes(n, blocksize=0):
  4847. """long_to_bytes(n:long, blocksize:int) : string
  4848. Convert a long integer to a byte string.
  4849. If optional blocksize is given and greater than zero, pad the front of the
  4850. byte string with binary zeros so that the length is a multiple of
  4851. blocksize.
  4852. """
  4853. # after much testing, this algorithm was deemed to be the fastest
  4854. s = b''
  4855. n = int(n)
  4856. while n > 0:
  4857. s = compat_struct_pack('>I', n & 0xffffffff) + s
  4858. n = n >> 32
  4859. # strip off leading zeros
  4860. for i in range(len(s)):
  4861. if s[i] != b'\000'[0]:
  4862. break
  4863. else:
  4864. # only happens when n == 0
  4865. s = b'\000'
  4866. i = 0
  4867. s = s[i:]
  4868. # add back some pad bytes. this could be done more efficiently w.r.t. the
  4869. # de-padding being done above, but sigh...
  4870. if blocksize > 0 and len(s) % blocksize:
  4871. s = (blocksize - len(s) % blocksize) * b'\000' + s
  4872. return s
  4873. def bytes_to_long(s):
  4874. """bytes_to_long(string) : long
  4875. Convert a byte string to a long integer.
  4876. This is (essentially) the inverse of long_to_bytes().
  4877. """
  4878. acc = 0
  4879. length = len(s)
  4880. if length % 4:
  4881. extra = (4 - length % 4)
  4882. s = b'\000' * extra + s
  4883. length = length + extra
  4884. for i in range(0, length, 4):
  4885. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  4886. return acc
  4887. def ohdave_rsa_encrypt(data, exponent, modulus):
  4888. '''
  4889. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  4890. Input:
  4891. data: data to encrypt, bytes-like object
  4892. exponent, modulus: parameter e and N of RSA algorithm, both integer
  4893. Output: hex string of encrypted data
  4894. Limitation: supports one block encryption only
  4895. '''
  4896. payload = int(binascii.hexlify(data[::-1]), 16)
  4897. encrypted = pow(payload, exponent, modulus)
  4898. return '%x' % encrypted
  4899. def pkcs1pad(data, length):
  4900. """
  4901. Padding input data with PKCS#1 scheme
  4902. @param {int[]} data input data
  4903. @param {int} length target length
  4904. @returns {int[]} padded data
  4905. """
  4906. if len(data) > length - 11:
  4907. raise ValueError('Input data too long for PKCS#1 padding')
  4908. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  4909. return [0, 2] + pseudo_random + [0] + data
  4910. def encode_base_n(num, n, table=None):
  4911. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4912. if not table:
  4913. table = FULL_TABLE[:n]
  4914. if n > len(table):
  4915. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  4916. if num == 0:
  4917. return table[0]
  4918. ret = ''
  4919. while num:
  4920. ret = table[num % n] + ret
  4921. num = num // n
  4922. return ret
  4923. def decode_packed_codes(code):
  4924. mobj = re.search(PACKED_CODES_RE, code)
  4925. obfuscated_code, base, count, symbols = mobj.groups()
  4926. base = int(base)
  4927. count = int(count)
  4928. symbols = symbols.split('|')
  4929. symbol_table = {}
  4930. while count:
  4931. count -= 1
  4932. base_n_count = encode_base_n(count, base)
  4933. symbol_table[base_n_count] = symbols[count] or base_n_count
  4934. return re.sub(
  4935. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  4936. obfuscated_code)
  4937. def caesar(s, alphabet, shift):
  4938. if shift == 0:
  4939. return s
  4940. l = len(alphabet)
  4941. return ''.join(
  4942. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  4943. for c in s)
  4944. def rot47(s):
  4945. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  4946. def parse_m3u8_attributes(attrib):
  4947. info = {}
  4948. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  4949. if val.startswith('"'):
  4950. val = val[1:-1]
  4951. info[key] = val
  4952. return info
  4953. def urshift(val, n):
  4954. return val >> n if val >= 0 else (val + 0x100000000) >> n
  4955. # Based on png2str() written by @gdkchan and improved by @yokrysty
  4956. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  4957. def decode_png(png_data):
  4958. # Reference: https://www.w3.org/TR/PNG/
  4959. header = png_data[8:]
  4960. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  4961. raise IOError('Not a valid PNG file.')
  4962. int_map = {1: '>B', 2: '>H', 4: '>I'}
  4963. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  4964. chunks = []
  4965. while header:
  4966. length = unpack_integer(header[:4])
  4967. header = header[4:]
  4968. chunk_type = header[:4]
  4969. header = header[4:]
  4970. chunk_data = header[:length]
  4971. header = header[length:]
  4972. header = header[4:] # Skip CRC
  4973. chunks.append({
  4974. 'type': chunk_type,
  4975. 'length': length,
  4976. 'data': chunk_data
  4977. })
  4978. ihdr = chunks[0]['data']
  4979. width = unpack_integer(ihdr[:4])
  4980. height = unpack_integer(ihdr[4:8])
  4981. idat = b''
  4982. for chunk in chunks:
  4983. if chunk['type'] == b'IDAT':
  4984. idat += chunk['data']
  4985. if not idat:
  4986. raise IOError('Unable to read PNG data.')
  4987. decompressed_data = bytearray(zlib.decompress(idat))
  4988. stride = width * 3
  4989. pixels = []
  4990. def _get_pixel(idx):
  4991. x = idx % stride
  4992. y = idx // stride
  4993. return pixels[y][x]
  4994. for y in range(height):
  4995. basePos = y * (1 + stride)
  4996. filter_type = decompressed_data[basePos]
  4997. current_row = []
  4998. pixels.append(current_row)
  4999. for x in range(stride):
  5000. color = decompressed_data[1 + basePos + x]
  5001. basex = y * stride + x
  5002. left = 0
  5003. up = 0
  5004. if x > 2:
  5005. left = _get_pixel(basex - 3)
  5006. if y > 0:
  5007. up = _get_pixel(basex - stride)
  5008. if filter_type == 1: # Sub
  5009. color = (color + left) & 0xff
  5010. elif filter_type == 2: # Up
  5011. color = (color + up) & 0xff
  5012. elif filter_type == 3: # Average
  5013. color = (color + ((left + up) >> 1)) & 0xff
  5014. elif filter_type == 4: # Paeth
  5015. a = left
  5016. b = up
  5017. c = 0
  5018. if x > 2 and y > 0:
  5019. c = _get_pixel(basex - stride - 3)
  5020. p = a + b - c
  5021. pa = abs(p - a)
  5022. pb = abs(p - b)
  5023. pc = abs(p - c)
  5024. if pa <= pb and pa <= pc:
  5025. color = (color + a) & 0xff
  5026. elif pb <= pc:
  5027. color = (color + b) & 0xff
  5028. else:
  5029. color = (color + c) & 0xff
  5030. current_row.append(color)
  5031. return width, height, pixels
  5032. def write_xattr(path, key, value):
  5033. # This mess below finds the best xattr tool for the job
  5034. try:
  5035. # try the pyxattr module...
  5036. import xattr
  5037. if hasattr(xattr, 'set'): # pyxattr
  5038. # Unicode arguments are not supported in python-pyxattr until
  5039. # version 0.5.0
  5040. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  5041. pyxattr_required_version = '0.5.0'
  5042. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  5043. # TODO: fallback to CLI tools
  5044. raise XAttrUnavailableError(
  5045. 'python-pyxattr is detected but is too old. '
  5046. 'youtube-dl requires %s or above while your version is %s. '
  5047. 'Falling back to other xattr implementations' % (
  5048. pyxattr_required_version, xattr.__version__))
  5049. setxattr = xattr.set
  5050. else: # xattr
  5051. setxattr = xattr.setxattr
  5052. try:
  5053. setxattr(path, key, value)
  5054. except EnvironmentError as e:
  5055. raise XAttrMetadataError(e.errno, e.strerror)
  5056. except ImportError:
  5057. if compat_os_name == 'nt':
  5058. # Write xattrs to NTFS Alternate Data Streams:
  5059. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  5060. assert ':' not in key
  5061. assert os.path.exists(path)
  5062. ads_fn = path + ':' + key
  5063. try:
  5064. with open(ads_fn, 'wb') as f:
  5065. f.write(value)
  5066. except EnvironmentError as e:
  5067. raise XAttrMetadataError(e.errno, e.strerror)
  5068. else:
  5069. user_has_setfattr = check_executable('setfattr', ['--version'])
  5070. user_has_xattr = check_executable('xattr', ['-h'])
  5071. if user_has_setfattr or user_has_xattr:
  5072. value = value.decode('utf-8')
  5073. if user_has_setfattr:
  5074. executable = 'setfattr'
  5075. opts = ['-n', key, '-v', value]
  5076. elif user_has_xattr:
  5077. executable = 'xattr'
  5078. opts = ['-w', key, value]
  5079. cmd = ([encodeFilename(executable, True)]
  5080. + [encodeArgument(o) for o in opts]
  5081. + [encodeFilename(path, True)])
  5082. try:
  5083. p = subprocess.Popen(
  5084. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  5085. except EnvironmentError as e:
  5086. raise XAttrMetadataError(e.errno, e.strerror)
  5087. stdout, stderr = p.communicate()
  5088. stderr = stderr.decode('utf-8', 'replace')
  5089. if p.returncode != 0:
  5090. raise XAttrMetadataError(p.returncode, stderr)
  5091. else:
  5092. # On Unix, and can't find pyxattr, setfattr, or xattr.
  5093. if sys.platform.startswith('linux'):
  5094. raise XAttrUnavailableError(
  5095. "Couldn't find a tool to set the xattrs. "
  5096. "Install either the python 'pyxattr' or 'xattr' "
  5097. "modules, or the GNU 'attr' package "
  5098. "(which contains the 'setfattr' tool).")
  5099. else:
  5100. raise XAttrUnavailableError(
  5101. "Couldn't find a tool to set the xattrs. "
  5102. "Install either the python 'xattr' module, "
  5103. "or the 'xattr' binary.")
  5104. def random_birthday(year_field, month_field, day_field):
  5105. start_date = datetime.date(1950, 1, 1)
  5106. end_date = datetime.date(1995, 12, 31)
  5107. offset = random.randint(0, (end_date - start_date).days)
  5108. random_date = start_date + datetime.timedelta(offset)
  5109. return {
  5110. year_field: str(random_date.year),
  5111. month_field: str(random_date.month),
  5112. day_field: str(random_date.day),
  5113. }
  5114. def clean_podcast_url(url):
  5115. return re.sub(r'''(?x)
  5116. (?:
  5117. (?:
  5118. chtbl\.com/track|
  5119. media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
  5120. play\.podtrac\.com
  5121. )/[^/]+|
  5122. (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
  5123. flex\.acast\.com|
  5124. pd(?:
  5125. cn\.co| # https://podcorn.com/analytics-prefix/
  5126. st\.fm # https://podsights.com/docs/
  5127. )/e
  5128. )/''', '', url)