utils.py 168 KB

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