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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.utils
  4. ~~~~~~~~~~~~~~
  5. This module provides utility functions that are used within Requests
  6. that are also useful for external consumption.
  7. """
  8. import cgi
  9. import codecs
  10. import collections
  11. import io
  12. import os
  13. import re
  14. import socket
  15. import struct
  16. import warnings
  17. from . import __version__
  18. from . import certs
  19. from .compat import parse_http_list as _parse_list_header
  20. from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
  21. builtin_str, getproxies, proxy_bypass, urlunparse,
  22. basestring)
  23. from .cookies import RequestsCookieJar, cookiejar_from_dict
  24. from .structures import CaseInsensitiveDict
  25. from .exceptions import InvalidURL, InvalidHeader, FileModeWarning
  26. _hush_pyflakes = (RequestsCookieJar,)
  27. NETRC_FILES = ('.netrc', '_netrc')
  28. DEFAULT_CA_BUNDLE_PATH = certs.where()
  29. def dict_to_sequence(d):
  30. """Returns an internal sequence dictionary update."""
  31. if hasattr(d, 'items'):
  32. d = d.items()
  33. return d
  34. def super_len(o):
  35. total_length = 0
  36. current_position = 0
  37. if hasattr(o, '__len__'):
  38. total_length = len(o)
  39. elif hasattr(o, 'len'):
  40. total_length = o.len
  41. elif hasattr(o, 'getvalue'):
  42. # e.g. BytesIO, cStringIO.StringIO
  43. total_length = len(o.getvalue())
  44. elif hasattr(o, 'fileno'):
  45. try:
  46. fileno = o.fileno()
  47. except io.UnsupportedOperation:
  48. pass
  49. else:
  50. total_length = os.fstat(fileno).st_size
  51. # Having used fstat to determine the file length, we need to
  52. # confirm that this file was opened up in binary mode.
  53. if 'b' not in o.mode:
  54. warnings.warn((
  55. "Requests has determined the content-length for this "
  56. "request using the binary size of the file: however, the "
  57. "file has been opened in text mode (i.e. without the 'b' "
  58. "flag in the mode). This may lead to an incorrect "
  59. "content-length. In Requests 3.0, support will be removed "
  60. "for files in text mode."),
  61. FileModeWarning
  62. )
  63. if hasattr(o, 'tell'):
  64. try:
  65. current_position = o.tell()
  66. except (OSError, IOError):
  67. # This can happen in some weird situations, such as when the file
  68. # is actually a special file descriptor like stdin. In this
  69. # instance, we don't know what the length is, so set it to zero and
  70. # let requests chunk it instead.
  71. current_position = total_length
  72. return max(0, total_length - current_position)
  73. def get_netrc_auth(url, raise_errors=False):
  74. """Returns the Requests tuple auth for a given url from netrc."""
  75. try:
  76. from netrc import netrc, NetrcParseError
  77. netrc_path = None
  78. for f in NETRC_FILES:
  79. try:
  80. loc = os.path.expanduser('~/{0}'.format(f))
  81. except KeyError:
  82. # os.path.expanduser can fail when $HOME is undefined and
  83. # getpwuid fails. See http://bugs.python.org/issue20164 &
  84. # https://github.com/kennethreitz/requests/issues/1846
  85. return
  86. if os.path.exists(loc):
  87. netrc_path = loc
  88. break
  89. # Abort early if there isn't one.
  90. if netrc_path is None:
  91. return
  92. ri = urlparse(url)
  93. # Strip port numbers from netloc. This weird `if...encode`` dance is
  94. # used for Python 3.2, which doesn't support unicode literals.
  95. splitstr = b':'
  96. if isinstance(url, str):
  97. splitstr = splitstr.decode('ascii')
  98. host = ri.netloc.split(splitstr)[0]
  99. try:
  100. _netrc = netrc(netrc_path).authenticators(host)
  101. if _netrc:
  102. # Return with login / password
  103. login_i = (0 if _netrc[0] else 1)
  104. return (_netrc[login_i], _netrc[2])
  105. except (NetrcParseError, IOError):
  106. # If there was a parsing error or a permissions issue reading the file,
  107. # we'll just skip netrc auth unless explicitly asked to raise errors.
  108. if raise_errors:
  109. raise
  110. # AppEngine hackiness.
  111. except (ImportError, AttributeError):
  112. pass
  113. def guess_filename(obj):
  114. """Tries to guess the filename of the given object."""
  115. name = getattr(obj, 'name', None)
  116. if (name and isinstance(name, basestring) and name[0] != '<' and
  117. name[-1] != '>'):
  118. return os.path.basename(name)
  119. def from_key_val_list(value):
  120. """Take an object and test to see if it can be represented as a
  121. dictionary. Unless it can not be represented as such, return an
  122. OrderedDict, e.g.,
  123. ::
  124. >>> from_key_val_list([('key', 'val')])
  125. OrderedDict([('key', 'val')])
  126. >>> from_key_val_list('string')
  127. ValueError: need more than 1 value to unpack
  128. >>> from_key_val_list({'key': 'val'})
  129. OrderedDict([('key', 'val')])
  130. :rtype: OrderedDict
  131. """
  132. if value is None:
  133. return None
  134. if isinstance(value, (str, bytes, bool, int)):
  135. raise ValueError('cannot encode objects that are not 2-tuples')
  136. return OrderedDict(value)
  137. def to_key_val_list(value):
  138. """Take an object and test to see if it can be represented as a
  139. dictionary. If it can be, return a list of tuples, e.g.,
  140. ::
  141. >>> to_key_val_list([('key', 'val')])
  142. [('key', 'val')]
  143. >>> to_key_val_list({'key': 'val'})
  144. [('key', 'val')]
  145. >>> to_key_val_list('string')
  146. ValueError: cannot encode objects that are not 2-tuples.
  147. :rtype: list
  148. """
  149. if value is None:
  150. return None
  151. if isinstance(value, (str, bytes, bool, int)):
  152. raise ValueError('cannot encode objects that are not 2-tuples')
  153. if isinstance(value, collections.Mapping):
  154. value = value.items()
  155. return list(value)
  156. # From mitsuhiko/werkzeug (used with permission).
  157. def parse_list_header(value):
  158. """Parse lists as described by RFC 2068 Section 2.
  159. In particular, parse comma-separated lists where the elements of
  160. the list may include quoted-strings. A quoted-string could
  161. contain a comma. A non-quoted string could have quotes in the
  162. middle. Quotes are removed automatically after parsing.
  163. It basically works like :func:`parse_set_header` just that items
  164. may appear multiple times and case sensitivity is preserved.
  165. The return value is a standard :class:`list`:
  166. >>> parse_list_header('token, "quoted value"')
  167. ['token', 'quoted value']
  168. To create a header from the :class:`list` again, use the
  169. :func:`dump_header` function.
  170. :param value: a string with a list header.
  171. :return: :class:`list`
  172. :rtype: list
  173. """
  174. result = []
  175. for item in _parse_list_header(value):
  176. if item[:1] == item[-1:] == '"':
  177. item = unquote_header_value(item[1:-1])
  178. result.append(item)
  179. return result
  180. # From mitsuhiko/werkzeug (used with permission).
  181. def parse_dict_header(value):
  182. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  183. convert them into a python dict:
  184. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  185. >>> type(d) is dict
  186. True
  187. >>> sorted(d.items())
  188. [('bar', 'as well'), ('foo', 'is a fish')]
  189. If there is no value for a key it will be `None`:
  190. >>> parse_dict_header('key_without_value')
  191. {'key_without_value': None}
  192. To create a header from the :class:`dict` again, use the
  193. :func:`dump_header` function.
  194. :param value: a string with a dict header.
  195. :return: :class:`dict`
  196. :rtype: dict
  197. """
  198. result = {}
  199. for item in _parse_list_header(value):
  200. if '=' not in item:
  201. result[item] = None
  202. continue
  203. name, value = item.split('=', 1)
  204. if value[:1] == value[-1:] == '"':
  205. value = unquote_header_value(value[1:-1])
  206. result[name] = value
  207. return result
  208. # From mitsuhiko/werkzeug (used with permission).
  209. def unquote_header_value(value, is_filename=False):
  210. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  211. This does not use the real unquoting but what browsers are actually
  212. using for quoting.
  213. :param value: the header value to unquote.
  214. :rtype: str
  215. """
  216. if value and value[0] == value[-1] == '"':
  217. # this is not the real unquoting, but fixing this so that the
  218. # RFC is met will result in bugs with internet explorer and
  219. # probably some other browsers as well. IE for example is
  220. # uploading files with "C:\foo\bar.txt" as filename
  221. value = value[1:-1]
  222. # if this is a filename and the starting characters look like
  223. # a UNC path, then just return the value without quotes. Using the
  224. # replace sequence below on a UNC path has the effect of turning
  225. # the leading double slash into a single slash and then
  226. # _fix_ie_filename() doesn't work correctly. See #458.
  227. if not is_filename or value[:2] != '\\\\':
  228. return value.replace('\\\\', '\\').replace('\\"', '"')
  229. return value
  230. def dict_from_cookiejar(cj):
  231. """Returns a key/value dictionary from a CookieJar.
  232. :param cj: CookieJar object to extract cookies from.
  233. :rtype: dict
  234. """
  235. cookie_dict = {}
  236. for cookie in cj:
  237. cookie_dict[cookie.name] = cookie.value
  238. return cookie_dict
  239. def add_dict_to_cookiejar(cj, cookie_dict):
  240. """Returns a CookieJar from a key/value dictionary.
  241. :param cj: CookieJar to insert cookies into.
  242. :param cookie_dict: Dict of key/values to insert into CookieJar.
  243. :rtype: CookieJar
  244. """
  245. cj2 = cookiejar_from_dict(cookie_dict)
  246. cj.update(cj2)
  247. return cj
  248. def get_encodings_from_content(content):
  249. """Returns encodings from given content string.
  250. :param content: bytestring to extract encodings from.
  251. """
  252. warnings.warn((
  253. 'In requests 3.0, get_encodings_from_content will be removed. For '
  254. 'more information, please see the discussion on issue #2266. (This'
  255. ' warning should only appear once.)'),
  256. DeprecationWarning)
  257. charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
  258. pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
  259. xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
  260. return (charset_re.findall(content) +
  261. pragma_re.findall(content) +
  262. xml_re.findall(content))
  263. def get_encoding_from_headers(headers):
  264. """Returns encodings from given HTTP Header Dict.
  265. :param headers: dictionary to extract encoding from.
  266. :rtype: str
  267. """
  268. content_type = headers.get('content-type')
  269. if not content_type:
  270. return None
  271. content_type, params = cgi.parse_header(content_type)
  272. if 'charset' in params:
  273. return params['charset'].strip("'\"")
  274. if 'text' in content_type:
  275. return 'ISO-8859-1'
  276. def stream_decode_response_unicode(iterator, r):
  277. """Stream decodes a iterator."""
  278. if r.encoding is None:
  279. for item in iterator:
  280. yield item
  281. return
  282. decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
  283. for chunk in iterator:
  284. rv = decoder.decode(chunk)
  285. if rv:
  286. yield rv
  287. rv = decoder.decode(b'', final=True)
  288. if rv:
  289. yield rv
  290. def iter_slices(string, slice_length):
  291. """Iterate over slices of a string."""
  292. pos = 0
  293. if slice_length is None or slice_length <= 0:
  294. slice_length = len(string)
  295. while pos < len(string):
  296. yield string[pos:pos + slice_length]
  297. pos += slice_length
  298. def get_unicode_from_response(r):
  299. """Returns the requested content back in unicode.
  300. :param r: Response object to get unicode content from.
  301. Tried:
  302. 1. charset from content-type
  303. 2. fall back and replace all unicode characters
  304. :rtype: str
  305. """
  306. warnings.warn((
  307. 'In requests 3.0, get_unicode_from_response will be removed. For '
  308. 'more information, please see the discussion on issue #2266. (This'
  309. ' warning should only appear once.)'),
  310. DeprecationWarning)
  311. tried_encodings = []
  312. # Try charset from content-type
  313. encoding = get_encoding_from_headers(r.headers)
  314. if encoding:
  315. try:
  316. return str(r.content, encoding)
  317. except UnicodeError:
  318. tried_encodings.append(encoding)
  319. # Fall back:
  320. try:
  321. return str(r.content, encoding, errors='replace')
  322. except TypeError:
  323. return r.content
  324. # The unreserved URI characters (RFC 3986)
  325. UNRESERVED_SET = frozenset(
  326. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  327. + "0123456789-._~")
  328. def unquote_unreserved(uri):
  329. """Un-escape any percent-escape sequences in a URI that are unreserved
  330. characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
  331. :rtype: str
  332. """
  333. parts = uri.split('%')
  334. for i in range(1, len(parts)):
  335. h = parts[i][0:2]
  336. if len(h) == 2 and h.isalnum():
  337. try:
  338. c = chr(int(h, 16))
  339. except ValueError:
  340. raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
  341. if c in UNRESERVED_SET:
  342. parts[i] = c + parts[i][2:]
  343. else:
  344. parts[i] = '%' + parts[i]
  345. else:
  346. parts[i] = '%' + parts[i]
  347. return ''.join(parts)
  348. def requote_uri(uri):
  349. """Re-quote the given URI.
  350. This function passes the given URI through an unquote/quote cycle to
  351. ensure that it is fully and consistently quoted.
  352. :rtype: str
  353. """
  354. safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
  355. safe_without_percent = "!#$&'()*+,/:;=?@[]~"
  356. try:
  357. # Unquote only the unreserved characters
  358. # Then quote only illegal characters (do not quote reserved,
  359. # unreserved, or '%')
  360. return quote(unquote_unreserved(uri), safe=safe_with_percent)
  361. except InvalidURL:
  362. # We couldn't unquote the given URI, so let's try quoting it, but
  363. # there may be unquoted '%'s in the URI. We need to make sure they're
  364. # properly quoted so they do not cause issues elsewhere.
  365. return quote(uri, safe=safe_without_percent)
  366. def address_in_network(ip, net):
  367. """This function allows you to check if on IP belongs to a network subnet
  368. Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
  369. returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
  370. :rtype: bool
  371. """
  372. ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
  373. netaddr, bits = net.split('/')
  374. netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
  375. network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
  376. return (ipaddr & netmask) == (network & netmask)
  377. def dotted_netmask(mask):
  378. """Converts mask from /xx format to xxx.xxx.xxx.xxx
  379. Example: if mask is 24 function returns 255.255.255.0
  380. :rtype: str
  381. """
  382. bits = 0xffffffff ^ (1 << 32 - mask) - 1
  383. return socket.inet_ntoa(struct.pack('>I', bits))
  384. def is_ipv4_address(string_ip):
  385. """
  386. :rtype: bool
  387. """
  388. try:
  389. socket.inet_aton(string_ip)
  390. except socket.error:
  391. return False
  392. return True
  393. def is_valid_cidr(string_network):
  394. """
  395. Very simple check of the cidr format in no_proxy variable.
  396. :rtype: bool
  397. """
  398. if string_network.count('/') == 1:
  399. try:
  400. mask = int(string_network.split('/')[1])
  401. except ValueError:
  402. return False
  403. if mask < 1 or mask > 32:
  404. return False
  405. try:
  406. socket.inet_aton(string_network.split('/')[0])
  407. except socket.error:
  408. return False
  409. else:
  410. return False
  411. return True
  412. def should_bypass_proxies(url):
  413. """
  414. Returns whether we should bypass proxies or not.
  415. :rtype: bool
  416. """
  417. get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
  418. # First check whether no_proxy is defined. If it is, check that the URL
  419. # we're getting isn't in the no_proxy list.
  420. no_proxy = get_proxy('no_proxy')
  421. netloc = urlparse(url).netloc
  422. if no_proxy:
  423. # We need to check whether we match here. We need to see if we match
  424. # the end of the netloc, both with and without the port.
  425. no_proxy = (
  426. host for host in no_proxy.replace(' ', '').split(',') if host
  427. )
  428. ip = netloc.split(':')[0]
  429. if is_ipv4_address(ip):
  430. for proxy_ip in no_proxy:
  431. if is_valid_cidr(proxy_ip):
  432. if address_in_network(ip, proxy_ip):
  433. return True
  434. elif ip == proxy_ip:
  435. # If no_proxy ip was defined in plain IP notation instead of cidr notation &
  436. # matches the IP of the index
  437. return True
  438. else:
  439. for host in no_proxy:
  440. if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
  441. # The URL does match something in no_proxy, so we don't want
  442. # to apply the proxies on this URL.
  443. return True
  444. # If the system proxy settings indicate that this URL should be bypassed,
  445. # don't proxy.
  446. # The proxy_bypass function is incredibly buggy on OS X in early versions
  447. # of Python 2.6, so allow this call to fail. Only catch the specific
  448. # exceptions we've seen, though: this call failing in other ways can reveal
  449. # legitimate problems.
  450. try:
  451. bypass = proxy_bypass(netloc)
  452. except (TypeError, socket.gaierror):
  453. bypass = False
  454. if bypass:
  455. return True
  456. return False
  457. def get_environ_proxies(url):
  458. """
  459. Return a dict of environment proxies.
  460. :rtype: dict
  461. """
  462. if should_bypass_proxies(url):
  463. return {}
  464. else:
  465. return getproxies()
  466. def select_proxy(url, proxies):
  467. """Select a proxy for the url, if applicable.
  468. :param url: The url being for the request
  469. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
  470. """
  471. proxies = proxies or {}
  472. urlparts = urlparse(url)
  473. if urlparts.hostname is None:
  474. return proxies.get('all', proxies.get(urlparts.scheme))
  475. proxy_keys = [
  476. 'all://' + urlparts.hostname,
  477. 'all',
  478. urlparts.scheme + '://' + urlparts.hostname,
  479. urlparts.scheme,
  480. ]
  481. proxy = None
  482. for proxy_key in proxy_keys:
  483. if proxy_key in proxies:
  484. proxy = proxies[proxy_key]
  485. break
  486. return proxy
  487. def default_user_agent(name="python-requests"):
  488. """
  489. Return a string representing the default user agent.
  490. :rtype: str
  491. """
  492. return '%s/%s' % (name, __version__)
  493. def default_headers():
  494. """
  495. :rtype: requests.structures.CaseInsensitiveDict
  496. """
  497. return CaseInsensitiveDict({
  498. 'User-Agent': default_user_agent(),
  499. 'Accept-Encoding': ', '.join(('gzip', 'deflate')),
  500. 'Accept': '*/*',
  501. 'Connection': 'keep-alive',
  502. })
  503. def parse_header_links(value):
  504. """Return a dict of parsed link headers proxies.
  505. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
  506. :rtype: list
  507. """
  508. links = []
  509. replace_chars = ' \'"'
  510. for val in re.split(', *<', value):
  511. try:
  512. url, params = val.split(';', 1)
  513. except ValueError:
  514. url, params = val, ''
  515. link = {'url': url.strip('<> \'"')}
  516. for param in params.split(';'):
  517. try:
  518. key, value = param.split('=')
  519. except ValueError:
  520. break
  521. link[key.strip(replace_chars)] = value.strip(replace_chars)
  522. links.append(link)
  523. return links
  524. # Null bytes; no need to recreate these on each call to guess_json_utf
  525. _null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
  526. _null2 = _null * 2
  527. _null3 = _null * 3
  528. def guess_json_utf(data):
  529. """
  530. :rtype: str
  531. """
  532. # JSON always starts with two ASCII characters, so detection is as
  533. # easy as counting the nulls and from their location and count
  534. # determine the encoding. Also detect a BOM, if present.
  535. sample = data[:4]
  536. if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE):
  537. return 'utf-32' # BOM included
  538. if sample[:3] == codecs.BOM_UTF8:
  539. return 'utf-8-sig' # BOM included, MS style (discouraged)
  540. if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
  541. return 'utf-16' # BOM included
  542. nullcount = sample.count(_null)
  543. if nullcount == 0:
  544. return 'utf-8'
  545. if nullcount == 2:
  546. if sample[::2] == _null2: # 1st and 3rd are null
  547. return 'utf-16-be'
  548. if sample[1::2] == _null2: # 2nd and 4th are null
  549. return 'utf-16-le'
  550. # Did not detect 2 valid UTF-16 ascii-range characters
  551. if nullcount == 3:
  552. if sample[:3] == _null3:
  553. return 'utf-32-be'
  554. if sample[1:] == _null3:
  555. return 'utf-32-le'
  556. # Did not detect a valid UTF-32 ascii-range character
  557. return None
  558. def prepend_scheme_if_needed(url, new_scheme):
  559. """Given a URL that may or may not have a scheme, prepend the given scheme.
  560. Does not replace a present scheme with the one provided as an argument.
  561. :rtype: str
  562. """
  563. scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
  564. # urlparse is a finicky beast, and sometimes decides that there isn't a
  565. # netloc present. Assume that it's being over-cautious, and switch netloc
  566. # and path if urlparse decided there was no netloc.
  567. if not netloc:
  568. netloc, path = path, netloc
  569. return urlunparse((scheme, netloc, path, params, query, fragment))
  570. def get_auth_from_url(url):
  571. """Given a url with authentication components, extract them into a tuple of
  572. username,password.
  573. :rtype: (str,str)
  574. """
  575. parsed = urlparse(url)
  576. try:
  577. auth = (unquote(parsed.username), unquote(parsed.password))
  578. except (AttributeError, TypeError):
  579. auth = ('', '')
  580. return auth
  581. def to_native_string(string, encoding='ascii'):
  582. """Given a string object, regardless of type, returns a representation of
  583. that string in the native string type, encoding and decoding where
  584. necessary. This assumes ASCII unless told otherwise.
  585. """
  586. if isinstance(string, builtin_str):
  587. out = string
  588. else:
  589. if is_py2:
  590. out = string.encode(encoding)
  591. else:
  592. out = string.decode(encoding)
  593. return out
  594. # Moved outside of function to avoid recompile every call
  595. _CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
  596. _CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
  597. def check_header_validity(header):
  598. """Verifies that header value is a string which doesn't contain
  599. leading whitespace or return characters. This prevents unintended
  600. header injection.
  601. :param header: tuple, in the format (name, value).
  602. """
  603. name, value = header
  604. if isinstance(value, bytes):
  605. pat = _CLEAN_HEADER_REGEX_BYTE
  606. else:
  607. pat = _CLEAN_HEADER_REGEX_STR
  608. try:
  609. if not pat.match(value):
  610. raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
  611. except TypeError:
  612. raise InvalidHeader("Header value %s must be of type str or bytes, "
  613. "not %s" % (value, type(value)))
  614. def urldefragauth(url):
  615. """
  616. Given a url remove the fragment and the authentication part.
  617. :rtype: str
  618. """
  619. scheme, netloc, path, params, query, fragment = urlparse(url)
  620. # see func:`prepend_scheme_if_needed`
  621. if not netloc:
  622. netloc, path = path, netloc
  623. netloc = netloc.rsplit('@', 1)[-1]
  624. return urlunparse((scheme, netloc, path, params, query, ''))