utils.py 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014
  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 contextlib
  9. import ctypes
  10. import datetime
  11. import email.utils
  12. import email.header
  13. import errno
  14. import functools
  15. import gzip
  16. import io
  17. import itertools
  18. import json
  19. import locale
  20. import math
  21. import operator
  22. import os
  23. import platform
  24. import random
  25. import re
  26. import socket
  27. import ssl
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import traceback
  32. import xml.etree.ElementTree
  33. import zlib
  34. from .compat import (
  35. compat_HTMLParseError,
  36. compat_HTMLParser,
  37. compat_basestring,
  38. compat_chr,
  39. compat_cookiejar,
  40. compat_ctypes_WINFUNCTYPE,
  41. compat_etree_fromstring,
  42. compat_expanduser,
  43. compat_html_entities,
  44. compat_html_entities_html5,
  45. compat_http_client,
  46. compat_kwargs,
  47. compat_os_name,
  48. compat_parse_qs,
  49. compat_shlex_quote,
  50. compat_str,
  51. compat_struct_pack,
  52. compat_struct_unpack,
  53. compat_urllib_error,
  54. compat_urllib_parse,
  55. compat_urllib_parse_urlencode,
  56. compat_urllib_parse_urlparse,
  57. compat_urllib_parse_unquote_plus,
  58. compat_urllib_request,
  59. compat_urlparse,
  60. compat_xpath,
  61. )
  62. from .socks import (
  63. ProxyType,
  64. sockssocket,
  65. )
  66. def register_socks_protocols():
  67. # "Register" SOCKS protocols
  68. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  69. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  70. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  71. if scheme not in compat_urlparse.uses_netloc:
  72. compat_urlparse.uses_netloc.append(scheme)
  73. # This is not clearly defined otherwise
  74. compiled_regex_type = type(re.compile(''))
  75. std_headers = {
  76. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0',
  77. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  78. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  79. 'Accept-Encoding': 'gzip, deflate',
  80. 'Accept-Language': 'en-us,en;q=0.5',
  81. }
  82. USER_AGENTS = {
  83. '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',
  84. }
  85. NO_DEFAULT = object()
  86. ENGLISH_MONTH_NAMES = [
  87. 'January', 'February', 'March', 'April', 'May', 'June',
  88. 'July', 'August', 'September', 'October', 'November', 'December']
  89. MONTH_NAMES = {
  90. 'en': ENGLISH_MONTH_NAMES,
  91. 'fr': [
  92. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  93. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  94. }
  95. KNOWN_EXTENSIONS = (
  96. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  97. 'flv', 'f4v', 'f4a', 'f4b',
  98. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  99. 'mkv', 'mka', 'mk3d',
  100. 'avi', 'divx',
  101. 'mov',
  102. 'asf', 'wmv', 'wma',
  103. '3gp', '3g2',
  104. 'mp3',
  105. 'flac',
  106. 'ape',
  107. 'wav',
  108. 'f4f', 'f4m', 'm3u8', 'smil')
  109. # needed for sanitizing filenames in restricted mode
  110. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  111. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUYP', ['ss'],
  112. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuypy')))
  113. DATE_FORMATS = (
  114. '%d %B %Y',
  115. '%d %b %Y',
  116. '%B %d %Y',
  117. '%B %dst %Y',
  118. '%B %dnd %Y',
  119. '%B %dth %Y',
  120. '%b %d %Y',
  121. '%b %dst %Y',
  122. '%b %dnd %Y',
  123. '%b %dth %Y',
  124. '%b %dst %Y %I:%M',
  125. '%b %dnd %Y %I:%M',
  126. '%b %dth %Y %I:%M',
  127. '%Y %m %d',
  128. '%Y-%m-%d',
  129. '%Y/%m/%d',
  130. '%Y/%m/%d %H:%M',
  131. '%Y/%m/%d %H:%M:%S',
  132. '%Y-%m-%d %H:%M',
  133. '%Y-%m-%d %H:%M:%S',
  134. '%Y-%m-%d %H:%M:%S.%f',
  135. '%d.%m.%Y %H:%M',
  136. '%d.%m.%Y %H.%M',
  137. '%Y-%m-%dT%H:%M:%SZ',
  138. '%Y-%m-%dT%H:%M:%S.%fZ',
  139. '%Y-%m-%dT%H:%M:%S.%f0Z',
  140. '%Y-%m-%dT%H:%M:%S',
  141. '%Y-%m-%dT%H:%M:%S.%f',
  142. '%Y-%m-%dT%H:%M',
  143. '%b %d %Y at %H:%M',
  144. '%b %d %Y at %H:%M:%S',
  145. '%B %d %Y at %H:%M',
  146. '%B %d %Y at %H:%M:%S',
  147. )
  148. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  149. DATE_FORMATS_DAY_FIRST.extend([
  150. '%d-%m-%Y',
  151. '%d.%m.%Y',
  152. '%d.%m.%y',
  153. '%d/%m/%Y',
  154. '%d/%m/%y',
  155. '%d/%m/%Y %H:%M:%S',
  156. ])
  157. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  158. DATE_FORMATS_MONTH_FIRST.extend([
  159. '%m-%d-%Y',
  160. '%m.%d.%Y',
  161. '%m/%d/%Y',
  162. '%m/%d/%y',
  163. '%m/%d/%Y %H:%M:%S',
  164. ])
  165. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  166. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
  167. def preferredencoding():
  168. """Get preferred encoding.
  169. Returns the best encoding scheme for the system, based on
  170. locale.getpreferredencoding() and some further tweaks.
  171. """
  172. try:
  173. pref = locale.getpreferredencoding()
  174. 'TEST'.encode(pref)
  175. except Exception:
  176. pref = 'UTF-8'
  177. return pref
  178. def write_json_file(obj, fn):
  179. """ Encode obj as JSON and write it to fn, atomically if possible """
  180. fn = encodeFilename(fn)
  181. if sys.version_info < (3, 0) and sys.platform != 'win32':
  182. encoding = get_filesystem_encoding()
  183. # os.path.basename returns a bytes object, but NamedTemporaryFile
  184. # will fail if the filename contains non ascii characters unless we
  185. # use a unicode object
  186. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  187. # the same for os.path.dirname
  188. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  189. else:
  190. path_basename = os.path.basename
  191. path_dirname = os.path.dirname
  192. args = {
  193. 'suffix': '.tmp',
  194. 'prefix': path_basename(fn) + '.',
  195. 'dir': path_dirname(fn),
  196. 'delete': False,
  197. }
  198. # In Python 2.x, json.dump expects a bytestream.
  199. # In Python 3.x, it writes to a character stream
  200. if sys.version_info < (3, 0):
  201. args['mode'] = 'wb'
  202. else:
  203. args.update({
  204. 'mode': 'w',
  205. 'encoding': 'utf-8',
  206. })
  207. tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
  208. try:
  209. with tf:
  210. json.dump(obj, tf)
  211. if sys.platform == 'win32':
  212. # Need to remove existing file on Windows, else os.rename raises
  213. # WindowsError or FileExistsError.
  214. try:
  215. os.unlink(fn)
  216. except OSError:
  217. pass
  218. os.rename(tf.name, fn)
  219. except Exception:
  220. try:
  221. os.remove(tf.name)
  222. except OSError:
  223. pass
  224. raise
  225. if sys.version_info >= (2, 7):
  226. def find_xpath_attr(node, xpath, key, val=None):
  227. """ Find the xpath xpath[@key=val] """
  228. assert re.match(r'^[a-zA-Z_-]+$', key)
  229. expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
  230. return node.find(expr)
  231. else:
  232. def find_xpath_attr(node, xpath, key, val=None):
  233. for f in node.findall(compat_xpath(xpath)):
  234. if key not in f.attrib:
  235. continue
  236. if val is None or f.attrib.get(key) == val:
  237. return f
  238. return None
  239. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  240. # the namespace parameter
  241. def xpath_with_ns(path, ns_map):
  242. components = [c.split(':') for c in path.split('/')]
  243. replaced = []
  244. for c in components:
  245. if len(c) == 1:
  246. replaced.append(c[0])
  247. else:
  248. ns, tag = c
  249. replaced.append('{%s}%s' % (ns_map[ns], tag))
  250. return '/'.join(replaced)
  251. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  252. def _find_xpath(xpath):
  253. return node.find(compat_xpath(xpath))
  254. if isinstance(xpath, (str, compat_str)):
  255. n = _find_xpath(xpath)
  256. else:
  257. for xp in xpath:
  258. n = _find_xpath(xp)
  259. if n is not None:
  260. break
  261. if n is None:
  262. if default is not NO_DEFAULT:
  263. return default
  264. elif fatal:
  265. name = xpath if name is None else name
  266. raise ExtractorError('Could not find XML element %s' % name)
  267. else:
  268. return None
  269. return n
  270. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  271. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  272. if n is None or n == default:
  273. return n
  274. if n.text is None:
  275. if default is not NO_DEFAULT:
  276. return default
  277. elif fatal:
  278. name = xpath if name is None else name
  279. raise ExtractorError('Could not find XML element\'s text %s' % name)
  280. else:
  281. return None
  282. return n.text
  283. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  284. n = find_xpath_attr(node, xpath, key)
  285. if n is None:
  286. if default is not NO_DEFAULT:
  287. return default
  288. elif fatal:
  289. name = '%s[@%s]' % (xpath, key) if name is None else name
  290. raise ExtractorError('Could not find XML attribute %s' % name)
  291. else:
  292. return None
  293. return n.attrib[key]
  294. def get_element_by_id(id, html):
  295. """Return the content of the tag with the specified ID in the passed HTML document"""
  296. return get_element_by_attribute('id', id, html)
  297. def get_element_by_class(class_name, html):
  298. """Return the content of the first tag with the specified class in the passed HTML document"""
  299. retval = get_elements_by_class(class_name, html)
  300. return retval[0] if retval else None
  301. def get_element_by_attribute(attribute, value, html, escape_value=True):
  302. retval = get_elements_by_attribute(attribute, value, html, escape_value)
  303. return retval[0] if retval else None
  304. def get_elements_by_class(class_name, html):
  305. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  306. return get_elements_by_attribute(
  307. 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
  308. html, escape_value=False)
  309. def get_elements_by_attribute(attribute, value, html, escape_value=True):
  310. """Return the content of the tag with the specified attribute in the passed HTML document"""
  311. value = re.escape(value) if escape_value else value
  312. retlist = []
  313. for m in re.finditer(r'''(?xs)
  314. <([a-zA-Z0-9:._-]+)
  315. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  316. \s+%s=['"]?%s['"]?
  317. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*?
  318. \s*>
  319. (?P<content>.*?)
  320. </\1>
  321. ''' % (re.escape(attribute), value), html):
  322. res = m.group('content')
  323. if res.startswith('"') or res.startswith("'"):
  324. res = res[1:-1]
  325. retlist.append(unescapeHTML(res))
  326. return retlist
  327. class HTMLAttributeParser(compat_HTMLParser):
  328. """Trivial HTML parser to gather the attributes for a single element"""
  329. def __init__(self):
  330. self.attrs = {}
  331. compat_HTMLParser.__init__(self)
  332. def handle_starttag(self, tag, attrs):
  333. self.attrs = dict(attrs)
  334. def extract_attributes(html_element):
  335. """Given a string for an HTML element such as
  336. <el
  337. a="foo" B="bar" c="&98;az" d=boz
  338. empty= noval entity="&amp;"
  339. sq='"' dq="'"
  340. >
  341. Decode and return a dictionary of attributes.
  342. {
  343. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  344. 'empty': '', 'noval': None, 'entity': '&',
  345. 'sq': '"', 'dq': '\''
  346. }.
  347. NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
  348. but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
  349. """
  350. parser = HTMLAttributeParser()
  351. try:
  352. parser.feed(html_element)
  353. parser.close()
  354. # Older Python may throw HTMLParseError in case of malformed HTML
  355. except compat_HTMLParseError:
  356. pass
  357. return parser.attrs
  358. def clean_html(html):
  359. """Clean an HTML snippet into a readable string"""
  360. if html is None: # Convenience for sanitizing descriptions etc.
  361. return html
  362. # Newline vs <br />
  363. html = html.replace('\n', ' ')
  364. html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
  365. html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  366. # Strip html tags
  367. html = re.sub('<.*?>', '', html)
  368. # Replace html entities
  369. html = unescapeHTML(html)
  370. return html.strip()
  371. def sanitize_open(filename, open_mode):
  372. """Try to open the given filename, and slightly tweak it if this fails.
  373. Attempts to open the given filename. If this fails, it tries to change
  374. the filename slightly, step by step, until it's either able to open it
  375. or it fails and raises a final exception, like the standard open()
  376. function.
  377. It returns the tuple (stream, definitive_file_name).
  378. """
  379. try:
  380. if filename == '-':
  381. if sys.platform == 'win32':
  382. import msvcrt
  383. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  384. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  385. stream = open(encodeFilename(filename), open_mode)
  386. return (stream, filename)
  387. except (IOError, OSError) as err:
  388. if err.errno in (errno.EACCES,):
  389. raise
  390. # In case of error, try to remove win32 forbidden chars
  391. alt_filename = sanitize_path(filename)
  392. if alt_filename == filename:
  393. raise
  394. else:
  395. # An exception here should be caught in the caller
  396. stream = open(encodeFilename(alt_filename), open_mode)
  397. return (stream, alt_filename)
  398. def timeconvert(timestr):
  399. """Convert RFC 2822 defined time string into system timestamp"""
  400. timestamp = None
  401. timetuple = email.utils.parsedate_tz(timestr)
  402. if timetuple is not None:
  403. timestamp = email.utils.mktime_tz(timetuple)
  404. return timestamp
  405. def sanitize_filename(s, restricted=False, is_id=False):
  406. """Sanitizes a string so it could be used as part of a filename.
  407. If restricted is set, use a stricter subset of allowed characters.
  408. Set is_id if this is not an arbitrary string, but an ID that should be kept
  409. if possible.
  410. """
  411. def replace_insane(char):
  412. if restricted and char in ACCENT_CHARS:
  413. return ACCENT_CHARS[char]
  414. if char == '?' or ord(char) < 32 or ord(char) == 127:
  415. return ''
  416. elif char == '"':
  417. return '' if restricted else '\''
  418. elif char == ':':
  419. return '_-' if restricted else ' -'
  420. elif char in '\\/|*<>':
  421. return '_'
  422. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  423. return '_'
  424. if restricted and ord(char) > 127:
  425. return '_'
  426. return char
  427. # Handle timestamps
  428. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  429. result = ''.join(map(replace_insane, s))
  430. if not is_id:
  431. while '__' in result:
  432. result = result.replace('__', '_')
  433. result = result.strip('_')
  434. # Common case of "Foreign band name - English song title"
  435. if restricted and result.startswith('-_'):
  436. result = result[2:]
  437. if result.startswith('-'):
  438. result = '_' + result[len('-'):]
  439. result = result.lstrip('.')
  440. if not result:
  441. result = '_'
  442. return result
  443. def sanitize_path(s):
  444. """Sanitizes and normalizes path on Windows"""
  445. if sys.platform != 'win32':
  446. return s
  447. drive_or_unc, _ = os.path.splitdrive(s)
  448. if sys.version_info < (2, 7) and not drive_or_unc:
  449. drive_or_unc, _ = os.path.splitunc(s)
  450. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  451. if drive_or_unc:
  452. norm_path.pop(0)
  453. sanitized_path = [
  454. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  455. for path_part in norm_path]
  456. if drive_or_unc:
  457. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  458. return os.path.join(*sanitized_path)
  459. def sanitize_url(url):
  460. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  461. # the number of unwanted failures due to missing protocol
  462. if url.startswith('//'):
  463. return 'http:%s' % url
  464. # Fix some common typos seen so far
  465. COMMON_TYPOS = (
  466. # https://github.com/ytdl-org/youtube-dl/issues/15649
  467. (r'^httpss://', r'https://'),
  468. # https://bx1.be/lives/direct-tv/
  469. (r'^rmtp([es]?)://', r'rtmp\1://'),
  470. )
  471. for mistake, fixup in COMMON_TYPOS:
  472. if re.match(mistake, url):
  473. return re.sub(mistake, fixup, url)
  474. return url
  475. def sanitized_Request(url, *args, **kwargs):
  476. return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
  477. def expand_path(s):
  478. """Expand shell variables and ~"""
  479. return os.path.expandvars(compat_expanduser(s))
  480. def orderedSet(iterable):
  481. """ Remove all duplicates from the input iterable """
  482. res = []
  483. for el in iterable:
  484. if el not in res:
  485. res.append(el)
  486. return res
  487. def _htmlentity_transform(entity_with_semicolon):
  488. """Transforms an HTML entity to a character."""
  489. entity = entity_with_semicolon[:-1]
  490. # Known non-numeric HTML entity
  491. if entity in compat_html_entities.name2codepoint:
  492. return compat_chr(compat_html_entities.name2codepoint[entity])
  493. # TODO: HTML5 allows entities without a semicolon. For example,
  494. # '&Eacuteric' should be decoded as 'Éric'.
  495. if entity_with_semicolon in compat_html_entities_html5:
  496. return compat_html_entities_html5[entity_with_semicolon]
  497. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  498. if mobj is not None:
  499. numstr = mobj.group(1)
  500. if numstr.startswith('x'):
  501. base = 16
  502. numstr = '0%s' % numstr
  503. else:
  504. base = 10
  505. # See https://github.com/ytdl-org/youtube-dl/issues/7518
  506. try:
  507. return compat_chr(int(numstr, base))
  508. except ValueError:
  509. pass
  510. # Unknown entity in name, return its literal representation
  511. return '&%s;' % entity
  512. def unescapeHTML(s):
  513. if s is None:
  514. return None
  515. assert type(s) == compat_str
  516. return re.sub(
  517. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  518. def get_subprocess_encoding():
  519. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  520. # For subprocess calls, encode with locale encoding
  521. # Refer to http://stackoverflow.com/a/9951851/35070
  522. encoding = preferredencoding()
  523. else:
  524. encoding = sys.getfilesystemencoding()
  525. if encoding is None:
  526. encoding = 'utf-8'
  527. return encoding
  528. def encodeFilename(s, for_subprocess=False):
  529. """
  530. @param s The name of the file
  531. """
  532. assert type(s) == compat_str
  533. # Python 3 has a Unicode API
  534. if sys.version_info >= (3, 0):
  535. return s
  536. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  537. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  538. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  539. if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  540. return s
  541. # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
  542. if sys.platform.startswith('java'):
  543. return s
  544. return s.encode(get_subprocess_encoding(), 'ignore')
  545. def decodeFilename(b, for_subprocess=False):
  546. if sys.version_info >= (3, 0):
  547. return b
  548. if not isinstance(b, bytes):
  549. return b
  550. return b.decode(get_subprocess_encoding(), 'ignore')
  551. def encodeArgument(s):
  552. if not isinstance(s, compat_str):
  553. # Legacy code that uses byte strings
  554. # Uncomment the following line after fixing all post processors
  555. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  556. s = s.decode('ascii')
  557. return encodeFilename(s, True)
  558. def decodeArgument(b):
  559. return decodeFilename(b, True)
  560. def decodeOption(optval):
  561. if optval is None:
  562. return optval
  563. if isinstance(optval, bytes):
  564. optval = optval.decode(preferredencoding())
  565. assert isinstance(optval, compat_str)
  566. return optval
  567. def formatSeconds(secs):
  568. if secs > 3600:
  569. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  570. elif secs > 60:
  571. return '%d:%02d' % (secs // 60, secs % 60)
  572. else:
  573. return '%d' % secs
  574. def make_HTTPS_handler(params, **kwargs):
  575. opts_no_check_certificate = params.get('nocheckcertificate', False)
  576. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  577. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  578. if opts_no_check_certificate:
  579. context.check_hostname = False
  580. context.verify_mode = ssl.CERT_NONE
  581. try:
  582. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  583. except TypeError:
  584. # Python 2.7.8
  585. # (create_default_context present but HTTPSHandler has no context=)
  586. pass
  587. if sys.version_info < (3, 2):
  588. return YoutubeDLHTTPSHandler(params, **kwargs)
  589. else: # Python < 3.4
  590. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  591. context.verify_mode = (ssl.CERT_NONE
  592. if opts_no_check_certificate
  593. else ssl.CERT_REQUIRED)
  594. context.set_default_verify_paths()
  595. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  596. def bug_reports_message():
  597. if ytdl_is_updateable():
  598. update_cmd = 'type youtube-dl -U to update'
  599. else:
  600. update_cmd = 'see https://yt-dl.org/update on how to update'
  601. msg = '; please report this issue on https://yt-dl.org/bug .'
  602. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  603. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  604. return msg
  605. class YoutubeDLError(Exception):
  606. """Base exception for YoutubeDL errors."""
  607. pass
  608. class ExtractorError(YoutubeDLError):
  609. """Error during info extraction."""
  610. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  611. """ tb, if given, is the original traceback (so that it can be printed out).
  612. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  613. """
  614. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  615. expected = True
  616. if video_id is not None:
  617. msg = video_id + ': ' + msg
  618. if cause:
  619. msg += ' (caused by %r)' % cause
  620. if not expected:
  621. msg += bug_reports_message()
  622. super(ExtractorError, self).__init__(msg)
  623. self.traceback = tb
  624. self.exc_info = sys.exc_info() # preserve original exception
  625. self.cause = cause
  626. self.video_id = video_id
  627. def format_traceback(self):
  628. if self.traceback is None:
  629. return None
  630. return ''.join(traceback.format_tb(self.traceback))
  631. class UnsupportedError(ExtractorError):
  632. def __init__(self, url):
  633. super(UnsupportedError, self).__init__(
  634. 'Unsupported URL: %s' % url, expected=True)
  635. self.url = url
  636. class RegexNotFoundError(ExtractorError):
  637. """Error when a regex didn't match"""
  638. pass
  639. class GeoRestrictedError(ExtractorError):
  640. """Geographic restriction Error exception.
  641. This exception may be thrown when a video is not available from your
  642. geographic location due to geographic restrictions imposed by a website.
  643. """
  644. def __init__(self, msg, countries=None):
  645. super(GeoRestrictedError, self).__init__(msg, expected=True)
  646. self.msg = msg
  647. self.countries = countries
  648. class DownloadError(YoutubeDLError):
  649. """Download Error exception.
  650. This exception may be thrown by FileDownloader objects if they are not
  651. configured to continue on errors. They will contain the appropriate
  652. error message.
  653. """
  654. def __init__(self, msg, exc_info=None):
  655. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  656. super(DownloadError, self).__init__(msg)
  657. self.exc_info = exc_info
  658. class SameFileError(YoutubeDLError):
  659. """Same File exception.
  660. This exception will be thrown by FileDownloader objects if they detect
  661. multiple files would have to be downloaded to the same file on disk.
  662. """
  663. pass
  664. class PostProcessingError(YoutubeDLError):
  665. """Post Processing exception.
  666. This exception may be raised by PostProcessor's .run() method to
  667. indicate an error in the postprocessing task.
  668. """
  669. def __init__(self, msg):
  670. super(PostProcessingError, self).__init__(msg)
  671. self.msg = msg
  672. class MaxDownloadsReached(YoutubeDLError):
  673. """ --max-downloads limit has been reached. """
  674. pass
  675. class UnavailableVideoError(YoutubeDLError):
  676. """Unavailable Format exception.
  677. This exception will be thrown when a video is requested
  678. in a format that is not available for that video.
  679. """
  680. pass
  681. class ContentTooShortError(YoutubeDLError):
  682. """Content Too Short exception.
  683. This exception may be raised by FileDownloader objects when a file they
  684. download is too small for what the server announced first, indicating
  685. the connection was probably interrupted.
  686. """
  687. def __init__(self, downloaded, expected):
  688. super(ContentTooShortError, self).__init__(
  689. 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
  690. )
  691. # Both in bytes
  692. self.downloaded = downloaded
  693. self.expected = expected
  694. class XAttrMetadataError(YoutubeDLError):
  695. def __init__(self, code=None, msg='Unknown error'):
  696. super(XAttrMetadataError, self).__init__(msg)
  697. self.code = code
  698. self.msg = msg
  699. # Parsing code and msg
  700. if (self.code in (errno.ENOSPC, errno.EDQUOT) or
  701. 'No space left' in self.msg or 'Disk quota excedded' in self.msg):
  702. self.reason = 'NO_SPACE'
  703. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  704. self.reason = 'VALUE_TOO_LONG'
  705. else:
  706. self.reason = 'NOT_SUPPORTED'
  707. class XAttrUnavailableError(YoutubeDLError):
  708. pass
  709. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  710. # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
  711. # expected HTTP responses to meet HTTP/1.0 or later (see also
  712. # https://github.com/ytdl-org/youtube-dl/issues/6727)
  713. if sys.version_info < (3, 0):
  714. kwargs['strict'] = True
  715. hc = http_class(*args, **compat_kwargs(kwargs))
  716. source_address = ydl_handler._params.get('source_address')
  717. if source_address is not None:
  718. # This is to workaround _create_connection() from socket where it will try all
  719. # address data from getaddrinfo() including IPv6. This filters the result from
  720. # getaddrinfo() based on the source_address value.
  721. # This is based on the cpython socket.create_connection() function.
  722. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  723. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  724. host, port = address
  725. err = None
  726. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  727. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  728. ip_addrs = [addr for addr in addrs if addr[0] == af]
  729. if addrs and not ip_addrs:
  730. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  731. raise socket.error(
  732. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  733. % (ip_version, source_address[0]))
  734. for res in ip_addrs:
  735. af, socktype, proto, canonname, sa = res
  736. sock = None
  737. try:
  738. sock = socket.socket(af, socktype, proto)
  739. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  740. sock.settimeout(timeout)
  741. sock.bind(source_address)
  742. sock.connect(sa)
  743. err = None # Explicitly break reference cycle
  744. return sock
  745. except socket.error as _:
  746. err = _
  747. if sock is not None:
  748. sock.close()
  749. if err is not None:
  750. raise err
  751. else:
  752. raise socket.error('getaddrinfo returns an empty list')
  753. if hasattr(hc, '_create_connection'):
  754. hc._create_connection = _create_connection
  755. sa = (source_address, 0)
  756. if hasattr(hc, 'source_address'): # Python 2.7+
  757. hc.source_address = sa
  758. else: # Python 2.6
  759. def _hc_connect(self, *args, **kwargs):
  760. sock = _create_connection(
  761. (self.host, self.port), self.timeout, sa)
  762. if is_https:
  763. self.sock = ssl.wrap_socket(
  764. sock, self.key_file, self.cert_file,
  765. ssl_version=ssl.PROTOCOL_TLSv1)
  766. else:
  767. self.sock = sock
  768. hc.connect = functools.partial(_hc_connect, hc)
  769. return hc
  770. def handle_youtubedl_headers(headers):
  771. filtered_headers = headers
  772. if 'Youtubedl-no-compression' in filtered_headers:
  773. filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
  774. del filtered_headers['Youtubedl-no-compression']
  775. return filtered_headers
  776. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  777. """Handler for HTTP requests and responses.
  778. This class, when installed with an OpenerDirector, automatically adds
  779. the standard headers to every HTTP request and handles gzipped and
  780. deflated responses from web servers. If compression is to be avoided in
  781. a particular request, the original request in the program code only has
  782. to include the HTTP header "Youtubedl-no-compression", which will be
  783. removed before making the real request.
  784. Part of this code was copied from:
  785. http://techknack.net/python-urllib2-handlers/
  786. Andrew Rowls, the author of that code, agreed to release it to the
  787. public domain.
  788. """
  789. def __init__(self, params, *args, **kwargs):
  790. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  791. self._params = params
  792. def http_open(self, req):
  793. conn_class = compat_http_client.HTTPConnection
  794. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  795. if socks_proxy:
  796. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  797. del req.headers['Ytdl-socks-proxy']
  798. return self.do_open(functools.partial(
  799. _create_http_connection, self, conn_class, False),
  800. req)
  801. @staticmethod
  802. def deflate(data):
  803. try:
  804. return zlib.decompress(data, -zlib.MAX_WBITS)
  805. except zlib.error:
  806. return zlib.decompress(data)
  807. def http_request(self, req):
  808. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  809. # always respected by websites, some tend to give out URLs with non percent-encoded
  810. # non-ASCII characters (see telemb.py, ard.py [#3412])
  811. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  812. # To work around aforementioned issue we will replace request's original URL with
  813. # percent-encoded one
  814. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  815. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  816. url = req.get_full_url()
  817. url_escaped = escape_url(url)
  818. # Substitute URL if any change after escaping
  819. if url != url_escaped:
  820. req = update_Request(req, url=url_escaped)
  821. for h, v in std_headers.items():
  822. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  823. # The dict keys are capitalized because of this bug by urllib
  824. if h.capitalize() not in req.headers:
  825. req.add_header(h, v)
  826. req.headers = handle_youtubedl_headers(req.headers)
  827. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  828. # Python 2.6 is brain-dead when it comes to fragments
  829. req._Request__original = req._Request__original.partition('#')[0]
  830. req._Request__r_type = req._Request__r_type.partition('#')[0]
  831. return req
  832. def http_response(self, req, resp):
  833. old_resp = resp
  834. # gzip
  835. if resp.headers.get('Content-encoding', '') == 'gzip':
  836. content = resp.read()
  837. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  838. try:
  839. uncompressed = io.BytesIO(gz.read())
  840. except IOError as original_ioerror:
  841. # There may be junk add the end of the file
  842. # See http://stackoverflow.com/q/4928560/35070 for details
  843. for i in range(1, 1024):
  844. try:
  845. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  846. uncompressed = io.BytesIO(gz.read())
  847. except IOError:
  848. continue
  849. break
  850. else:
  851. raise original_ioerror
  852. resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  853. resp.msg = old_resp.msg
  854. del resp.headers['Content-encoding']
  855. # deflate
  856. if resp.headers.get('Content-encoding', '') == 'deflate':
  857. gz = io.BytesIO(self.deflate(resp.read()))
  858. resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  859. resp.msg = old_resp.msg
  860. del resp.headers['Content-encoding']
  861. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  862. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  863. if 300 <= resp.code < 400:
  864. location = resp.headers.get('Location')
  865. if location:
  866. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  867. if sys.version_info >= (3, 0):
  868. location = location.encode('iso-8859-1').decode('utf-8')
  869. else:
  870. location = location.decode('utf-8')
  871. location_escaped = escape_url(location)
  872. if location != location_escaped:
  873. del resp.headers['Location']
  874. if sys.version_info < (3, 0):
  875. location_escaped = location_escaped.encode('utf-8')
  876. resp.headers['Location'] = location_escaped
  877. return resp
  878. https_request = http_request
  879. https_response = http_response
  880. def make_socks_conn_class(base_class, socks_proxy):
  881. assert issubclass(base_class, (
  882. compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
  883. url_components = compat_urlparse.urlparse(socks_proxy)
  884. if url_components.scheme.lower() == 'socks5':
  885. socks_type = ProxyType.SOCKS5
  886. elif url_components.scheme.lower() in ('socks', 'socks4'):
  887. socks_type = ProxyType.SOCKS4
  888. elif url_components.scheme.lower() == 'socks4a':
  889. socks_type = ProxyType.SOCKS4A
  890. def unquote_if_non_empty(s):
  891. if not s:
  892. return s
  893. return compat_urllib_parse_unquote_plus(s)
  894. proxy_args = (
  895. socks_type,
  896. url_components.hostname, url_components.port or 1080,
  897. True, # Remote DNS
  898. unquote_if_non_empty(url_components.username),
  899. unquote_if_non_empty(url_components.password),
  900. )
  901. class SocksConnection(base_class):
  902. def connect(self):
  903. self.sock = sockssocket()
  904. self.sock.setproxy(*proxy_args)
  905. if type(self.timeout) in (int, float):
  906. self.sock.settimeout(self.timeout)
  907. self.sock.connect((self.host, self.port))
  908. if isinstance(self, compat_http_client.HTTPSConnection):
  909. if hasattr(self, '_context'): # Python > 2.6
  910. self.sock = self._context.wrap_socket(
  911. self.sock, server_hostname=self.host)
  912. else:
  913. self.sock = ssl.wrap_socket(self.sock)
  914. return SocksConnection
  915. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  916. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  917. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  918. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  919. self._params = params
  920. def https_open(self, req):
  921. kwargs = {}
  922. conn_class = self._https_conn_class
  923. if hasattr(self, '_context'): # python > 2.6
  924. kwargs['context'] = self._context
  925. if hasattr(self, '_check_hostname'): # python 3.x
  926. kwargs['check_hostname'] = self._check_hostname
  927. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  928. if socks_proxy:
  929. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  930. del req.headers['Ytdl-socks-proxy']
  931. return self.do_open(functools.partial(
  932. _create_http_connection, self, conn_class, True),
  933. req, **kwargs)
  934. class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
  935. _HTTPONLY_PREFIX = '#HttpOnly_'
  936. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  937. # Store session cookies with `expires` set to 0 instead of an empty
  938. # string
  939. for cookie in self:
  940. if cookie.expires is None:
  941. cookie.expires = 0
  942. compat_cookiejar.MozillaCookieJar.save(self, filename, ignore_discard, ignore_expires)
  943. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  944. """Load cookies from a file."""
  945. if filename is None:
  946. if self.filename is not None:
  947. filename = self.filename
  948. else:
  949. raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
  950. cf = io.StringIO()
  951. with open(filename) as f:
  952. for line in f:
  953. if line.startswith(self._HTTPONLY_PREFIX):
  954. line = line[len(self._HTTPONLY_PREFIX):]
  955. cf.write(compat_str(line))
  956. cf.seek(0)
  957. self._really_load(cf, filename, ignore_discard, ignore_expires)
  958. # Session cookies are denoted by either `expires` field set to
  959. # an empty string or 0. MozillaCookieJar only recognizes the former
  960. # (see [1]). So we need force the latter to be recognized as session
  961. # cookies on our own.
  962. # Session cookies may be important for cookies-based authentication,
  963. # e.g. usually, when user does not check 'Remember me' check box while
  964. # logging in on a site, some important cookies are stored as session
  965. # cookies so that not recognizing them will result in failed login.
  966. # 1. https://bugs.python.org/issue17164
  967. for cookie in self:
  968. # Treat `expires=0` cookies as session cookies
  969. if cookie.expires == 0:
  970. cookie.expires = None
  971. cookie.discard = True
  972. class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
  973. def __init__(self, cookiejar=None):
  974. compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
  975. def http_response(self, request, response):
  976. # Python 2 will choke on next HTTP request in row if there are non-ASCII
  977. # characters in Set-Cookie HTTP header of last response (see
  978. # https://github.com/ytdl-org/youtube-dl/issues/6769).
  979. # In order to at least prevent crashing we will percent encode Set-Cookie
  980. # header before HTTPCookieProcessor starts processing it.
  981. # if sys.version_info < (3, 0) and response.headers:
  982. # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
  983. # set_cookie = response.headers.get(set_cookie_header)
  984. # if set_cookie:
  985. # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
  986. # if set_cookie != set_cookie_escaped:
  987. # del response.headers[set_cookie_header]
  988. # response.headers[set_cookie_header] = set_cookie_escaped
  989. return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
  990. https_request = compat_urllib_request.HTTPCookieProcessor.http_request
  991. https_response = http_response
  992. def extract_timezone(date_str):
  993. m = re.search(
  994. r'^.{8,}?(?P<tz>Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  995. date_str)
  996. if not m:
  997. timezone = datetime.timedelta()
  998. else:
  999. date_str = date_str[:-len(m.group('tz'))]
  1000. if not m.group('sign'):
  1001. timezone = datetime.timedelta()
  1002. else:
  1003. sign = 1 if m.group('sign') == '+' else -1
  1004. timezone = datetime.timedelta(
  1005. hours=sign * int(m.group('hours')),
  1006. minutes=sign * int(m.group('minutes')))
  1007. return timezone, date_str
  1008. def parse_iso8601(date_str, delimiter='T', timezone=None):
  1009. """ Return a UNIX timestamp from the given date """
  1010. if date_str is None:
  1011. return None
  1012. date_str = re.sub(r'\.[0-9]+', '', date_str)
  1013. if timezone is None:
  1014. timezone, date_str = extract_timezone(date_str)
  1015. try:
  1016. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  1017. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  1018. return calendar.timegm(dt.timetuple())
  1019. except ValueError:
  1020. pass
  1021. def date_formats(day_first=True):
  1022. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  1023. def unified_strdate(date_str, day_first=True):
  1024. """Return a string with the date in the format YYYYMMDD"""
  1025. if date_str is None:
  1026. return None
  1027. upload_date = None
  1028. # Replace commas
  1029. date_str = date_str.replace(',', ' ')
  1030. # Remove AM/PM + timezone
  1031. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1032. _, date_str = extract_timezone(date_str)
  1033. for expression in date_formats(day_first):
  1034. try:
  1035. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  1036. except ValueError:
  1037. pass
  1038. if upload_date is None:
  1039. timetuple = email.utils.parsedate_tz(date_str)
  1040. if timetuple:
  1041. try:
  1042. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  1043. except ValueError:
  1044. pass
  1045. if upload_date is not None:
  1046. return compat_str(upload_date)
  1047. def unified_timestamp(date_str, day_first=True):
  1048. if date_str is None:
  1049. return None
  1050. date_str = re.sub(r'[,|]', '', date_str)
  1051. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  1052. timezone, date_str = extract_timezone(date_str)
  1053. # Remove AM/PM + timezone
  1054. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1055. # Remove unrecognized timezones from ISO 8601 alike timestamps
  1056. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  1057. if m:
  1058. date_str = date_str[:-len(m.group('tz'))]
  1059. # Python only supports microseconds, so remove nanoseconds
  1060. 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)
  1061. if m:
  1062. date_str = m.group(1)
  1063. for expression in date_formats(day_first):
  1064. try:
  1065. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  1066. return calendar.timegm(dt.timetuple())
  1067. except ValueError:
  1068. pass
  1069. timetuple = email.utils.parsedate_tz(date_str)
  1070. if timetuple:
  1071. return calendar.timegm(timetuple) + pm_delta * 3600
  1072. def determine_ext(url, default_ext='unknown_video'):
  1073. if url is None or '.' not in url:
  1074. return default_ext
  1075. guess = url.partition('?')[0].rpartition('.')[2]
  1076. if re.match(r'^[A-Za-z0-9]+$', guess):
  1077. return guess
  1078. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  1079. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  1080. return guess.rstrip('/')
  1081. else:
  1082. return default_ext
  1083. def subtitles_filename(filename, sub_lang, sub_format):
  1084. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  1085. def date_from_str(date_str):
  1086. """
  1087. Return a datetime object from a string in the format YYYYMMDD or
  1088. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  1089. today = datetime.date.today()
  1090. if date_str in ('now', 'today'):
  1091. return today
  1092. if date_str == 'yesterday':
  1093. return today - datetime.timedelta(days=1)
  1094. match = re.match(r'(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  1095. if match is not None:
  1096. sign = match.group('sign')
  1097. time = int(match.group('time'))
  1098. if sign == '-':
  1099. time = -time
  1100. unit = match.group('unit')
  1101. # A bad approximation?
  1102. if unit == 'month':
  1103. unit = 'day'
  1104. time *= 30
  1105. elif unit == 'year':
  1106. unit = 'day'
  1107. time *= 365
  1108. unit += 's'
  1109. delta = datetime.timedelta(**{unit: time})
  1110. return today + delta
  1111. return datetime.datetime.strptime(date_str, '%Y%m%d').date()
  1112. def hyphenate_date(date_str):
  1113. """
  1114. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  1115. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  1116. if match is not None:
  1117. return '-'.join(match.groups())
  1118. else:
  1119. return date_str
  1120. class DateRange(object):
  1121. """Represents a time interval between two dates"""
  1122. def __init__(self, start=None, end=None):
  1123. """start and end must be strings in the format accepted by date"""
  1124. if start is not None:
  1125. self.start = date_from_str(start)
  1126. else:
  1127. self.start = datetime.datetime.min.date()
  1128. if end is not None:
  1129. self.end = date_from_str(end)
  1130. else:
  1131. self.end = datetime.datetime.max.date()
  1132. if self.start > self.end:
  1133. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  1134. @classmethod
  1135. def day(cls, day):
  1136. """Returns a range that only contains the given day"""
  1137. return cls(day, day)
  1138. def __contains__(self, date):
  1139. """Check if the date is in the range"""
  1140. if not isinstance(date, datetime.date):
  1141. date = date_from_str(date)
  1142. return self.start <= date <= self.end
  1143. def __str__(self):
  1144. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  1145. def platform_name():
  1146. """ Returns the platform name as a compat_str """
  1147. res = platform.platform()
  1148. if isinstance(res, bytes):
  1149. res = res.decode(preferredencoding())
  1150. assert isinstance(res, compat_str)
  1151. return res
  1152. def _windows_write_string(s, out):
  1153. """ Returns True if the string was written using special methods,
  1154. False if it has yet to be written out."""
  1155. # Adapted from http://stackoverflow.com/a/3259271/35070
  1156. import ctypes
  1157. import ctypes.wintypes
  1158. WIN_OUTPUT_IDS = {
  1159. 1: -11,
  1160. 2: -12,
  1161. }
  1162. try:
  1163. fileno = out.fileno()
  1164. except AttributeError:
  1165. # If the output stream doesn't have a fileno, it's virtual
  1166. return False
  1167. except io.UnsupportedOperation:
  1168. # Some strange Windows pseudo files?
  1169. return False
  1170. if fileno not in WIN_OUTPUT_IDS:
  1171. return False
  1172. GetStdHandle = compat_ctypes_WINFUNCTYPE(
  1173. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  1174. ('GetStdHandle', ctypes.windll.kernel32))
  1175. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  1176. WriteConsoleW = compat_ctypes_WINFUNCTYPE(
  1177. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  1178. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  1179. ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
  1180. written = ctypes.wintypes.DWORD(0)
  1181. GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
  1182. FILE_TYPE_CHAR = 0x0002
  1183. FILE_TYPE_REMOTE = 0x8000
  1184. GetConsoleMode = compat_ctypes_WINFUNCTYPE(
  1185. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  1186. ctypes.POINTER(ctypes.wintypes.DWORD))(
  1187. ('GetConsoleMode', ctypes.windll.kernel32))
  1188. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  1189. def not_a_console(handle):
  1190. if handle == INVALID_HANDLE_VALUE or handle is None:
  1191. return True
  1192. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  1193. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  1194. if not_a_console(h):
  1195. return False
  1196. def next_nonbmp_pos(s):
  1197. try:
  1198. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  1199. except StopIteration:
  1200. return len(s)
  1201. while s:
  1202. count = min(next_nonbmp_pos(s), 1024)
  1203. ret = WriteConsoleW(
  1204. h, s, count if count else 2, ctypes.byref(written), None)
  1205. if ret == 0:
  1206. raise OSError('Failed to write string')
  1207. if not count: # We just wrote a non-BMP character
  1208. assert written.value == 2
  1209. s = s[1:]
  1210. else:
  1211. assert written.value > 0
  1212. s = s[written.value:]
  1213. return True
  1214. def write_string(s, out=None, encoding=None):
  1215. if out is None:
  1216. out = sys.stderr
  1217. assert type(s) == compat_str
  1218. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  1219. if _windows_write_string(s, out):
  1220. return
  1221. if ('b' in getattr(out, 'mode', '') or
  1222. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  1223. byt = s.encode(encoding or preferredencoding(), 'ignore')
  1224. out.write(byt)
  1225. elif hasattr(out, 'buffer'):
  1226. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1227. byt = s.encode(enc, 'ignore')
  1228. out.buffer.write(byt)
  1229. else:
  1230. out.write(s)
  1231. out.flush()
  1232. def bytes_to_intlist(bs):
  1233. if not bs:
  1234. return []
  1235. if isinstance(bs[0], int): # Python 3
  1236. return list(bs)
  1237. else:
  1238. return [ord(c) for c in bs]
  1239. def intlist_to_bytes(xs):
  1240. if not xs:
  1241. return b''
  1242. return compat_struct_pack('%dB' % len(xs), *xs)
  1243. # Cross-platform file locking
  1244. if sys.platform == 'win32':
  1245. import ctypes.wintypes
  1246. import msvcrt
  1247. class OVERLAPPED(ctypes.Structure):
  1248. _fields_ = [
  1249. ('Internal', ctypes.wintypes.LPVOID),
  1250. ('InternalHigh', ctypes.wintypes.LPVOID),
  1251. ('Offset', ctypes.wintypes.DWORD),
  1252. ('OffsetHigh', ctypes.wintypes.DWORD),
  1253. ('hEvent', ctypes.wintypes.HANDLE),
  1254. ]
  1255. kernel32 = ctypes.windll.kernel32
  1256. LockFileEx = kernel32.LockFileEx
  1257. LockFileEx.argtypes = [
  1258. ctypes.wintypes.HANDLE, # hFile
  1259. ctypes.wintypes.DWORD, # dwFlags
  1260. ctypes.wintypes.DWORD, # dwReserved
  1261. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1262. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1263. ctypes.POINTER(OVERLAPPED) # Overlapped
  1264. ]
  1265. LockFileEx.restype = ctypes.wintypes.BOOL
  1266. UnlockFileEx = kernel32.UnlockFileEx
  1267. UnlockFileEx.argtypes = [
  1268. ctypes.wintypes.HANDLE, # hFile
  1269. ctypes.wintypes.DWORD, # dwReserved
  1270. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1271. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1272. ctypes.POINTER(OVERLAPPED) # Overlapped
  1273. ]
  1274. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1275. whole_low = 0xffffffff
  1276. whole_high = 0x7fffffff
  1277. def _lock_file(f, exclusive):
  1278. overlapped = OVERLAPPED()
  1279. overlapped.Offset = 0
  1280. overlapped.OffsetHigh = 0
  1281. overlapped.hEvent = 0
  1282. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1283. handle = msvcrt.get_osfhandle(f.fileno())
  1284. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  1285. whole_low, whole_high, f._lock_file_overlapped_p):
  1286. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  1287. def _unlock_file(f):
  1288. assert f._lock_file_overlapped_p
  1289. handle = msvcrt.get_osfhandle(f.fileno())
  1290. if not UnlockFileEx(handle, 0,
  1291. whole_low, whole_high, f._lock_file_overlapped_p):
  1292. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1293. else:
  1294. # Some platforms, such as Jython, is missing fcntl
  1295. try:
  1296. import fcntl
  1297. def _lock_file(f, exclusive):
  1298. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  1299. def _unlock_file(f):
  1300. fcntl.flock(f, fcntl.LOCK_UN)
  1301. except ImportError:
  1302. UNSUPPORTED_MSG = 'file locking is not supported on this platform'
  1303. def _lock_file(f, exclusive):
  1304. raise IOError(UNSUPPORTED_MSG)
  1305. def _unlock_file(f):
  1306. raise IOError(UNSUPPORTED_MSG)
  1307. class locked_file(object):
  1308. def __init__(self, filename, mode, encoding=None):
  1309. assert mode in ['r', 'a', 'w']
  1310. self.f = io.open(filename, mode, encoding=encoding)
  1311. self.mode = mode
  1312. def __enter__(self):
  1313. exclusive = self.mode != 'r'
  1314. try:
  1315. _lock_file(self.f, exclusive)
  1316. except IOError:
  1317. self.f.close()
  1318. raise
  1319. return self
  1320. def __exit__(self, etype, value, traceback):
  1321. try:
  1322. _unlock_file(self.f)
  1323. finally:
  1324. self.f.close()
  1325. def __iter__(self):
  1326. return iter(self.f)
  1327. def write(self, *args):
  1328. return self.f.write(*args)
  1329. def read(self, *args):
  1330. return self.f.read(*args)
  1331. def get_filesystem_encoding():
  1332. encoding = sys.getfilesystemencoding()
  1333. return encoding if encoding is not None else 'utf-8'
  1334. def shell_quote(args):
  1335. quoted_args = []
  1336. encoding = get_filesystem_encoding()
  1337. for a in args:
  1338. if isinstance(a, bytes):
  1339. # We may get a filename encoded with 'encodeFilename'
  1340. a = a.decode(encoding)
  1341. quoted_args.append(compat_shlex_quote(a))
  1342. return ' '.join(quoted_args)
  1343. def smuggle_url(url, data):
  1344. """ Pass additional data in a URL for internal use. """
  1345. url, idata = unsmuggle_url(url, {})
  1346. data.update(idata)
  1347. sdata = compat_urllib_parse_urlencode(
  1348. {'__youtubedl_smuggle': json.dumps(data)})
  1349. return url + '#' + sdata
  1350. def unsmuggle_url(smug_url, default=None):
  1351. if '#__youtubedl_smuggle' not in smug_url:
  1352. return smug_url, default
  1353. url, _, sdata = smug_url.rpartition('#')
  1354. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  1355. data = json.loads(jsond)
  1356. return url, data
  1357. def format_bytes(bytes):
  1358. if bytes is None:
  1359. return 'N/A'
  1360. if type(bytes) is str:
  1361. bytes = float(bytes)
  1362. if bytes == 0.0:
  1363. exponent = 0
  1364. else:
  1365. exponent = int(math.log(bytes, 1024.0))
  1366. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  1367. converted = float(bytes) / float(1024 ** exponent)
  1368. return '%.2f%s' % (converted, suffix)
  1369. def lookup_unit_table(unit_table, s):
  1370. units_re = '|'.join(re.escape(u) for u in unit_table)
  1371. m = re.match(
  1372. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1373. if not m:
  1374. return None
  1375. num_str = m.group('num').replace(',', '.')
  1376. mult = unit_table[m.group('unit')]
  1377. return int(float(num_str) * mult)
  1378. def parse_filesize(s):
  1379. if s is None:
  1380. return None
  1381. # The lower-case forms are of course incorrect and unofficial,
  1382. # but we support those too
  1383. _UNIT_TABLE = {
  1384. 'B': 1,
  1385. 'b': 1,
  1386. 'bytes': 1,
  1387. 'KiB': 1024,
  1388. 'KB': 1000,
  1389. 'kB': 1024,
  1390. 'Kb': 1000,
  1391. 'kb': 1000,
  1392. 'kilobytes': 1000,
  1393. 'kibibytes': 1024,
  1394. 'MiB': 1024 ** 2,
  1395. 'MB': 1000 ** 2,
  1396. 'mB': 1024 ** 2,
  1397. 'Mb': 1000 ** 2,
  1398. 'mb': 1000 ** 2,
  1399. 'megabytes': 1000 ** 2,
  1400. 'mebibytes': 1024 ** 2,
  1401. 'GiB': 1024 ** 3,
  1402. 'GB': 1000 ** 3,
  1403. 'gB': 1024 ** 3,
  1404. 'Gb': 1000 ** 3,
  1405. 'gb': 1000 ** 3,
  1406. 'gigabytes': 1000 ** 3,
  1407. 'gibibytes': 1024 ** 3,
  1408. 'TiB': 1024 ** 4,
  1409. 'TB': 1000 ** 4,
  1410. 'tB': 1024 ** 4,
  1411. 'Tb': 1000 ** 4,
  1412. 'tb': 1000 ** 4,
  1413. 'terabytes': 1000 ** 4,
  1414. 'tebibytes': 1024 ** 4,
  1415. 'PiB': 1024 ** 5,
  1416. 'PB': 1000 ** 5,
  1417. 'pB': 1024 ** 5,
  1418. 'Pb': 1000 ** 5,
  1419. 'pb': 1000 ** 5,
  1420. 'petabytes': 1000 ** 5,
  1421. 'pebibytes': 1024 ** 5,
  1422. 'EiB': 1024 ** 6,
  1423. 'EB': 1000 ** 6,
  1424. 'eB': 1024 ** 6,
  1425. 'Eb': 1000 ** 6,
  1426. 'eb': 1000 ** 6,
  1427. 'exabytes': 1000 ** 6,
  1428. 'exbibytes': 1024 ** 6,
  1429. 'ZiB': 1024 ** 7,
  1430. 'ZB': 1000 ** 7,
  1431. 'zB': 1024 ** 7,
  1432. 'Zb': 1000 ** 7,
  1433. 'zb': 1000 ** 7,
  1434. 'zettabytes': 1000 ** 7,
  1435. 'zebibytes': 1024 ** 7,
  1436. 'YiB': 1024 ** 8,
  1437. 'YB': 1000 ** 8,
  1438. 'yB': 1024 ** 8,
  1439. 'Yb': 1000 ** 8,
  1440. 'yb': 1000 ** 8,
  1441. 'yottabytes': 1000 ** 8,
  1442. 'yobibytes': 1024 ** 8,
  1443. }
  1444. return lookup_unit_table(_UNIT_TABLE, s)
  1445. def parse_count(s):
  1446. if s is None:
  1447. return None
  1448. s = s.strip()
  1449. if re.match(r'^[\d,.]+$', s):
  1450. return str_to_int(s)
  1451. _UNIT_TABLE = {
  1452. 'k': 1000,
  1453. 'K': 1000,
  1454. 'm': 1000 ** 2,
  1455. 'M': 1000 ** 2,
  1456. 'kk': 1000 ** 2,
  1457. 'KK': 1000 ** 2,
  1458. }
  1459. return lookup_unit_table(_UNIT_TABLE, s)
  1460. def parse_resolution(s):
  1461. if s is None:
  1462. return {}
  1463. mobj = re.search(r'\b(?P<w>\d+)\s*[xX×]\s*(?P<h>\d+)\b', s)
  1464. if mobj:
  1465. return {
  1466. 'width': int(mobj.group('w')),
  1467. 'height': int(mobj.group('h')),
  1468. }
  1469. mobj = re.search(r'\b(\d+)[pPiI]\b', s)
  1470. if mobj:
  1471. return {'height': int(mobj.group(1))}
  1472. mobj = re.search(r'\b([48])[kK]\b', s)
  1473. if mobj:
  1474. return {'height': int(mobj.group(1)) * 540}
  1475. return {}
  1476. def parse_bitrate(s):
  1477. if not isinstance(s, compat_str):
  1478. return
  1479. mobj = re.search(r'\b(\d+)\s*kbps', s)
  1480. if mobj:
  1481. return int(mobj.group(1))
  1482. def month_by_name(name, lang='en'):
  1483. """ Return the number of a month by (locale-independently) English name """
  1484. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  1485. try:
  1486. return month_names.index(name) + 1
  1487. except ValueError:
  1488. return None
  1489. def month_by_abbreviation(abbrev):
  1490. """ Return the number of a month by (locale-independently) English
  1491. abbreviations """
  1492. try:
  1493. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1494. except ValueError:
  1495. return None
  1496. def fix_xml_ampersands(xml_str):
  1497. """Replace all the '&' by '&amp;' in XML"""
  1498. return re.sub(
  1499. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1500. '&amp;',
  1501. xml_str)
  1502. def setproctitle(title):
  1503. assert isinstance(title, compat_str)
  1504. # ctypes in Jython is not complete
  1505. # http://bugs.jython.org/issue2148
  1506. if sys.platform.startswith('java'):
  1507. return
  1508. try:
  1509. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1510. except OSError:
  1511. return
  1512. except TypeError:
  1513. # LoadLibrary in Windows Python 2.7.13 only expects
  1514. # a bytestring, but since unicode_literals turns
  1515. # every string into a unicode string, it fails.
  1516. return
  1517. title_bytes = title.encode('utf-8')
  1518. buf = ctypes.create_string_buffer(len(title_bytes))
  1519. buf.value = title_bytes
  1520. try:
  1521. libc.prctl(15, buf, 0, 0, 0)
  1522. except AttributeError:
  1523. return # Strange libc, just skip this
  1524. def remove_start(s, start):
  1525. return s[len(start):] if s is not None and s.startswith(start) else s
  1526. def remove_end(s, end):
  1527. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1528. def remove_quotes(s):
  1529. if s is None or len(s) < 2:
  1530. return s
  1531. for quote in ('"', "'", ):
  1532. if s[0] == quote and s[-1] == quote:
  1533. return s[1:-1]
  1534. return s
  1535. def url_basename(url):
  1536. path = compat_urlparse.urlparse(url).path
  1537. return path.strip('/').split('/')[-1]
  1538. def base_url(url):
  1539. return re.match(r'https?://[^?#&]+/', url).group()
  1540. def urljoin(base, path):
  1541. if isinstance(path, bytes):
  1542. path = path.decode('utf-8')
  1543. if not isinstance(path, compat_str) or not path:
  1544. return None
  1545. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  1546. return path
  1547. if isinstance(base, bytes):
  1548. base = base.decode('utf-8')
  1549. if not isinstance(base, compat_str) or not re.match(
  1550. r'^(?:https?:)?//', base):
  1551. return None
  1552. return compat_urlparse.urljoin(base, path)
  1553. class HEADRequest(compat_urllib_request.Request):
  1554. def get_method(self):
  1555. return 'HEAD'
  1556. class PUTRequest(compat_urllib_request.Request):
  1557. def get_method(self):
  1558. return 'PUT'
  1559. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1560. if get_attr:
  1561. if v is not None:
  1562. v = getattr(v, get_attr, None)
  1563. if v == '':
  1564. v = None
  1565. if v is None:
  1566. return default
  1567. try:
  1568. return int(v) * invscale // scale
  1569. except (ValueError, TypeError):
  1570. return default
  1571. def str_or_none(v, default=None):
  1572. return default if v is None else compat_str(v)
  1573. def str_to_int(int_str):
  1574. """ A more relaxed version of int_or_none """
  1575. if int_str is None:
  1576. return None
  1577. int_str = re.sub(r'[,\.\+]', '', int_str)
  1578. return int(int_str)
  1579. def float_or_none(v, scale=1, invscale=1, default=None):
  1580. if v is None:
  1581. return default
  1582. try:
  1583. return float(v) * invscale / scale
  1584. except (ValueError, TypeError):
  1585. return default
  1586. def bool_or_none(v, default=None):
  1587. return v if isinstance(v, bool) else default
  1588. def strip_or_none(v):
  1589. return None if v is None else v.strip()
  1590. def url_or_none(url):
  1591. if not url or not isinstance(url, compat_str):
  1592. return None
  1593. url = url.strip()
  1594. return url if re.match(r'^(?:[a-zA-Z][\da-zA-Z.+-]*:)?//', url) else None
  1595. def parse_duration(s):
  1596. if not isinstance(s, compat_basestring):
  1597. return None
  1598. s = s.strip()
  1599. days, hours, mins, secs, ms = [None] * 5
  1600. 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)
  1601. if m:
  1602. days, hours, mins, secs, ms = m.groups()
  1603. else:
  1604. m = re.match(
  1605. r'''(?ix)(?:P?
  1606. (?:
  1607. [0-9]+\s*y(?:ears?)?\s*
  1608. )?
  1609. (?:
  1610. [0-9]+\s*m(?:onths?)?\s*
  1611. )?
  1612. (?:
  1613. [0-9]+\s*w(?:eeks?)?\s*
  1614. )?
  1615. (?:
  1616. (?P<days>[0-9]+)\s*d(?:ays?)?\s*
  1617. )?
  1618. T)?
  1619. (?:
  1620. (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
  1621. )?
  1622. (?:
  1623. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
  1624. )?
  1625. (?:
  1626. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  1627. )?Z?$''', s)
  1628. if m:
  1629. days, hours, mins, secs, ms = m.groups()
  1630. else:
  1631. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  1632. if m:
  1633. hours, mins = m.groups()
  1634. else:
  1635. return None
  1636. duration = 0
  1637. if secs:
  1638. duration += float(secs)
  1639. if mins:
  1640. duration += float(mins) * 60
  1641. if hours:
  1642. duration += float(hours) * 60 * 60
  1643. if days:
  1644. duration += float(days) * 24 * 60 * 60
  1645. if ms:
  1646. duration += float(ms)
  1647. return duration
  1648. def prepend_extension(filename, ext, expected_real_ext=None):
  1649. name, real_ext = os.path.splitext(filename)
  1650. return (
  1651. '{0}.{1}{2}'.format(name, ext, real_ext)
  1652. if not expected_real_ext or real_ext[1:] == expected_real_ext
  1653. else '{0}.{1}'.format(filename, ext))
  1654. def replace_extension(filename, ext, expected_real_ext=None):
  1655. name, real_ext = os.path.splitext(filename)
  1656. return '{0}.{1}'.format(
  1657. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  1658. ext)
  1659. def check_executable(exe, args=[]):
  1660. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1661. args can be a list of arguments for a short output (like -version) """
  1662. try:
  1663. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1664. except OSError:
  1665. return False
  1666. return exe
  1667. def get_exe_version(exe, args=['--version'],
  1668. version_re=None, unrecognized='present'):
  1669. """ Returns the version of the specified executable,
  1670. or False if the executable is not present """
  1671. try:
  1672. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  1673. # SIGTTOU if youtube-dl is run in the background.
  1674. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  1675. out, _ = subprocess.Popen(
  1676. [encodeArgument(exe)] + args,
  1677. stdin=subprocess.PIPE,
  1678. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1679. except OSError:
  1680. return False
  1681. if isinstance(out, bytes): # Python 2.x
  1682. out = out.decode('ascii', 'ignore')
  1683. return detect_exe_version(out, version_re, unrecognized)
  1684. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1685. assert isinstance(output, compat_str)
  1686. if version_re is None:
  1687. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1688. m = re.search(version_re, output)
  1689. if m:
  1690. return m.group(1)
  1691. else:
  1692. return unrecognized
  1693. class PagedList(object):
  1694. def __len__(self):
  1695. # This is only useful for tests
  1696. return len(self.getslice())
  1697. class OnDemandPagedList(PagedList):
  1698. def __init__(self, pagefunc, pagesize, use_cache=True):
  1699. self._pagefunc = pagefunc
  1700. self._pagesize = pagesize
  1701. self._use_cache = use_cache
  1702. if use_cache:
  1703. self._cache = {}
  1704. def getslice(self, start=0, end=None):
  1705. res = []
  1706. for pagenum in itertools.count(start // self._pagesize):
  1707. firstid = pagenum * self._pagesize
  1708. nextfirstid = pagenum * self._pagesize + self._pagesize
  1709. if start >= nextfirstid:
  1710. continue
  1711. page_results = None
  1712. if self._use_cache:
  1713. page_results = self._cache.get(pagenum)
  1714. if page_results is None:
  1715. page_results = list(self._pagefunc(pagenum))
  1716. if self._use_cache:
  1717. self._cache[pagenum] = page_results
  1718. startv = (
  1719. start % self._pagesize
  1720. if firstid <= start < nextfirstid
  1721. else 0)
  1722. endv = (
  1723. ((end - 1) % self._pagesize) + 1
  1724. if (end is not None and firstid <= end <= nextfirstid)
  1725. else None)
  1726. if startv != 0 or endv is not None:
  1727. page_results = page_results[startv:endv]
  1728. res.extend(page_results)
  1729. # A little optimization - if current page is not "full", ie. does
  1730. # not contain page_size videos then we can assume that this page
  1731. # is the last one - there are no more ids on further pages -
  1732. # i.e. no need to query again.
  1733. if len(page_results) + startv < self._pagesize:
  1734. break
  1735. # If we got the whole page, but the next page is not interesting,
  1736. # break out early as well
  1737. if end == nextfirstid:
  1738. break
  1739. return res
  1740. class InAdvancePagedList(PagedList):
  1741. def __init__(self, pagefunc, pagecount, pagesize):
  1742. self._pagefunc = pagefunc
  1743. self._pagecount = pagecount
  1744. self._pagesize = pagesize
  1745. def getslice(self, start=0, end=None):
  1746. res = []
  1747. start_page = start // self._pagesize
  1748. end_page = (
  1749. self._pagecount if end is None else (end // self._pagesize + 1))
  1750. skip_elems = start - start_page * self._pagesize
  1751. only_more = None if end is None else end - start
  1752. for pagenum in range(start_page, end_page):
  1753. page = list(self._pagefunc(pagenum))
  1754. if skip_elems:
  1755. page = page[skip_elems:]
  1756. skip_elems = None
  1757. if only_more is not None:
  1758. if len(page) < only_more:
  1759. only_more -= len(page)
  1760. else:
  1761. page = page[:only_more]
  1762. res.extend(page)
  1763. break
  1764. res.extend(page)
  1765. return res
  1766. def uppercase_escape(s):
  1767. unicode_escape = codecs.getdecoder('unicode_escape')
  1768. return re.sub(
  1769. r'\\U[0-9a-fA-F]{8}',
  1770. lambda m: unicode_escape(m.group(0))[0],
  1771. s)
  1772. def lowercase_escape(s):
  1773. unicode_escape = codecs.getdecoder('unicode_escape')
  1774. return re.sub(
  1775. r'\\u[0-9a-fA-F]{4}',
  1776. lambda m: unicode_escape(m.group(0))[0],
  1777. s)
  1778. def escape_rfc3986(s):
  1779. """Escape non-ASCII characters as suggested by RFC 3986"""
  1780. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1781. s = s.encode('utf-8')
  1782. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1783. def escape_url(url):
  1784. """Escape URL as suggested by RFC 3986"""
  1785. url_parsed = compat_urllib_parse_urlparse(url)
  1786. return url_parsed._replace(
  1787. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  1788. path=escape_rfc3986(url_parsed.path),
  1789. params=escape_rfc3986(url_parsed.params),
  1790. query=escape_rfc3986(url_parsed.query),
  1791. fragment=escape_rfc3986(url_parsed.fragment)
  1792. ).geturl()
  1793. def read_batch_urls(batch_fd):
  1794. def fixup(url):
  1795. if not isinstance(url, compat_str):
  1796. url = url.decode('utf-8', 'replace')
  1797. BOM_UTF8 = '\xef\xbb\xbf'
  1798. if url.startswith(BOM_UTF8):
  1799. url = url[len(BOM_UTF8):]
  1800. url = url.strip()
  1801. if url.startswith(('#', ';', ']')):
  1802. return False
  1803. return url
  1804. with contextlib.closing(batch_fd) as fd:
  1805. return [url for url in map(fixup, fd) if url]
  1806. def urlencode_postdata(*args, **kargs):
  1807. return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
  1808. def update_url_query(url, query):
  1809. if not query:
  1810. return url
  1811. parsed_url = compat_urlparse.urlparse(url)
  1812. qs = compat_parse_qs(parsed_url.query)
  1813. qs.update(query)
  1814. return compat_urlparse.urlunparse(parsed_url._replace(
  1815. query=compat_urllib_parse_urlencode(qs, True)))
  1816. def update_Request(req, url=None, data=None, headers={}, query={}):
  1817. req_headers = req.headers.copy()
  1818. req_headers.update(headers)
  1819. req_data = data or req.data
  1820. req_url = update_url_query(url or req.get_full_url(), query)
  1821. req_get_method = req.get_method()
  1822. if req_get_method == 'HEAD':
  1823. req_type = HEADRequest
  1824. elif req_get_method == 'PUT':
  1825. req_type = PUTRequest
  1826. else:
  1827. req_type = compat_urllib_request.Request
  1828. new_req = req_type(
  1829. req_url, data=req_data, headers=req_headers,
  1830. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1831. if hasattr(req, 'timeout'):
  1832. new_req.timeout = req.timeout
  1833. return new_req
  1834. def _multipart_encode_impl(data, boundary):
  1835. content_type = 'multipart/form-data; boundary=%s' % boundary
  1836. out = b''
  1837. for k, v in data.items():
  1838. out += b'--' + boundary.encode('ascii') + b'\r\n'
  1839. if isinstance(k, compat_str):
  1840. k = k.encode('utf-8')
  1841. if isinstance(v, compat_str):
  1842. v = v.encode('utf-8')
  1843. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  1844. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  1845. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  1846. if boundary.encode('ascii') in content:
  1847. raise ValueError('Boundary overlaps with data')
  1848. out += content
  1849. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  1850. return out, content_type
  1851. def multipart_encode(data, boundary=None):
  1852. '''
  1853. Encode a dict to RFC 7578-compliant form-data
  1854. data:
  1855. A dict where keys and values can be either Unicode or bytes-like
  1856. objects.
  1857. boundary:
  1858. If specified a Unicode object, it's used as the boundary. Otherwise
  1859. a random boundary is generated.
  1860. Reference: https://tools.ietf.org/html/rfc7578
  1861. '''
  1862. has_specified_boundary = boundary is not None
  1863. while True:
  1864. if boundary is None:
  1865. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  1866. try:
  1867. out, content_type = _multipart_encode_impl(data, boundary)
  1868. break
  1869. except ValueError:
  1870. if has_specified_boundary:
  1871. raise
  1872. boundary = None
  1873. return out, content_type
  1874. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  1875. if isinstance(key_or_keys, (list, tuple)):
  1876. for key in key_or_keys:
  1877. if key not in d or d[key] is None or skip_false_values and not d[key]:
  1878. continue
  1879. return d[key]
  1880. return default
  1881. return d.get(key_or_keys, default)
  1882. def try_get(src, getter, expected_type=None):
  1883. if not isinstance(getter, (list, tuple)):
  1884. getter = [getter]
  1885. for get in getter:
  1886. try:
  1887. v = get(src)
  1888. except (AttributeError, KeyError, TypeError, IndexError):
  1889. pass
  1890. else:
  1891. if expected_type is None or isinstance(v, expected_type):
  1892. return v
  1893. def merge_dicts(*dicts):
  1894. merged = {}
  1895. for a_dict in dicts:
  1896. for k, v in a_dict.items():
  1897. if v is None:
  1898. continue
  1899. if (k not in merged or
  1900. (isinstance(v, compat_str) and v and
  1901. isinstance(merged[k], compat_str) and
  1902. not merged[k])):
  1903. merged[k] = v
  1904. return merged
  1905. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  1906. return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
  1907. US_RATINGS = {
  1908. 'G': 0,
  1909. 'PG': 10,
  1910. 'PG-13': 13,
  1911. 'R': 16,
  1912. 'NC': 18,
  1913. }
  1914. TV_PARENTAL_GUIDELINES = {
  1915. 'TV-Y': 0,
  1916. 'TV-Y7': 7,
  1917. 'TV-G': 0,
  1918. 'TV-PG': 0,
  1919. 'TV-14': 14,
  1920. 'TV-MA': 17,
  1921. }
  1922. def parse_age_limit(s):
  1923. if type(s) == int:
  1924. return s if 0 <= s <= 21 else None
  1925. if not isinstance(s, compat_basestring):
  1926. return None
  1927. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1928. if m:
  1929. return int(m.group('age'))
  1930. if s in US_RATINGS:
  1931. return US_RATINGS[s]
  1932. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  1933. if m:
  1934. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  1935. return None
  1936. def strip_jsonp(code):
  1937. return re.sub(
  1938. r'''(?sx)^
  1939. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  1940. (?:\s*&&\s*(?P=func_name))?
  1941. \s*\(\s*(?P<callback_data>.*)\);?
  1942. \s*?(?://[^\n]*)*$''',
  1943. r'\g<callback_data>', code)
  1944. def js_to_json(code):
  1945. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
  1946. SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
  1947. INTEGER_TABLE = (
  1948. (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
  1949. (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
  1950. )
  1951. def fix_kv(m):
  1952. v = m.group(0)
  1953. if v in ('true', 'false', 'null'):
  1954. return v
  1955. elif v.startswith('/*') or v.startswith('//') or v == ',':
  1956. return ""
  1957. if v[0] in ("'", '"'):
  1958. v = re.sub(r'(?s)\\.|"', lambda m: {
  1959. '"': '\\"',
  1960. "\\'": "'",
  1961. '\\\n': '',
  1962. '\\x': '\\u00',
  1963. }.get(m.group(0), m.group(0)), v[1:-1])
  1964. for regex, base in INTEGER_TABLE:
  1965. im = re.match(regex, v)
  1966. if im:
  1967. i = int(im.group(1), base)
  1968. return '"%d":' % i if v.endswith(':') else '%d' % i
  1969. return '"%s"' % v
  1970. return re.sub(r'''(?sx)
  1971. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  1972. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  1973. {comment}|,(?={skip}[\]}}])|
  1974. (?:(?<![0-9])[eE]|[a-df-zA-DF-Z_])[.a-zA-Z_0-9]*|
  1975. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  1976. [0-9]+(?={skip}:)
  1977. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  1978. def qualities(quality_ids):
  1979. """ Get a numeric quality value out of a list of possible values """
  1980. def q(qid):
  1981. try:
  1982. return quality_ids.index(qid)
  1983. except ValueError:
  1984. return -1
  1985. return q
  1986. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1987. def limit_length(s, length):
  1988. """ Add ellipses to overly long strings """
  1989. if s is None:
  1990. return None
  1991. ELLIPSES = '...'
  1992. if len(s) > length:
  1993. return s[:length - len(ELLIPSES)] + ELLIPSES
  1994. return s
  1995. def version_tuple(v):
  1996. return tuple(int(e) for e in re.split(r'[-.]', v))
  1997. def is_outdated_version(version, limit, assume_new=True):
  1998. if not version:
  1999. return not assume_new
  2000. try:
  2001. return version_tuple(version) < version_tuple(limit)
  2002. except ValueError:
  2003. return not assume_new
  2004. def ytdl_is_updateable():
  2005. """ Returns if youtube-dl can be updated with -U """
  2006. from zipimport import zipimporter
  2007. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  2008. def args_to_str(args):
  2009. # Get a short string representation for a subprocess command
  2010. return ' '.join(compat_shlex_quote(a) for a in args)
  2011. def error_to_compat_str(err):
  2012. err_str = str(err)
  2013. # On python 2 error byte string must be decoded with proper
  2014. # encoding rather than ascii
  2015. if sys.version_info[0] < 3:
  2016. err_str = err_str.decode(preferredencoding())
  2017. return err_str
  2018. def mimetype2ext(mt):
  2019. if mt is None:
  2020. return None
  2021. ext = {
  2022. 'audio/mp4': 'm4a',
  2023. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  2024. # it's the most popular one
  2025. 'audio/mpeg': 'mp3',
  2026. }.get(mt)
  2027. if ext is not None:
  2028. return ext
  2029. _, _, res = mt.rpartition('/')
  2030. res = res.split(';')[0].strip().lower()
  2031. return {
  2032. '3gpp': '3gp',
  2033. 'smptett+xml': 'tt',
  2034. 'ttaf+xml': 'dfxp',
  2035. 'ttml+xml': 'ttml',
  2036. 'x-flv': 'flv',
  2037. 'x-mp4-fragmented': 'mp4',
  2038. 'x-ms-sami': 'sami',
  2039. 'x-ms-wmv': 'wmv',
  2040. 'mpegurl': 'm3u8',
  2041. 'x-mpegurl': 'm3u8',
  2042. 'vnd.apple.mpegurl': 'm3u8',
  2043. 'dash+xml': 'mpd',
  2044. 'f4m+xml': 'f4m',
  2045. 'hds+xml': 'f4m',
  2046. 'vnd.ms-sstr+xml': 'ism',
  2047. 'quicktime': 'mov',
  2048. 'mp2t': 'ts',
  2049. }.get(res, res)
  2050. def parse_codecs(codecs_str):
  2051. # http://tools.ietf.org/html/rfc6381
  2052. if not codecs_str:
  2053. return {}
  2054. splited_codecs = list(filter(None, map(
  2055. lambda str: str.strip(), codecs_str.strip().strip(',').split(','))))
  2056. vcodec, acodec = None, None
  2057. for full_codec in splited_codecs:
  2058. codec = full_codec.split('.')[0]
  2059. if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2', 'h263', 'h264', 'mp4v', 'hvc1', 'av01'):
  2060. if not vcodec:
  2061. vcodec = full_codec
  2062. elif codec in ('mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  2063. if not acodec:
  2064. acodec = full_codec
  2065. else:
  2066. write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
  2067. if not vcodec and not acodec:
  2068. if len(splited_codecs) == 2:
  2069. return {
  2070. 'vcodec': vcodec,
  2071. 'acodec': acodec,
  2072. }
  2073. elif len(splited_codecs) == 1:
  2074. return {
  2075. 'vcodec': 'none',
  2076. 'acodec': vcodec,
  2077. }
  2078. else:
  2079. return {
  2080. 'vcodec': vcodec or 'none',
  2081. 'acodec': acodec or 'none',
  2082. }
  2083. return {}
  2084. def urlhandle_detect_ext(url_handle):
  2085. getheader = url_handle.headers.get
  2086. cd = getheader('Content-Disposition')
  2087. if cd:
  2088. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  2089. if m:
  2090. e = determine_ext(m.group('filename'), default_ext=None)
  2091. if e:
  2092. return e
  2093. return mimetype2ext(getheader('Content-Type'))
  2094. def encode_data_uri(data, mime_type):
  2095. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  2096. def age_restricted(content_limit, age_limit):
  2097. """ Returns True iff the content should be blocked """
  2098. if age_limit is None: # No limit set
  2099. return False
  2100. if content_limit is None:
  2101. return False # Content available for everyone
  2102. return age_limit < content_limit
  2103. def is_html(first_bytes):
  2104. """ Detect whether a file contains HTML by examining its first bytes. """
  2105. BOMS = [
  2106. (b'\xef\xbb\xbf', 'utf-8'),
  2107. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  2108. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  2109. (b'\xff\xfe', 'utf-16-le'),
  2110. (b'\xfe\xff', 'utf-16-be'),
  2111. ]
  2112. for bom, enc in BOMS:
  2113. if first_bytes.startswith(bom):
  2114. s = first_bytes[len(bom):].decode(enc, 'replace')
  2115. break
  2116. else:
  2117. s = first_bytes.decode('utf-8', 'replace')
  2118. return re.match(r'^\s*<', s)
  2119. def determine_protocol(info_dict):
  2120. protocol = info_dict.get('protocol')
  2121. if protocol is not None:
  2122. return protocol
  2123. url = info_dict['url']
  2124. if url.startswith('rtmp'):
  2125. return 'rtmp'
  2126. elif url.startswith('mms'):
  2127. return 'mms'
  2128. elif url.startswith('rtsp'):
  2129. return 'rtsp'
  2130. ext = determine_ext(url)
  2131. if ext == 'm3u8':
  2132. return 'm3u8'
  2133. elif ext == 'f4m':
  2134. return 'f4m'
  2135. return compat_urllib_parse_urlparse(url).scheme
  2136. def render_table(header_row, data):
  2137. """ Render a list of rows, each as a list of values """
  2138. table = [header_row] + data
  2139. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  2140. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  2141. return '\n'.join(format_str % tuple(row) for row in table)
  2142. def _match_one(filter_part, dct):
  2143. COMPARISON_OPERATORS = {
  2144. '<': operator.lt,
  2145. '<=': operator.le,
  2146. '>': operator.gt,
  2147. '>=': operator.ge,
  2148. '=': operator.eq,
  2149. '!=': operator.ne,
  2150. }
  2151. operator_rex = re.compile(r'''(?x)\s*
  2152. (?P<key>[a-z_]+)
  2153. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  2154. (?:
  2155. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  2156. (?P<quote>["\'])(?P<quotedstrval>(?:\\.|(?!(?P=quote)|\\).)+?)(?P=quote)|
  2157. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  2158. )
  2159. \s*$
  2160. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  2161. m = operator_rex.search(filter_part)
  2162. if m:
  2163. op = COMPARISON_OPERATORS[m.group('op')]
  2164. actual_value = dct.get(m.group('key'))
  2165. if (m.group('quotedstrval') is not None or
  2166. m.group('strval') is not None or
  2167. # If the original field is a string and matching comparisonvalue is
  2168. # a number we should respect the origin of the original field
  2169. # and process comparison value as a string (see
  2170. # https://github.com/ytdl-org/youtube-dl/issues/11082).
  2171. actual_value is not None and m.group('intval') is not None and
  2172. isinstance(actual_value, compat_str)):
  2173. if m.group('op') not in ('=', '!='):
  2174. raise ValueError(
  2175. 'Operator %s does not support string values!' % m.group('op'))
  2176. comparison_value = m.group('quotedstrval') or m.group('strval') or m.group('intval')
  2177. quote = m.group('quote')
  2178. if quote is not None:
  2179. comparison_value = comparison_value.replace(r'\%s' % quote, quote)
  2180. else:
  2181. try:
  2182. comparison_value = int(m.group('intval'))
  2183. except ValueError:
  2184. comparison_value = parse_filesize(m.group('intval'))
  2185. if comparison_value is None:
  2186. comparison_value = parse_filesize(m.group('intval') + 'B')
  2187. if comparison_value is None:
  2188. raise ValueError(
  2189. 'Invalid integer value %r in filter part %r' % (
  2190. m.group('intval'), filter_part))
  2191. if actual_value is None:
  2192. return m.group('none_inclusive')
  2193. return op(actual_value, comparison_value)
  2194. UNARY_OPERATORS = {
  2195. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  2196. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  2197. }
  2198. operator_rex = re.compile(r'''(?x)\s*
  2199. (?P<op>%s)\s*(?P<key>[a-z_]+)
  2200. \s*$
  2201. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  2202. m = operator_rex.search(filter_part)
  2203. if m:
  2204. op = UNARY_OPERATORS[m.group('op')]
  2205. actual_value = dct.get(m.group('key'))
  2206. return op(actual_value)
  2207. raise ValueError('Invalid filter part %r' % filter_part)
  2208. def match_str(filter_str, dct):
  2209. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  2210. return all(
  2211. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  2212. def match_filter_func(filter_str):
  2213. def _match_func(info_dict):
  2214. if match_str(filter_str, info_dict):
  2215. return None
  2216. else:
  2217. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  2218. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  2219. return _match_func
  2220. def parse_dfxp_time_expr(time_expr):
  2221. if not time_expr:
  2222. return
  2223. mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
  2224. if mobj:
  2225. return float(mobj.group('time_offset'))
  2226. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  2227. if mobj:
  2228. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  2229. def srt_subtitles_timecode(seconds):
  2230. return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
  2231. def dfxp2srt(dfxp_data):
  2232. '''
  2233. @param dfxp_data A bytes-like object containing DFXP data
  2234. @returns A unicode object containing converted SRT data
  2235. '''
  2236. LEGACY_NAMESPACES = (
  2237. (b'http://www.w3.org/ns/ttml', [
  2238. b'http://www.w3.org/2004/11/ttaf1',
  2239. b'http://www.w3.org/2006/04/ttaf1',
  2240. b'http://www.w3.org/2006/10/ttaf1',
  2241. ]),
  2242. (b'http://www.w3.org/ns/ttml#styling', [
  2243. b'http://www.w3.org/ns/ttml#style',
  2244. ]),
  2245. )
  2246. SUPPORTED_STYLING = [
  2247. 'color',
  2248. 'fontFamily',
  2249. 'fontSize',
  2250. 'fontStyle',
  2251. 'fontWeight',
  2252. 'textDecoration'
  2253. ]
  2254. _x = functools.partial(xpath_with_ns, ns_map={
  2255. 'xml': 'http://www.w3.org/XML/1998/namespace',
  2256. 'ttml': 'http://www.w3.org/ns/ttml',
  2257. 'tts': 'http://www.w3.org/ns/ttml#styling',
  2258. })
  2259. styles = {}
  2260. default_style = {}
  2261. class TTMLPElementParser(object):
  2262. _out = ''
  2263. _unclosed_elements = []
  2264. _applied_styles = []
  2265. def start(self, tag, attrib):
  2266. if tag in (_x('ttml:br'), 'br'):
  2267. self._out += '\n'
  2268. else:
  2269. unclosed_elements = []
  2270. style = {}
  2271. element_style_id = attrib.get('style')
  2272. if default_style:
  2273. style.update(default_style)
  2274. if element_style_id:
  2275. style.update(styles.get(element_style_id, {}))
  2276. for prop in SUPPORTED_STYLING:
  2277. prop_val = attrib.get(_x('tts:' + prop))
  2278. if prop_val:
  2279. style[prop] = prop_val
  2280. if style:
  2281. font = ''
  2282. for k, v in sorted(style.items()):
  2283. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  2284. continue
  2285. if k == 'color':
  2286. font += ' color="%s"' % v
  2287. elif k == 'fontSize':
  2288. font += ' size="%s"' % v
  2289. elif k == 'fontFamily':
  2290. font += ' face="%s"' % v
  2291. elif k == 'fontWeight' and v == 'bold':
  2292. self._out += '<b>'
  2293. unclosed_elements.append('b')
  2294. elif k == 'fontStyle' and v == 'italic':
  2295. self._out += '<i>'
  2296. unclosed_elements.append('i')
  2297. elif k == 'textDecoration' and v == 'underline':
  2298. self._out += '<u>'
  2299. unclosed_elements.append('u')
  2300. if font:
  2301. self._out += '<font' + font + '>'
  2302. unclosed_elements.append('font')
  2303. applied_style = {}
  2304. if self._applied_styles:
  2305. applied_style.update(self._applied_styles[-1])
  2306. applied_style.update(style)
  2307. self._applied_styles.append(applied_style)
  2308. self._unclosed_elements.append(unclosed_elements)
  2309. def end(self, tag):
  2310. if tag not in (_x('ttml:br'), 'br'):
  2311. unclosed_elements = self._unclosed_elements.pop()
  2312. for element in reversed(unclosed_elements):
  2313. self._out += '</%s>' % element
  2314. if unclosed_elements and self._applied_styles:
  2315. self._applied_styles.pop()
  2316. def data(self, data):
  2317. self._out += data
  2318. def close(self):
  2319. return self._out.strip()
  2320. def parse_node(node):
  2321. target = TTMLPElementParser()
  2322. parser = xml.etree.ElementTree.XMLParser(target=target)
  2323. parser.feed(xml.etree.ElementTree.tostring(node))
  2324. return parser.close()
  2325. for k, v in LEGACY_NAMESPACES:
  2326. for ns in v:
  2327. dfxp_data = dfxp_data.replace(ns, k)
  2328. dfxp = compat_etree_fromstring(dfxp_data)
  2329. out = []
  2330. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  2331. if not paras:
  2332. raise ValueError('Invalid dfxp/TTML subtitle')
  2333. repeat = False
  2334. while True:
  2335. for style in dfxp.findall(_x('.//ttml:style')):
  2336. style_id = style.get('id') or style.get(_x('xml:id'))
  2337. if not style_id:
  2338. continue
  2339. parent_style_id = style.get('style')
  2340. if parent_style_id:
  2341. if parent_style_id not in styles:
  2342. repeat = True
  2343. continue
  2344. styles[style_id] = styles[parent_style_id].copy()
  2345. for prop in SUPPORTED_STYLING:
  2346. prop_val = style.get(_x('tts:' + prop))
  2347. if prop_val:
  2348. styles.setdefault(style_id, {})[prop] = prop_val
  2349. if repeat:
  2350. repeat = False
  2351. else:
  2352. break
  2353. for p in ('body', 'div'):
  2354. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  2355. if ele is None:
  2356. continue
  2357. style = styles.get(ele.get('style'))
  2358. if not style:
  2359. continue
  2360. default_style.update(style)
  2361. for para, index in zip(paras, itertools.count(1)):
  2362. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  2363. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  2364. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  2365. if begin_time is None:
  2366. continue
  2367. if not end_time:
  2368. if not dur:
  2369. continue
  2370. end_time = begin_time + dur
  2371. out.append('%d\n%s --> %s\n%s\n\n' % (
  2372. index,
  2373. srt_subtitles_timecode(begin_time),
  2374. srt_subtitles_timecode(end_time),
  2375. parse_node(para)))
  2376. return ''.join(out)
  2377. def cli_option(params, command_option, param):
  2378. param = params.get(param)
  2379. if param:
  2380. param = compat_str(param)
  2381. return [command_option, param] if param is not None else []
  2382. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  2383. param = params.get(param)
  2384. if param is None:
  2385. return []
  2386. assert isinstance(param, bool)
  2387. if separator:
  2388. return [command_option + separator + (true_value if param else false_value)]
  2389. return [command_option, true_value if param else false_value]
  2390. def cli_valueless_option(params, command_option, param, expected_value=True):
  2391. param = params.get(param)
  2392. return [command_option] if param == expected_value else []
  2393. def cli_configuration_args(params, param, default=[]):
  2394. ex_args = params.get(param)
  2395. if ex_args is None:
  2396. return default
  2397. assert isinstance(ex_args, list)
  2398. return ex_args
  2399. class ISO639Utils(object):
  2400. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  2401. _lang_map = {
  2402. 'aa': 'aar',
  2403. 'ab': 'abk',
  2404. 'ae': 'ave',
  2405. 'af': 'afr',
  2406. 'ak': 'aka',
  2407. 'am': 'amh',
  2408. 'an': 'arg',
  2409. 'ar': 'ara',
  2410. 'as': 'asm',
  2411. 'av': 'ava',
  2412. 'ay': 'aym',
  2413. 'az': 'aze',
  2414. 'ba': 'bak',
  2415. 'be': 'bel',
  2416. 'bg': 'bul',
  2417. 'bh': 'bih',
  2418. 'bi': 'bis',
  2419. 'bm': 'bam',
  2420. 'bn': 'ben',
  2421. 'bo': 'bod',
  2422. 'br': 'bre',
  2423. 'bs': 'bos',
  2424. 'ca': 'cat',
  2425. 'ce': 'che',
  2426. 'ch': 'cha',
  2427. 'co': 'cos',
  2428. 'cr': 'cre',
  2429. 'cs': 'ces',
  2430. 'cu': 'chu',
  2431. 'cv': 'chv',
  2432. 'cy': 'cym',
  2433. 'da': 'dan',
  2434. 'de': 'deu',
  2435. 'dv': 'div',
  2436. 'dz': 'dzo',
  2437. 'ee': 'ewe',
  2438. 'el': 'ell',
  2439. 'en': 'eng',
  2440. 'eo': 'epo',
  2441. 'es': 'spa',
  2442. 'et': 'est',
  2443. 'eu': 'eus',
  2444. 'fa': 'fas',
  2445. 'ff': 'ful',
  2446. 'fi': 'fin',
  2447. 'fj': 'fij',
  2448. 'fo': 'fao',
  2449. 'fr': 'fra',
  2450. 'fy': 'fry',
  2451. 'ga': 'gle',
  2452. 'gd': 'gla',
  2453. 'gl': 'glg',
  2454. 'gn': 'grn',
  2455. 'gu': 'guj',
  2456. 'gv': 'glv',
  2457. 'ha': 'hau',
  2458. 'he': 'heb',
  2459. 'iw': 'heb', # Replaced by he in 1989 revision
  2460. 'hi': 'hin',
  2461. 'ho': 'hmo',
  2462. 'hr': 'hrv',
  2463. 'ht': 'hat',
  2464. 'hu': 'hun',
  2465. 'hy': 'hye',
  2466. 'hz': 'her',
  2467. 'ia': 'ina',
  2468. 'id': 'ind',
  2469. 'in': 'ind', # Replaced by id in 1989 revision
  2470. 'ie': 'ile',
  2471. 'ig': 'ibo',
  2472. 'ii': 'iii',
  2473. 'ik': 'ipk',
  2474. 'io': 'ido',
  2475. 'is': 'isl',
  2476. 'it': 'ita',
  2477. 'iu': 'iku',
  2478. 'ja': 'jpn',
  2479. 'jv': 'jav',
  2480. 'ka': 'kat',
  2481. 'kg': 'kon',
  2482. 'ki': 'kik',
  2483. 'kj': 'kua',
  2484. 'kk': 'kaz',
  2485. 'kl': 'kal',
  2486. 'km': 'khm',
  2487. 'kn': 'kan',
  2488. 'ko': 'kor',
  2489. 'kr': 'kau',
  2490. 'ks': 'kas',
  2491. 'ku': 'kur',
  2492. 'kv': 'kom',
  2493. 'kw': 'cor',
  2494. 'ky': 'kir',
  2495. 'la': 'lat',
  2496. 'lb': 'ltz',
  2497. 'lg': 'lug',
  2498. 'li': 'lim',
  2499. 'ln': 'lin',
  2500. 'lo': 'lao',
  2501. 'lt': 'lit',
  2502. 'lu': 'lub',
  2503. 'lv': 'lav',
  2504. 'mg': 'mlg',
  2505. 'mh': 'mah',
  2506. 'mi': 'mri',
  2507. 'mk': 'mkd',
  2508. 'ml': 'mal',
  2509. 'mn': 'mon',
  2510. 'mr': 'mar',
  2511. 'ms': 'msa',
  2512. 'mt': 'mlt',
  2513. 'my': 'mya',
  2514. 'na': 'nau',
  2515. 'nb': 'nob',
  2516. 'nd': 'nde',
  2517. 'ne': 'nep',
  2518. 'ng': 'ndo',
  2519. 'nl': 'nld',
  2520. 'nn': 'nno',
  2521. 'no': 'nor',
  2522. 'nr': 'nbl',
  2523. 'nv': 'nav',
  2524. 'ny': 'nya',
  2525. 'oc': 'oci',
  2526. 'oj': 'oji',
  2527. 'om': 'orm',
  2528. 'or': 'ori',
  2529. 'os': 'oss',
  2530. 'pa': 'pan',
  2531. 'pi': 'pli',
  2532. 'pl': 'pol',
  2533. 'ps': 'pus',
  2534. 'pt': 'por',
  2535. 'qu': 'que',
  2536. 'rm': 'roh',
  2537. 'rn': 'run',
  2538. 'ro': 'ron',
  2539. 'ru': 'rus',
  2540. 'rw': 'kin',
  2541. 'sa': 'san',
  2542. 'sc': 'srd',
  2543. 'sd': 'snd',
  2544. 'se': 'sme',
  2545. 'sg': 'sag',
  2546. 'si': 'sin',
  2547. 'sk': 'slk',
  2548. 'sl': 'slv',
  2549. 'sm': 'smo',
  2550. 'sn': 'sna',
  2551. 'so': 'som',
  2552. 'sq': 'sqi',
  2553. 'sr': 'srp',
  2554. 'ss': 'ssw',
  2555. 'st': 'sot',
  2556. 'su': 'sun',
  2557. 'sv': 'swe',
  2558. 'sw': 'swa',
  2559. 'ta': 'tam',
  2560. 'te': 'tel',
  2561. 'tg': 'tgk',
  2562. 'th': 'tha',
  2563. 'ti': 'tir',
  2564. 'tk': 'tuk',
  2565. 'tl': 'tgl',
  2566. 'tn': 'tsn',
  2567. 'to': 'ton',
  2568. 'tr': 'tur',
  2569. 'ts': 'tso',
  2570. 'tt': 'tat',
  2571. 'tw': 'twi',
  2572. 'ty': 'tah',
  2573. 'ug': 'uig',
  2574. 'uk': 'ukr',
  2575. 'ur': 'urd',
  2576. 'uz': 'uzb',
  2577. 've': 'ven',
  2578. 'vi': 'vie',
  2579. 'vo': 'vol',
  2580. 'wa': 'wln',
  2581. 'wo': 'wol',
  2582. 'xh': 'xho',
  2583. 'yi': 'yid',
  2584. 'ji': 'yid', # Replaced by yi in 1989 revision
  2585. 'yo': 'yor',
  2586. 'za': 'zha',
  2587. 'zh': 'zho',
  2588. 'zu': 'zul',
  2589. }
  2590. @classmethod
  2591. def short2long(cls, code):
  2592. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  2593. return cls._lang_map.get(code[:2])
  2594. @classmethod
  2595. def long2short(cls, code):
  2596. """Convert language code from ISO 639-2/T to ISO 639-1"""
  2597. for short_name, long_name in cls._lang_map.items():
  2598. if long_name == code:
  2599. return short_name
  2600. class ISO3166Utils(object):
  2601. # From http://data.okfn.org/data/core/country-list
  2602. _country_map = {
  2603. 'AF': 'Afghanistan',
  2604. 'AX': 'Åland Islands',
  2605. 'AL': 'Albania',
  2606. 'DZ': 'Algeria',
  2607. 'AS': 'American Samoa',
  2608. 'AD': 'Andorra',
  2609. 'AO': 'Angola',
  2610. 'AI': 'Anguilla',
  2611. 'AQ': 'Antarctica',
  2612. 'AG': 'Antigua and Barbuda',
  2613. 'AR': 'Argentina',
  2614. 'AM': 'Armenia',
  2615. 'AW': 'Aruba',
  2616. 'AU': 'Australia',
  2617. 'AT': 'Austria',
  2618. 'AZ': 'Azerbaijan',
  2619. 'BS': 'Bahamas',
  2620. 'BH': 'Bahrain',
  2621. 'BD': 'Bangladesh',
  2622. 'BB': 'Barbados',
  2623. 'BY': 'Belarus',
  2624. 'BE': 'Belgium',
  2625. 'BZ': 'Belize',
  2626. 'BJ': 'Benin',
  2627. 'BM': 'Bermuda',
  2628. 'BT': 'Bhutan',
  2629. 'BO': 'Bolivia, Plurinational State of',
  2630. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  2631. 'BA': 'Bosnia and Herzegovina',
  2632. 'BW': 'Botswana',
  2633. 'BV': 'Bouvet Island',
  2634. 'BR': 'Brazil',
  2635. 'IO': 'British Indian Ocean Territory',
  2636. 'BN': 'Brunei Darussalam',
  2637. 'BG': 'Bulgaria',
  2638. 'BF': 'Burkina Faso',
  2639. 'BI': 'Burundi',
  2640. 'KH': 'Cambodia',
  2641. 'CM': 'Cameroon',
  2642. 'CA': 'Canada',
  2643. 'CV': 'Cape Verde',
  2644. 'KY': 'Cayman Islands',
  2645. 'CF': 'Central African Republic',
  2646. 'TD': 'Chad',
  2647. 'CL': 'Chile',
  2648. 'CN': 'China',
  2649. 'CX': 'Christmas Island',
  2650. 'CC': 'Cocos (Keeling) Islands',
  2651. 'CO': 'Colombia',
  2652. 'KM': 'Comoros',
  2653. 'CG': 'Congo',
  2654. 'CD': 'Congo, the Democratic Republic of the',
  2655. 'CK': 'Cook Islands',
  2656. 'CR': 'Costa Rica',
  2657. 'CI': 'Côte d\'Ivoire',
  2658. 'HR': 'Croatia',
  2659. 'CU': 'Cuba',
  2660. 'CW': 'Curaçao',
  2661. 'CY': 'Cyprus',
  2662. 'CZ': 'Czech Republic',
  2663. 'DK': 'Denmark',
  2664. 'DJ': 'Djibouti',
  2665. 'DM': 'Dominica',
  2666. 'DO': 'Dominican Republic',
  2667. 'EC': 'Ecuador',
  2668. 'EG': 'Egypt',
  2669. 'SV': 'El Salvador',
  2670. 'GQ': 'Equatorial Guinea',
  2671. 'ER': 'Eritrea',
  2672. 'EE': 'Estonia',
  2673. 'ET': 'Ethiopia',
  2674. 'FK': 'Falkland Islands (Malvinas)',
  2675. 'FO': 'Faroe Islands',
  2676. 'FJ': 'Fiji',
  2677. 'FI': 'Finland',
  2678. 'FR': 'France',
  2679. 'GF': 'French Guiana',
  2680. 'PF': 'French Polynesia',
  2681. 'TF': 'French Southern Territories',
  2682. 'GA': 'Gabon',
  2683. 'GM': 'Gambia',
  2684. 'GE': 'Georgia',
  2685. 'DE': 'Germany',
  2686. 'GH': 'Ghana',
  2687. 'GI': 'Gibraltar',
  2688. 'GR': 'Greece',
  2689. 'GL': 'Greenland',
  2690. 'GD': 'Grenada',
  2691. 'GP': 'Guadeloupe',
  2692. 'GU': 'Guam',
  2693. 'GT': 'Guatemala',
  2694. 'GG': 'Guernsey',
  2695. 'GN': 'Guinea',
  2696. 'GW': 'Guinea-Bissau',
  2697. 'GY': 'Guyana',
  2698. 'HT': 'Haiti',
  2699. 'HM': 'Heard Island and McDonald Islands',
  2700. 'VA': 'Holy See (Vatican City State)',
  2701. 'HN': 'Honduras',
  2702. 'HK': 'Hong Kong',
  2703. 'HU': 'Hungary',
  2704. 'IS': 'Iceland',
  2705. 'IN': 'India',
  2706. 'ID': 'Indonesia',
  2707. 'IR': 'Iran, Islamic Republic of',
  2708. 'IQ': 'Iraq',
  2709. 'IE': 'Ireland',
  2710. 'IM': 'Isle of Man',
  2711. 'IL': 'Israel',
  2712. 'IT': 'Italy',
  2713. 'JM': 'Jamaica',
  2714. 'JP': 'Japan',
  2715. 'JE': 'Jersey',
  2716. 'JO': 'Jordan',
  2717. 'KZ': 'Kazakhstan',
  2718. 'KE': 'Kenya',
  2719. 'KI': 'Kiribati',
  2720. 'KP': 'Korea, Democratic People\'s Republic of',
  2721. 'KR': 'Korea, Republic of',
  2722. 'KW': 'Kuwait',
  2723. 'KG': 'Kyrgyzstan',
  2724. 'LA': 'Lao People\'s Democratic Republic',
  2725. 'LV': 'Latvia',
  2726. 'LB': 'Lebanon',
  2727. 'LS': 'Lesotho',
  2728. 'LR': 'Liberia',
  2729. 'LY': 'Libya',
  2730. 'LI': 'Liechtenstein',
  2731. 'LT': 'Lithuania',
  2732. 'LU': 'Luxembourg',
  2733. 'MO': 'Macao',
  2734. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  2735. 'MG': 'Madagascar',
  2736. 'MW': 'Malawi',
  2737. 'MY': 'Malaysia',
  2738. 'MV': 'Maldives',
  2739. 'ML': 'Mali',
  2740. 'MT': 'Malta',
  2741. 'MH': 'Marshall Islands',
  2742. 'MQ': 'Martinique',
  2743. 'MR': 'Mauritania',
  2744. 'MU': 'Mauritius',
  2745. 'YT': 'Mayotte',
  2746. 'MX': 'Mexico',
  2747. 'FM': 'Micronesia, Federated States of',
  2748. 'MD': 'Moldova, Republic of',
  2749. 'MC': 'Monaco',
  2750. 'MN': 'Mongolia',
  2751. 'ME': 'Montenegro',
  2752. 'MS': 'Montserrat',
  2753. 'MA': 'Morocco',
  2754. 'MZ': 'Mozambique',
  2755. 'MM': 'Myanmar',
  2756. 'NA': 'Namibia',
  2757. 'NR': 'Nauru',
  2758. 'NP': 'Nepal',
  2759. 'NL': 'Netherlands',
  2760. 'NC': 'New Caledonia',
  2761. 'NZ': 'New Zealand',
  2762. 'NI': 'Nicaragua',
  2763. 'NE': 'Niger',
  2764. 'NG': 'Nigeria',
  2765. 'NU': 'Niue',
  2766. 'NF': 'Norfolk Island',
  2767. 'MP': 'Northern Mariana Islands',
  2768. 'NO': 'Norway',
  2769. 'OM': 'Oman',
  2770. 'PK': 'Pakistan',
  2771. 'PW': 'Palau',
  2772. 'PS': 'Palestine, State of',
  2773. 'PA': 'Panama',
  2774. 'PG': 'Papua New Guinea',
  2775. 'PY': 'Paraguay',
  2776. 'PE': 'Peru',
  2777. 'PH': 'Philippines',
  2778. 'PN': 'Pitcairn',
  2779. 'PL': 'Poland',
  2780. 'PT': 'Portugal',
  2781. 'PR': 'Puerto Rico',
  2782. 'QA': 'Qatar',
  2783. 'RE': 'Réunion',
  2784. 'RO': 'Romania',
  2785. 'RU': 'Russian Federation',
  2786. 'RW': 'Rwanda',
  2787. 'BL': 'Saint Barthélemy',
  2788. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  2789. 'KN': 'Saint Kitts and Nevis',
  2790. 'LC': 'Saint Lucia',
  2791. 'MF': 'Saint Martin (French part)',
  2792. 'PM': 'Saint Pierre and Miquelon',
  2793. 'VC': 'Saint Vincent and the Grenadines',
  2794. 'WS': 'Samoa',
  2795. 'SM': 'San Marino',
  2796. 'ST': 'Sao Tome and Principe',
  2797. 'SA': 'Saudi Arabia',
  2798. 'SN': 'Senegal',
  2799. 'RS': 'Serbia',
  2800. 'SC': 'Seychelles',
  2801. 'SL': 'Sierra Leone',
  2802. 'SG': 'Singapore',
  2803. 'SX': 'Sint Maarten (Dutch part)',
  2804. 'SK': 'Slovakia',
  2805. 'SI': 'Slovenia',
  2806. 'SB': 'Solomon Islands',
  2807. 'SO': 'Somalia',
  2808. 'ZA': 'South Africa',
  2809. 'GS': 'South Georgia and the South Sandwich Islands',
  2810. 'SS': 'South Sudan',
  2811. 'ES': 'Spain',
  2812. 'LK': 'Sri Lanka',
  2813. 'SD': 'Sudan',
  2814. 'SR': 'Suriname',
  2815. 'SJ': 'Svalbard and Jan Mayen',
  2816. 'SZ': 'Swaziland',
  2817. 'SE': 'Sweden',
  2818. 'CH': 'Switzerland',
  2819. 'SY': 'Syrian Arab Republic',
  2820. 'TW': 'Taiwan, Province of China',
  2821. 'TJ': 'Tajikistan',
  2822. 'TZ': 'Tanzania, United Republic of',
  2823. 'TH': 'Thailand',
  2824. 'TL': 'Timor-Leste',
  2825. 'TG': 'Togo',
  2826. 'TK': 'Tokelau',
  2827. 'TO': 'Tonga',
  2828. 'TT': 'Trinidad and Tobago',
  2829. 'TN': 'Tunisia',
  2830. 'TR': 'Turkey',
  2831. 'TM': 'Turkmenistan',
  2832. 'TC': 'Turks and Caicos Islands',
  2833. 'TV': 'Tuvalu',
  2834. 'UG': 'Uganda',
  2835. 'UA': 'Ukraine',
  2836. 'AE': 'United Arab Emirates',
  2837. 'GB': 'United Kingdom',
  2838. 'US': 'United States',
  2839. 'UM': 'United States Minor Outlying Islands',
  2840. 'UY': 'Uruguay',
  2841. 'UZ': 'Uzbekistan',
  2842. 'VU': 'Vanuatu',
  2843. 'VE': 'Venezuela, Bolivarian Republic of',
  2844. 'VN': 'Viet Nam',
  2845. 'VG': 'Virgin Islands, British',
  2846. 'VI': 'Virgin Islands, U.S.',
  2847. 'WF': 'Wallis and Futuna',
  2848. 'EH': 'Western Sahara',
  2849. 'YE': 'Yemen',
  2850. 'ZM': 'Zambia',
  2851. 'ZW': 'Zimbabwe',
  2852. }
  2853. @classmethod
  2854. def short2full(cls, code):
  2855. """Convert an ISO 3166-2 country code to the corresponding full name"""
  2856. return cls._country_map.get(code.upper())
  2857. class GeoUtils(object):
  2858. # Major IPv4 address blocks per country
  2859. _country_ip_map = {
  2860. 'AD': '85.94.160.0/19',
  2861. 'AE': '94.200.0.0/13',
  2862. 'AF': '149.54.0.0/17',
  2863. 'AG': '209.59.64.0/18',
  2864. 'AI': '204.14.248.0/21',
  2865. 'AL': '46.99.0.0/16',
  2866. 'AM': '46.70.0.0/15',
  2867. 'AO': '105.168.0.0/13',
  2868. 'AP': '159.117.192.0/21',
  2869. 'AR': '181.0.0.0/12',
  2870. 'AS': '202.70.112.0/20',
  2871. 'AT': '84.112.0.0/13',
  2872. 'AU': '1.128.0.0/11',
  2873. 'AW': '181.41.0.0/18',
  2874. 'AZ': '5.191.0.0/16',
  2875. 'BA': '31.176.128.0/17',
  2876. 'BB': '65.48.128.0/17',
  2877. 'BD': '114.130.0.0/16',
  2878. 'BE': '57.0.0.0/8',
  2879. 'BF': '129.45.128.0/17',
  2880. 'BG': '95.42.0.0/15',
  2881. 'BH': '37.131.0.0/17',
  2882. 'BI': '154.117.192.0/18',
  2883. 'BJ': '137.255.0.0/16',
  2884. 'BL': '192.131.134.0/24',
  2885. 'BM': '196.12.64.0/18',
  2886. 'BN': '156.31.0.0/16',
  2887. 'BO': '161.56.0.0/16',
  2888. 'BQ': '161.0.80.0/20',
  2889. 'BR': '152.240.0.0/12',
  2890. 'BS': '24.51.64.0/18',
  2891. 'BT': '119.2.96.0/19',
  2892. 'BW': '168.167.0.0/16',
  2893. 'BY': '178.120.0.0/13',
  2894. 'BZ': '179.42.192.0/18',
  2895. 'CA': '99.224.0.0/11',
  2896. 'CD': '41.243.0.0/16',
  2897. 'CF': '196.32.200.0/21',
  2898. 'CG': '197.214.128.0/17',
  2899. 'CH': '85.0.0.0/13',
  2900. 'CI': '154.232.0.0/14',
  2901. 'CK': '202.65.32.0/19',
  2902. 'CL': '152.172.0.0/14',
  2903. 'CM': '165.210.0.0/15',
  2904. 'CN': '36.128.0.0/10',
  2905. 'CO': '181.240.0.0/12',
  2906. 'CR': '201.192.0.0/12',
  2907. 'CU': '152.206.0.0/15',
  2908. 'CV': '165.90.96.0/19',
  2909. 'CW': '190.88.128.0/17',
  2910. 'CY': '46.198.0.0/15',
  2911. 'CZ': '88.100.0.0/14',
  2912. 'DE': '53.0.0.0/8',
  2913. 'DJ': '197.241.0.0/17',
  2914. 'DK': '87.48.0.0/12',
  2915. 'DM': '192.243.48.0/20',
  2916. 'DO': '152.166.0.0/15',
  2917. 'DZ': '41.96.0.0/12',
  2918. 'EC': '186.68.0.0/15',
  2919. 'EE': '90.190.0.0/15',
  2920. 'EG': '156.160.0.0/11',
  2921. 'ER': '196.200.96.0/20',
  2922. 'ES': '88.0.0.0/11',
  2923. 'ET': '196.188.0.0/14',
  2924. 'EU': '2.16.0.0/13',
  2925. 'FI': '91.152.0.0/13',
  2926. 'FJ': '144.120.0.0/16',
  2927. 'FM': '119.252.112.0/20',
  2928. 'FO': '88.85.32.0/19',
  2929. 'FR': '90.0.0.0/9',
  2930. 'GA': '41.158.0.0/15',
  2931. 'GB': '25.0.0.0/8',
  2932. 'GD': '74.122.88.0/21',
  2933. 'GE': '31.146.0.0/16',
  2934. 'GF': '161.22.64.0/18',
  2935. 'GG': '62.68.160.0/19',
  2936. 'GH': '45.208.0.0/14',
  2937. 'GI': '85.115.128.0/19',
  2938. 'GL': '88.83.0.0/19',
  2939. 'GM': '160.182.0.0/15',
  2940. 'GN': '197.149.192.0/18',
  2941. 'GP': '104.250.0.0/19',
  2942. 'GQ': '105.235.224.0/20',
  2943. 'GR': '94.64.0.0/13',
  2944. 'GT': '168.234.0.0/16',
  2945. 'GU': '168.123.0.0/16',
  2946. 'GW': '197.214.80.0/20',
  2947. 'GY': '181.41.64.0/18',
  2948. 'HK': '113.252.0.0/14',
  2949. 'HN': '181.210.0.0/16',
  2950. 'HR': '93.136.0.0/13',
  2951. 'HT': '148.102.128.0/17',
  2952. 'HU': '84.0.0.0/14',
  2953. 'ID': '39.192.0.0/10',
  2954. 'IE': '87.32.0.0/12',
  2955. 'IL': '79.176.0.0/13',
  2956. 'IM': '5.62.80.0/20',
  2957. 'IN': '117.192.0.0/10',
  2958. 'IO': '203.83.48.0/21',
  2959. 'IQ': '37.236.0.0/14',
  2960. 'IR': '2.176.0.0/12',
  2961. 'IS': '82.221.0.0/16',
  2962. 'IT': '79.0.0.0/10',
  2963. 'JE': '87.244.64.0/18',
  2964. 'JM': '72.27.0.0/17',
  2965. 'JO': '176.29.0.0/16',
  2966. 'JP': '126.0.0.0/8',
  2967. 'KE': '105.48.0.0/12',
  2968. 'KG': '158.181.128.0/17',
  2969. 'KH': '36.37.128.0/17',
  2970. 'KI': '103.25.140.0/22',
  2971. 'KM': '197.255.224.0/20',
  2972. 'KN': '198.32.32.0/19',
  2973. 'KP': '175.45.176.0/22',
  2974. 'KR': '175.192.0.0/10',
  2975. 'KW': '37.36.0.0/14',
  2976. 'KY': '64.96.0.0/15',
  2977. 'KZ': '2.72.0.0/13',
  2978. 'LA': '115.84.64.0/18',
  2979. 'LB': '178.135.0.0/16',
  2980. 'LC': '192.147.231.0/24',
  2981. 'LI': '82.117.0.0/19',
  2982. 'LK': '112.134.0.0/15',
  2983. 'LR': '41.86.0.0/19',
  2984. 'LS': '129.232.0.0/17',
  2985. 'LT': '78.56.0.0/13',
  2986. 'LU': '188.42.0.0/16',
  2987. 'LV': '46.109.0.0/16',
  2988. 'LY': '41.252.0.0/14',
  2989. 'MA': '105.128.0.0/11',
  2990. 'MC': '88.209.64.0/18',
  2991. 'MD': '37.246.0.0/16',
  2992. 'ME': '178.175.0.0/17',
  2993. 'MF': '74.112.232.0/21',
  2994. 'MG': '154.126.0.0/17',
  2995. 'MH': '117.103.88.0/21',
  2996. 'MK': '77.28.0.0/15',
  2997. 'ML': '154.118.128.0/18',
  2998. 'MM': '37.111.0.0/17',
  2999. 'MN': '49.0.128.0/17',
  3000. 'MO': '60.246.0.0/16',
  3001. 'MP': '202.88.64.0/20',
  3002. 'MQ': '109.203.224.0/19',
  3003. 'MR': '41.188.64.0/18',
  3004. 'MS': '208.90.112.0/22',
  3005. 'MT': '46.11.0.0/16',
  3006. 'MU': '105.16.0.0/12',
  3007. 'MV': '27.114.128.0/18',
  3008. 'MW': '105.234.0.0/16',
  3009. 'MX': '187.192.0.0/11',
  3010. 'MY': '175.136.0.0/13',
  3011. 'MZ': '197.218.0.0/15',
  3012. 'NA': '41.182.0.0/16',
  3013. 'NC': '101.101.0.0/18',
  3014. 'NE': '197.214.0.0/18',
  3015. 'NF': '203.17.240.0/22',
  3016. 'NG': '105.112.0.0/12',
  3017. 'NI': '186.76.0.0/15',
  3018. 'NL': '145.96.0.0/11',
  3019. 'NO': '84.208.0.0/13',
  3020. 'NP': '36.252.0.0/15',
  3021. 'NR': '203.98.224.0/19',
  3022. 'NU': '49.156.48.0/22',
  3023. 'NZ': '49.224.0.0/14',
  3024. 'OM': '5.36.0.0/15',
  3025. 'PA': '186.72.0.0/15',
  3026. 'PE': '186.160.0.0/14',
  3027. 'PF': '123.50.64.0/18',
  3028. 'PG': '124.240.192.0/19',
  3029. 'PH': '49.144.0.0/13',
  3030. 'PK': '39.32.0.0/11',
  3031. 'PL': '83.0.0.0/11',
  3032. 'PM': '70.36.0.0/20',
  3033. 'PR': '66.50.0.0/16',
  3034. 'PS': '188.161.0.0/16',
  3035. 'PT': '85.240.0.0/13',
  3036. 'PW': '202.124.224.0/20',
  3037. 'PY': '181.120.0.0/14',
  3038. 'QA': '37.210.0.0/15',
  3039. 'RE': '139.26.0.0/16',
  3040. 'RO': '79.112.0.0/13',
  3041. 'RS': '178.220.0.0/14',
  3042. 'RU': '5.136.0.0/13',
  3043. 'RW': '105.178.0.0/15',
  3044. 'SA': '188.48.0.0/13',
  3045. 'SB': '202.1.160.0/19',
  3046. 'SC': '154.192.0.0/11',
  3047. 'SD': '154.96.0.0/13',
  3048. 'SE': '78.64.0.0/12',
  3049. 'SG': '152.56.0.0/14',
  3050. 'SI': '188.196.0.0/14',
  3051. 'SK': '78.98.0.0/15',
  3052. 'SL': '197.215.0.0/17',
  3053. 'SM': '89.186.32.0/19',
  3054. 'SN': '41.82.0.0/15',
  3055. 'SO': '197.220.64.0/19',
  3056. 'SR': '186.179.128.0/17',
  3057. 'SS': '105.235.208.0/21',
  3058. 'ST': '197.159.160.0/19',
  3059. 'SV': '168.243.0.0/16',
  3060. 'SX': '190.102.0.0/20',
  3061. 'SY': '5.0.0.0/16',
  3062. 'SZ': '41.84.224.0/19',
  3063. 'TC': '65.255.48.0/20',
  3064. 'TD': '154.68.128.0/19',
  3065. 'TG': '196.168.0.0/14',
  3066. 'TH': '171.96.0.0/13',
  3067. 'TJ': '85.9.128.0/18',
  3068. 'TK': '27.96.24.0/21',
  3069. 'TL': '180.189.160.0/20',
  3070. 'TM': '95.85.96.0/19',
  3071. 'TN': '197.0.0.0/11',
  3072. 'TO': '175.176.144.0/21',
  3073. 'TR': '78.160.0.0/11',
  3074. 'TT': '186.44.0.0/15',
  3075. 'TV': '202.2.96.0/19',
  3076. 'TW': '120.96.0.0/11',
  3077. 'TZ': '156.156.0.0/14',
  3078. 'UA': '93.72.0.0/13',
  3079. 'UG': '154.224.0.0/13',
  3080. 'US': '3.0.0.0/8',
  3081. 'UY': '167.56.0.0/13',
  3082. 'UZ': '82.215.64.0/18',
  3083. 'VA': '212.77.0.0/19',
  3084. 'VC': '24.92.144.0/20',
  3085. 'VE': '186.88.0.0/13',
  3086. 'VG': '172.103.64.0/18',
  3087. 'VI': '146.226.0.0/16',
  3088. 'VN': '14.160.0.0/11',
  3089. 'VU': '202.80.32.0/20',
  3090. 'WF': '117.20.32.0/21',
  3091. 'WS': '202.4.32.0/19',
  3092. 'YE': '134.35.0.0/16',
  3093. 'YT': '41.242.116.0/22',
  3094. 'ZA': '41.0.0.0/11',
  3095. 'ZM': '165.56.0.0/13',
  3096. 'ZW': '41.85.192.0/19',
  3097. }
  3098. @classmethod
  3099. def random_ipv4(cls, code_or_block):
  3100. if len(code_or_block) == 2:
  3101. block = cls._country_ip_map.get(code_or_block.upper())
  3102. if not block:
  3103. return None
  3104. else:
  3105. block = code_or_block
  3106. addr, preflen = block.split('/')
  3107. addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
  3108. addr_max = addr_min | (0xffffffff >> int(preflen))
  3109. return compat_str(socket.inet_ntoa(
  3110. compat_struct_pack('!L', random.randint(addr_min, addr_max))))
  3111. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  3112. def __init__(self, proxies=None):
  3113. # Set default handlers
  3114. for type in ('http', 'https'):
  3115. setattr(self, '%s_open' % type,
  3116. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  3117. meth(r, proxy, type))
  3118. compat_urllib_request.ProxyHandler.__init__(self, proxies)
  3119. def proxy_open(self, req, proxy, type):
  3120. req_proxy = req.headers.get('Ytdl-request-proxy')
  3121. if req_proxy is not None:
  3122. proxy = req_proxy
  3123. del req.headers['Ytdl-request-proxy']
  3124. if proxy == '__noproxy__':
  3125. return None # No Proxy
  3126. if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  3127. req.add_header('Ytdl-socks-proxy', proxy)
  3128. # youtube-dl's http/https handlers do wrapping the socket with socks
  3129. return None
  3130. return compat_urllib_request.ProxyHandler.proxy_open(
  3131. self, req, proxy, type)
  3132. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  3133. # released into Public Domain
  3134. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  3135. def long_to_bytes(n, blocksize=0):
  3136. """long_to_bytes(n:long, blocksize:int) : string
  3137. Convert a long integer to a byte string.
  3138. If optional blocksize is given and greater than zero, pad the front of the
  3139. byte string with binary zeros so that the length is a multiple of
  3140. blocksize.
  3141. """
  3142. # after much testing, this algorithm was deemed to be the fastest
  3143. s = b''
  3144. n = int(n)
  3145. while n > 0:
  3146. s = compat_struct_pack('>I', n & 0xffffffff) + s
  3147. n = n >> 32
  3148. # strip off leading zeros
  3149. for i in range(len(s)):
  3150. if s[i] != b'\000'[0]:
  3151. break
  3152. else:
  3153. # only happens when n == 0
  3154. s = b'\000'
  3155. i = 0
  3156. s = s[i:]
  3157. # add back some pad bytes. this could be done more efficiently w.r.t. the
  3158. # de-padding being done above, but sigh...
  3159. if blocksize > 0 and len(s) % blocksize:
  3160. s = (blocksize - len(s) % blocksize) * b'\000' + s
  3161. return s
  3162. def bytes_to_long(s):
  3163. """bytes_to_long(string) : long
  3164. Convert a byte string to a long integer.
  3165. This is (essentially) the inverse of long_to_bytes().
  3166. """
  3167. acc = 0
  3168. length = len(s)
  3169. if length % 4:
  3170. extra = (4 - length % 4)
  3171. s = b'\000' * extra + s
  3172. length = length + extra
  3173. for i in range(0, length, 4):
  3174. acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
  3175. return acc
  3176. def ohdave_rsa_encrypt(data, exponent, modulus):
  3177. '''
  3178. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  3179. Input:
  3180. data: data to encrypt, bytes-like object
  3181. exponent, modulus: parameter e and N of RSA algorithm, both integer
  3182. Output: hex string of encrypted data
  3183. Limitation: supports one block encryption only
  3184. '''
  3185. payload = int(binascii.hexlify(data[::-1]), 16)
  3186. encrypted = pow(payload, exponent, modulus)
  3187. return '%x' % encrypted
  3188. def pkcs1pad(data, length):
  3189. """
  3190. Padding input data with PKCS#1 scheme
  3191. @param {int[]} data input data
  3192. @param {int} length target length
  3193. @returns {int[]} padded data
  3194. """
  3195. if len(data) > length - 11:
  3196. raise ValueError('Input data too long for PKCS#1 padding')
  3197. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  3198. return [0, 2] + pseudo_random + [0] + data
  3199. def encode_base_n(num, n, table=None):
  3200. FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  3201. if not table:
  3202. table = FULL_TABLE[:n]
  3203. if n > len(table):
  3204. raise ValueError('base %d exceeds table length %d' % (n, len(table)))
  3205. if num == 0:
  3206. return table[0]
  3207. ret = ''
  3208. while num:
  3209. ret = table[num % n] + ret
  3210. num = num // n
  3211. return ret
  3212. def decode_packed_codes(code):
  3213. mobj = re.search(PACKED_CODES_RE, code)
  3214. obfucasted_code, base, count, symbols = mobj.groups()
  3215. base = int(base)
  3216. count = int(count)
  3217. symbols = symbols.split('|')
  3218. symbol_table = {}
  3219. while count:
  3220. count -= 1
  3221. base_n_count = encode_base_n(count, base)
  3222. symbol_table[base_n_count] = symbols[count] or base_n_count
  3223. return re.sub(
  3224. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  3225. obfucasted_code)
  3226. def parse_m3u8_attributes(attrib):
  3227. info = {}
  3228. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  3229. if val.startswith('"'):
  3230. val = val[1:-1]
  3231. info[key] = val
  3232. return info
  3233. def urshift(val, n):
  3234. return val >> n if val >= 0 else (val + 0x100000000) >> n
  3235. # Based on png2str() written by @gdkchan and improved by @yokrysty
  3236. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  3237. def decode_png(png_data):
  3238. # Reference: https://www.w3.org/TR/PNG/
  3239. header = png_data[8:]
  3240. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  3241. raise IOError('Not a valid PNG file.')
  3242. int_map = {1: '>B', 2: '>H', 4: '>I'}
  3243. unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
  3244. chunks = []
  3245. while header:
  3246. length = unpack_integer(header[:4])
  3247. header = header[4:]
  3248. chunk_type = header[:4]
  3249. header = header[4:]
  3250. chunk_data = header[:length]
  3251. header = header[length:]
  3252. header = header[4:] # Skip CRC
  3253. chunks.append({
  3254. 'type': chunk_type,
  3255. 'length': length,
  3256. 'data': chunk_data
  3257. })
  3258. ihdr = chunks[0]['data']
  3259. width = unpack_integer(ihdr[:4])
  3260. height = unpack_integer(ihdr[4:8])
  3261. idat = b''
  3262. for chunk in chunks:
  3263. if chunk['type'] == b'IDAT':
  3264. idat += chunk['data']
  3265. if not idat:
  3266. raise IOError('Unable to read PNG data.')
  3267. decompressed_data = bytearray(zlib.decompress(idat))
  3268. stride = width * 3
  3269. pixels = []
  3270. def _get_pixel(idx):
  3271. x = idx % stride
  3272. y = idx // stride
  3273. return pixels[y][x]
  3274. for y in range(height):
  3275. basePos = y * (1 + stride)
  3276. filter_type = decompressed_data[basePos]
  3277. current_row = []
  3278. pixels.append(current_row)
  3279. for x in range(stride):
  3280. color = decompressed_data[1 + basePos + x]
  3281. basex = y * stride + x
  3282. left = 0
  3283. up = 0
  3284. if x > 2:
  3285. left = _get_pixel(basex - 3)
  3286. if y > 0:
  3287. up = _get_pixel(basex - stride)
  3288. if filter_type == 1: # Sub
  3289. color = (color + left) & 0xff
  3290. elif filter_type == 2: # Up
  3291. color = (color + up) & 0xff
  3292. elif filter_type == 3: # Average
  3293. color = (color + ((left + up) >> 1)) & 0xff
  3294. elif filter_type == 4: # Paeth
  3295. a = left
  3296. b = up
  3297. c = 0
  3298. if x > 2 and y > 0:
  3299. c = _get_pixel(basex - stride - 3)
  3300. p = a + b - c
  3301. pa = abs(p - a)
  3302. pb = abs(p - b)
  3303. pc = abs(p - c)
  3304. if pa <= pb and pa <= pc:
  3305. color = (color + a) & 0xff
  3306. elif pb <= pc:
  3307. color = (color + b) & 0xff
  3308. else:
  3309. color = (color + c) & 0xff
  3310. current_row.append(color)
  3311. return width, height, pixels
  3312. def write_xattr(path, key, value):
  3313. # This mess below finds the best xattr tool for the job
  3314. try:
  3315. # try the pyxattr module...
  3316. import xattr
  3317. if hasattr(xattr, 'set'): # pyxattr
  3318. # Unicode arguments are not supported in python-pyxattr until
  3319. # version 0.5.0
  3320. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  3321. pyxattr_required_version = '0.5.0'
  3322. if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
  3323. # TODO: fallback to CLI tools
  3324. raise XAttrUnavailableError(
  3325. 'python-pyxattr is detected but is too old. '
  3326. 'youtube-dl requires %s or above while your version is %s. '
  3327. 'Falling back to other xattr implementations' % (
  3328. pyxattr_required_version, xattr.__version__))
  3329. setxattr = xattr.set
  3330. else: # xattr
  3331. setxattr = xattr.setxattr
  3332. try:
  3333. setxattr(path, key, value)
  3334. except EnvironmentError as e:
  3335. raise XAttrMetadataError(e.errno, e.strerror)
  3336. except ImportError:
  3337. if compat_os_name == 'nt':
  3338. # Write xattrs to NTFS Alternate Data Streams:
  3339. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  3340. assert ':' not in key
  3341. assert os.path.exists(path)
  3342. ads_fn = path + ':' + key
  3343. try:
  3344. with open(ads_fn, 'wb') as f:
  3345. f.write(value)
  3346. except EnvironmentError as e:
  3347. raise XAttrMetadataError(e.errno, e.strerror)
  3348. else:
  3349. user_has_setfattr = check_executable('setfattr', ['--version'])
  3350. user_has_xattr = check_executable('xattr', ['-h'])
  3351. if user_has_setfattr or user_has_xattr:
  3352. value = value.decode('utf-8')
  3353. if user_has_setfattr:
  3354. executable = 'setfattr'
  3355. opts = ['-n', key, '-v', value]
  3356. elif user_has_xattr:
  3357. executable = 'xattr'
  3358. opts = ['-w', key, value]
  3359. cmd = ([encodeFilename(executable, True)] +
  3360. [encodeArgument(o) for o in opts] +
  3361. [encodeFilename(path, True)])
  3362. try:
  3363. p = subprocess.Popen(
  3364. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  3365. except EnvironmentError as e:
  3366. raise XAttrMetadataError(e.errno, e.strerror)
  3367. stdout, stderr = p.communicate()
  3368. stderr = stderr.decode('utf-8', 'replace')
  3369. if p.returncode != 0:
  3370. raise XAttrMetadataError(p.returncode, stderr)
  3371. else:
  3372. # On Unix, and can't find pyxattr, setfattr, or xattr.
  3373. if sys.platform.startswith('linux'):
  3374. raise XAttrUnavailableError(
  3375. "Couldn't find a tool to set the xattrs. "
  3376. "Install either the python 'pyxattr' or 'xattr' "
  3377. "modules, or the GNU 'attr' package "
  3378. "(which contains the 'setfattr' tool).")
  3379. else:
  3380. raise XAttrUnavailableError(
  3381. "Couldn't find a tool to set the xattrs. "
  3382. "Install either the python 'xattr' module, "
  3383. "or the 'xattr' binary.")
  3384. def random_birthday(year_field, month_field, day_field):
  3385. start_date = datetime.date(1950, 1, 1)
  3386. end_date = datetime.date(1995, 12, 31)
  3387. offset = random.randint(0, (end_date - start_date).days)
  3388. random_date = start_date + datetime.timedelta(offset)
  3389. return {
  3390. year_field: str(random_date.year),
  3391. month_field: str(random_date.month),
  3392. day_field: str(random_date.day),
  3393. }