Plex plugin to to play various online streams (mostly Latvian).

poolmanager.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. from __future__ import absolute_import
  2. import collections
  3. import functools
  4. import logging
  5. try: # Python 3
  6. from urllib.parse import urljoin
  7. except ImportError:
  8. from urlparse import urljoin
  9. from ._collections import RecentlyUsedContainer
  10. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
  11. from .connectionpool import port_by_scheme
  12. from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown
  13. from .request import RequestMethods
  14. from .util.url import parse_url
  15. from .util.retry import Retry
  16. __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
  17. log = logging.getLogger(__name__)
  18. SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
  19. 'ssl_version', 'ca_cert_dir')
  20. # The base fields to use when determining what pool to get a connection from;
  21. # these do not rely on the ``connection_pool_kw`` and can be determined by the
  22. # URL and potentially the ``urllib3.connection.port_by_scheme`` dictionary.
  23. #
  24. # All custom key schemes should include the fields in this key at a minimum.
  25. BasePoolKey = collections.namedtuple('BasePoolKey', ('scheme', 'host', 'port'))
  26. # The fields to use when determining what pool to get a HTTP and HTTPS
  27. # connection from. All additional fields must be present in the PoolManager's
  28. # ``connection_pool_kw`` instance variable.
  29. HTTPPoolKey = collections.namedtuple(
  30. 'HTTPPoolKey', BasePoolKey._fields + ('timeout', 'retries', 'strict',
  31. 'block', 'source_address')
  32. )
  33. HTTPSPoolKey = collections.namedtuple(
  34. 'HTTPSPoolKey', HTTPPoolKey._fields + SSL_KEYWORDS
  35. )
  36. def _default_key_normalizer(key_class, request_context):
  37. """
  38. Create a pool key of type ``key_class`` for a request.
  39. According to RFC 3986, both the scheme and host are case-insensitive.
  40. Therefore, this function normalizes both before constructing the pool
  41. key for an HTTPS request. If you wish to change this behaviour, provide
  42. alternate callables to ``key_fn_by_scheme``.
  43. :param key_class:
  44. The class to use when constructing the key. This should be a namedtuple
  45. with the ``scheme`` and ``host`` keys at a minimum.
  46. :param request_context:
  47. A dictionary-like object that contain the context for a request.
  48. It should contain a key for each field in the :class:`HTTPPoolKey`
  49. """
  50. context = {}
  51. for key in key_class._fields:
  52. context[key] = request_context.get(key)
  53. context['scheme'] = context['scheme'].lower()
  54. context['host'] = context['host'].lower()
  55. return key_class(**context)
  56. # A dictionary that maps a scheme to a callable that creates a pool key.
  57. # This can be used to alter the way pool keys are constructed, if desired.
  58. # Each PoolManager makes a copy of this dictionary so they can be configured
  59. # globally here, or individually on the instance.
  60. key_fn_by_scheme = {
  61. 'http': functools.partial(_default_key_normalizer, HTTPPoolKey),
  62. 'https': functools.partial(_default_key_normalizer, HTTPSPoolKey),
  63. }
  64. pool_classes_by_scheme = {
  65. 'http': HTTPConnectionPool,
  66. 'https': HTTPSConnectionPool,
  67. }
  68. class PoolManager(RequestMethods):
  69. """
  70. Allows for arbitrary requests while transparently keeping track of
  71. necessary connection pools for you.
  72. :param num_pools:
  73. Number of connection pools to cache before discarding the least
  74. recently used pool.
  75. :param headers:
  76. Headers to include with all requests, unless other headers are given
  77. explicitly.
  78. :param \**connection_pool_kw:
  79. Additional parameters are used to create fresh
  80. :class:`urllib3.connectionpool.ConnectionPool` instances.
  81. Example::
  82. >>> manager = PoolManager(num_pools=2)
  83. >>> r = manager.request('GET', 'http://google.com/')
  84. >>> r = manager.request('GET', 'http://google.com/mail')
  85. >>> r = manager.request('GET', 'http://yahoo.com/')
  86. >>> len(manager.pools)
  87. 2
  88. """
  89. proxy = None
  90. def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
  91. RequestMethods.__init__(self, headers)
  92. self.connection_pool_kw = connection_pool_kw
  93. self.pools = RecentlyUsedContainer(num_pools,
  94. dispose_func=lambda p: p.close())
  95. # Locally set the pool classes and keys so other PoolManagers can
  96. # override them.
  97. self.pool_classes_by_scheme = pool_classes_by_scheme
  98. self.key_fn_by_scheme = key_fn_by_scheme.copy()
  99. def __enter__(self):
  100. return self
  101. def __exit__(self, exc_type, exc_val, exc_tb):
  102. self.clear()
  103. # Return False to re-raise any potential exceptions
  104. return False
  105. def _new_pool(self, scheme, host, port):
  106. """
  107. Create a new :class:`ConnectionPool` based on host, port and scheme.
  108. This method is used to actually create the connection pools handed out
  109. by :meth:`connection_from_url` and companion methods. It is intended
  110. to be overridden for customization.
  111. """
  112. pool_cls = self.pool_classes_by_scheme[scheme]
  113. kwargs = self.connection_pool_kw
  114. if scheme == 'http':
  115. kwargs = self.connection_pool_kw.copy()
  116. for kw in SSL_KEYWORDS:
  117. kwargs.pop(kw, None)
  118. return pool_cls(host, port, **kwargs)
  119. def clear(self):
  120. """
  121. Empty our store of pools and direct them all to close.
  122. This will not affect in-flight connections, but they will not be
  123. re-used after completion.
  124. """
  125. self.pools.clear()
  126. def connection_from_host(self, host, port=None, scheme='http'):
  127. """
  128. Get a :class:`ConnectionPool` based on the host, port, and scheme.
  129. If ``port`` isn't given, it will be derived from the ``scheme`` using
  130. ``urllib3.connectionpool.port_by_scheme``.
  131. """
  132. if not host:
  133. raise LocationValueError("No host specified.")
  134. request_context = self.connection_pool_kw.copy()
  135. request_context['scheme'] = scheme or 'http'
  136. if not port:
  137. port = port_by_scheme.get(request_context['scheme'].lower(), 80)
  138. request_context['port'] = port
  139. request_context['host'] = host
  140. return self.connection_from_context(request_context)
  141. def connection_from_context(self, request_context):
  142. """
  143. Get a :class:`ConnectionPool` based on the request context.
  144. ``request_context`` must at least contain the ``scheme`` key and its
  145. value must be a key in ``key_fn_by_scheme`` instance variable.
  146. """
  147. scheme = request_context['scheme'].lower()
  148. pool_key_constructor = self.key_fn_by_scheme[scheme]
  149. pool_key = pool_key_constructor(request_context)
  150. return self.connection_from_pool_key(pool_key)
  151. def connection_from_pool_key(self, pool_key):
  152. """
  153. Get a :class:`ConnectionPool` based on the provided pool key.
  154. ``pool_key`` should be a namedtuple that only contains immutable
  155. objects. At a minimum it must have the ``scheme``, ``host``, and
  156. ``port`` fields.
  157. """
  158. with self.pools.lock:
  159. # If the scheme, host, or port doesn't match existing open
  160. # connections, open a new ConnectionPool.
  161. pool = self.pools.get(pool_key)
  162. if pool:
  163. return pool
  164. # Make a fresh ConnectionPool of the desired type
  165. pool = self._new_pool(pool_key.scheme, pool_key.host, pool_key.port)
  166. self.pools[pool_key] = pool
  167. return pool
  168. def connection_from_url(self, url):
  169. """
  170. Similar to :func:`urllib3.connectionpool.connection_from_url` but
  171. doesn't pass any additional parameters to the
  172. :class:`urllib3.connectionpool.ConnectionPool` constructor.
  173. Additional parameters are taken from the :class:`.PoolManager`
  174. constructor.
  175. """
  176. u = parse_url(url)
  177. return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  178. def urlopen(self, method, url, redirect=True, **kw):
  179. """
  180. Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
  181. with custom cross-host redirect logic and only sends the request-uri
  182. portion of the ``url``.
  183. The given ``url`` parameter must be absolute, such that an appropriate
  184. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  185. """
  186. u = parse_url(url)
  187. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  188. kw['assert_same_host'] = False
  189. kw['redirect'] = False
  190. if 'headers' not in kw:
  191. kw['headers'] = self.headers
  192. if self.proxy is not None and u.scheme == "http":
  193. response = conn.urlopen(method, url, **kw)
  194. else:
  195. response = conn.urlopen(method, u.request_uri, **kw)
  196. redirect_location = redirect and response.get_redirect_location()
  197. if not redirect_location:
  198. return response
  199. # Support relative URLs for redirecting.
  200. redirect_location = urljoin(url, redirect_location)
  201. # RFC 7231, Section 6.4.4
  202. if response.status == 303:
  203. method = 'GET'
  204. retries = kw.get('retries')
  205. if not isinstance(retries, Retry):
  206. retries = Retry.from_int(retries, redirect=redirect)
  207. try:
  208. retries = retries.increment(method, url, response=response, _pool=conn)
  209. except MaxRetryError:
  210. if retries.raise_on_redirect:
  211. raise
  212. return response
  213. kw['retries'] = retries
  214. kw['redirect'] = redirect
  215. log.info("Redirecting %s -> %s", url, redirect_location)
  216. return self.urlopen(method, redirect_location, **kw)
  217. class ProxyManager(PoolManager):
  218. """
  219. Behaves just like :class:`PoolManager`, but sends all requests through
  220. the defined proxy, using the CONNECT method for HTTPS URLs.
  221. :param proxy_url:
  222. The URL of the proxy to be used.
  223. :param proxy_headers:
  224. A dictionary contaning headers that will be sent to the proxy. In case
  225. of HTTP they are being sent with each request, while in the
  226. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  227. authentication.
  228. Example:
  229. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  230. >>> r1 = proxy.request('GET', 'http://google.com/')
  231. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  232. >>> len(proxy.pools)
  233. 1
  234. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  235. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  236. >>> len(proxy.pools)
  237. 3
  238. """
  239. def __init__(self, proxy_url, num_pools=10, headers=None,
  240. proxy_headers=None, **connection_pool_kw):
  241. if isinstance(proxy_url, HTTPConnectionPool):
  242. proxy_url = '%s://%s:%i' % (proxy_url.scheme, proxy_url.host,
  243. proxy_url.port)
  244. proxy = parse_url(proxy_url)
  245. if not proxy.port:
  246. port = port_by_scheme.get(proxy.scheme, 80)
  247. proxy = proxy._replace(port=port)
  248. if proxy.scheme not in ("http", "https"):
  249. raise ProxySchemeUnknown(proxy.scheme)
  250. self.proxy = proxy
  251. self.proxy_headers = proxy_headers or {}
  252. connection_pool_kw['_proxy'] = self.proxy
  253. connection_pool_kw['_proxy_headers'] = self.proxy_headers
  254. super(ProxyManager, self).__init__(
  255. num_pools, headers, **connection_pool_kw)
  256. def connection_from_host(self, host, port=None, scheme='http'):
  257. if scheme == "https":
  258. return super(ProxyManager, self).connection_from_host(
  259. host, port, scheme)
  260. return super(ProxyManager, self).connection_from_host(
  261. self.proxy.host, self.proxy.port, self.proxy.scheme)
  262. def _set_proxy_headers(self, url, headers=None):
  263. """
  264. Sets headers needed by proxies: specifically, the Accept and Host
  265. headers. Only sets headers not provided by the user.
  266. """
  267. headers_ = {'Accept': '*/*'}
  268. netloc = parse_url(url).netloc
  269. if netloc:
  270. headers_['Host'] = netloc
  271. if headers:
  272. headers_.update(headers)
  273. return headers_
  274. def urlopen(self, method, url, redirect=True, **kw):
  275. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  276. u = parse_url(url)
  277. if u.scheme == "http":
  278. # For proxied HTTPS requests, httplib sets the necessary headers
  279. # on the CONNECT to the proxy. For HTTP, we'll definitely
  280. # need to set 'Host' at the very least.
  281. headers = kw.get('headers', self.headers)
  282. kw['headers'] = self._set_proxy_headers(url, headers)
  283. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  284. def proxy_from_url(url, **kw):
  285. return ProxyManager(proxy_url=url, **kw)