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

cookies.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.cookies
  4. ~~~~~~~~~~~~~~~~
  5. Compatibility code to be able to use `cookielib.CookieJar` with requests.
  6. requests.utils imports from here, so be careful with imports.
  7. """
  8. import copy
  9. import time
  10. import calendar
  11. import collections
  12. from .compat import cookielib, urlparse, urlunparse, Morsel
  13. try:
  14. import threading
  15. # grr, pyflakes: this fixes "redefinition of unused 'threading'"
  16. threading
  17. except ImportError:
  18. import dummy_threading as threading
  19. class MockRequest(object):
  20. """Wraps a `requests.Request` to mimic a `urllib2.Request`.
  21. The code in `cookielib.CookieJar` expects this interface in order to correctly
  22. manage cookie policies, i.e., determine whether a cookie can be set, given the
  23. domains of the request and the cookie.
  24. The original request object is read-only. The client is responsible for collecting
  25. the new headers via `get_new_headers()` and interpreting them appropriately. You
  26. probably want `get_cookie_header`, defined below.
  27. """
  28. def __init__(self, request):
  29. self._r = request
  30. self._new_headers = {}
  31. self.type = urlparse(self._r.url).scheme
  32. def get_type(self):
  33. return self.type
  34. def get_host(self):
  35. return urlparse(self._r.url).netloc
  36. def get_origin_req_host(self):
  37. return self.get_host()
  38. def get_full_url(self):
  39. # Only return the response's URL if the user hadn't set the Host
  40. # header
  41. if not self._r.headers.get('Host'):
  42. return self._r.url
  43. # If they did set it, retrieve it and reconstruct the expected domain
  44. host = self._r.headers['Host']
  45. parsed = urlparse(self._r.url)
  46. # Reconstruct the URL as we expect it
  47. return urlunparse([
  48. parsed.scheme, host, parsed.path, parsed.params, parsed.query,
  49. parsed.fragment
  50. ])
  51. def is_unverifiable(self):
  52. return True
  53. def has_header(self, name):
  54. return name in self._r.headers or name in self._new_headers
  55. def get_header(self, name, default=None):
  56. return self._r.headers.get(name, self._new_headers.get(name, default))
  57. def add_header(self, key, val):
  58. """cookielib has no legitimate use for this method; add it back if you find one."""
  59. raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
  60. def add_unredirected_header(self, name, value):
  61. self._new_headers[name] = value
  62. def get_new_headers(self):
  63. return self._new_headers
  64. @property
  65. def unverifiable(self):
  66. return self.is_unverifiable()
  67. @property
  68. def origin_req_host(self):
  69. return self.get_origin_req_host()
  70. @property
  71. def host(self):
  72. return self.get_host()
  73. class MockResponse(object):
  74. """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
  75. ...what? Basically, expose the parsed HTTP headers from the server response
  76. the way `cookielib` expects to see them.
  77. """
  78. def __init__(self, headers):
  79. """Make a MockResponse for `cookielib` to read.
  80. :param headers: a httplib.HTTPMessage or analogous carrying the headers
  81. """
  82. self._headers = headers
  83. def info(self):
  84. return self._headers
  85. def getheaders(self, name):
  86. self._headers.getheaders(name)
  87. def extract_cookies_to_jar(jar, request, response):
  88. """Extract the cookies from the response into a CookieJar.
  89. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
  90. :param request: our own requests.Request object
  91. :param response: urllib3.HTTPResponse object
  92. """
  93. if not (hasattr(response, '_original_response') and
  94. response._original_response):
  95. return
  96. # the _original_response field is the wrapped httplib.HTTPResponse object,
  97. req = MockRequest(request)
  98. # pull out the HTTPMessage with the headers and put it in the mock:
  99. res = MockResponse(response._original_response.msg)
  100. jar.extract_cookies(res, req)
  101. def get_cookie_header(jar, request):
  102. """
  103. Produce an appropriate Cookie header string to be sent with `request`, or None.
  104. :rtype: str
  105. """
  106. r = MockRequest(request)
  107. jar.add_cookie_header(r)
  108. return r.get_new_headers().get('Cookie')
  109. def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
  110. """Unsets a cookie by name, by default over all domains and paths.
  111. Wraps CookieJar.clear(), is O(n).
  112. """
  113. clearables = []
  114. for cookie in cookiejar:
  115. if cookie.name != name:
  116. continue
  117. if domain is not None and domain != cookie.domain:
  118. continue
  119. if path is not None and path != cookie.path:
  120. continue
  121. clearables.append((cookie.domain, cookie.path, cookie.name))
  122. for domain, path, name in clearables:
  123. cookiejar.clear(domain, path, name)
  124. class CookieConflictError(RuntimeError):
  125. """There are two cookies that meet the criteria specified in the cookie jar.
  126. Use .get and .set and include domain and path args in order to be more specific.
  127. """
  128. class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
  129. """Compatibility class; is a cookielib.CookieJar, but exposes a dict
  130. interface.
  131. This is the CookieJar we create by default for requests and sessions that
  132. don't specify one, since some clients may expect response.cookies and
  133. session.cookies to support dict operations.
  134. Requests does not use the dict interface internally; it's just for
  135. compatibility with external client code. All requests code should work
  136. out of the box with externally provided instances of ``CookieJar``, e.g.
  137. ``LWPCookieJar`` and ``FileCookieJar``.
  138. Unlike a regular CookieJar, this class is pickleable.
  139. .. warning:: dictionary operations that are normally O(1) may be O(n).
  140. """
  141. def get(self, name, default=None, domain=None, path=None):
  142. """Dict-like get() that also supports optional domain and path args in
  143. order to resolve naming collisions from using one cookie jar over
  144. multiple domains.
  145. .. warning:: operation is O(n), not O(1).
  146. """
  147. try:
  148. return self._find_no_duplicates(name, domain, path)
  149. except KeyError:
  150. return default
  151. def set(self, name, value, **kwargs):
  152. """Dict-like set() that also supports optional domain and path args in
  153. order to resolve naming collisions from using one cookie jar over
  154. multiple domains.
  155. """
  156. # support client code that unsets cookies by assignment of a None value:
  157. if value is None:
  158. remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
  159. return
  160. if isinstance(value, Morsel):
  161. c = morsel_to_cookie(value)
  162. else:
  163. c = create_cookie(name, value, **kwargs)
  164. self.set_cookie(c)
  165. return c
  166. def iterkeys(self):
  167. """Dict-like iterkeys() that returns an iterator of names of cookies
  168. from the jar.
  169. .. seealso:: itervalues() and iteritems().
  170. """
  171. for cookie in iter(self):
  172. yield cookie.name
  173. def keys(self):
  174. """Dict-like keys() that returns a list of names of cookies from the
  175. jar.
  176. .. seealso:: values() and items().
  177. """
  178. return list(self.iterkeys())
  179. def itervalues(self):
  180. """Dict-like itervalues() that returns an iterator of values of cookies
  181. from the jar.
  182. .. seealso:: iterkeys() and iteritems().
  183. """
  184. for cookie in iter(self):
  185. yield cookie.value
  186. def values(self):
  187. """Dict-like values() that returns a list of values of cookies from the
  188. jar.
  189. .. seealso:: keys() and items().
  190. """
  191. return list(self.itervalues())
  192. def iteritems(self):
  193. """Dict-like iteritems() that returns an iterator of name-value tuples
  194. from the jar.
  195. .. seealso:: iterkeys() and itervalues().
  196. """
  197. for cookie in iter(self):
  198. yield cookie.name, cookie.value
  199. def items(self):
  200. """Dict-like items() that returns a list of name-value tuples from the
  201. jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
  202. vanilla python dict of key value pairs.
  203. .. seealso:: keys() and values().
  204. """
  205. return list(self.iteritems())
  206. def list_domains(self):
  207. """Utility method to list all the domains in the jar."""
  208. domains = []
  209. for cookie in iter(self):
  210. if cookie.domain not in domains:
  211. domains.append(cookie.domain)
  212. return domains
  213. def list_paths(self):
  214. """Utility method to list all the paths in the jar."""
  215. paths = []
  216. for cookie in iter(self):
  217. if cookie.path not in paths:
  218. paths.append(cookie.path)
  219. return paths
  220. def multiple_domains(self):
  221. """Returns True if there are multiple domains in the jar.
  222. Returns False otherwise.
  223. :rtype: bool
  224. """
  225. domains = []
  226. for cookie in iter(self):
  227. if cookie.domain is not None and cookie.domain in domains:
  228. return True
  229. domains.append(cookie.domain)
  230. return False # there is only one domain in jar
  231. def get_dict(self, domain=None, path=None):
  232. """Takes as an argument an optional domain and path and returns a plain
  233. old Python dict of name-value pairs of cookies that meet the
  234. requirements.
  235. :rtype: dict
  236. """
  237. dictionary = {}
  238. for cookie in iter(self):
  239. if (domain is None or cookie.domain == domain) and (path is None
  240. or cookie.path == path):
  241. dictionary[cookie.name] = cookie.value
  242. return dictionary
  243. def __contains__(self, name):
  244. try:
  245. return super(RequestsCookieJar, self).__contains__(name)
  246. except CookieConflictError:
  247. return True
  248. def __getitem__(self, name):
  249. """Dict-like __getitem__() for compatibility with client code. Throws
  250. exception if there are more than one cookie with name. In that case,
  251. use the more explicit get() method instead.
  252. .. warning:: operation is O(n), not O(1).
  253. """
  254. return self._find_no_duplicates(name)
  255. def __setitem__(self, name, value):
  256. """Dict-like __setitem__ for compatibility with client code. Throws
  257. exception if there is already a cookie of that name in the jar. In that
  258. case, use the more explicit set() method instead.
  259. """
  260. self.set(name, value)
  261. def __delitem__(self, name):
  262. """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
  263. ``remove_cookie_by_name()``.
  264. """
  265. remove_cookie_by_name(self, name)
  266. def set_cookie(self, cookie, *args, **kwargs):
  267. if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
  268. cookie.value = cookie.value.replace('\\"', '')
  269. return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
  270. def update(self, other):
  271. """Updates this jar with cookies from another CookieJar or dict-like"""
  272. if isinstance(other, cookielib.CookieJar):
  273. for cookie in other:
  274. self.set_cookie(copy.copy(cookie))
  275. else:
  276. super(RequestsCookieJar, self).update(other)
  277. def _find(self, name, domain=None, path=None):
  278. """Requests uses this method internally to get cookie values.
  279. If there are conflicting cookies, _find arbitrarily chooses one.
  280. See _find_no_duplicates if you want an exception thrown if there are
  281. conflicting cookies.
  282. :param name: a string containing name of cookie
  283. :param domain: (optional) string containing domain of cookie
  284. :param path: (optional) string containing path of cookie
  285. :return: cookie.value
  286. """
  287. for cookie in iter(self):
  288. if cookie.name == name:
  289. if domain is None or cookie.domain == domain:
  290. if path is None or cookie.path == path:
  291. return cookie.value
  292. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  293. def _find_no_duplicates(self, name, domain=None, path=None):
  294. """Both ``__get_item__`` and ``get`` call this function: it's never
  295. used elsewhere in Requests.
  296. :param name: a string containing name of cookie
  297. :param domain: (optional) string containing domain of cookie
  298. :param path: (optional) string containing path of cookie
  299. :raises KeyError: if cookie is not found
  300. :raises CookieConflictError: if there are multiple cookies
  301. that match name and optionally domain and path
  302. :return: cookie.value
  303. """
  304. toReturn = None
  305. for cookie in iter(self):
  306. if cookie.name == name:
  307. if domain is None or cookie.domain == domain:
  308. if path is None or cookie.path == path:
  309. if toReturn is not None: # if there are multiple cookies that meet passed in criteria
  310. raise CookieConflictError('There are multiple cookies with name, %r' % (name))
  311. toReturn = cookie.value # we will eventually return this as long as no cookie conflict
  312. if toReturn:
  313. return toReturn
  314. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  315. def __getstate__(self):
  316. """Unlike a normal CookieJar, this class is pickleable."""
  317. state = self.__dict__.copy()
  318. # remove the unpickleable RLock object
  319. state.pop('_cookies_lock')
  320. return state
  321. def __setstate__(self, state):
  322. """Unlike a normal CookieJar, this class is pickleable."""
  323. self.__dict__.update(state)
  324. if '_cookies_lock' not in self.__dict__:
  325. self._cookies_lock = threading.RLock()
  326. def copy(self):
  327. """Return a copy of this RequestsCookieJar."""
  328. new_cj = RequestsCookieJar()
  329. new_cj.update(self)
  330. return new_cj
  331. def _copy_cookie_jar(jar):
  332. if jar is None:
  333. return None
  334. if hasattr(jar, 'copy'):
  335. # We're dealing with an instance of RequestsCookieJar
  336. return jar.copy()
  337. # We're dealing with a generic CookieJar instance
  338. new_jar = copy.copy(jar)
  339. new_jar.clear()
  340. for cookie in jar:
  341. new_jar.set_cookie(copy.copy(cookie))
  342. return new_jar
  343. def create_cookie(name, value, **kwargs):
  344. """Make a cookie from underspecified parameters.
  345. By default, the pair of `name` and `value` will be set for the domain ''
  346. and sent on every request (this is sometimes called a "supercookie").
  347. """
  348. result = dict(
  349. version=0,
  350. name=name,
  351. value=value,
  352. port=None,
  353. domain='',
  354. path='/',
  355. secure=False,
  356. expires=None,
  357. discard=True,
  358. comment=None,
  359. comment_url=None,
  360. rest={'HttpOnly': None},
  361. rfc2109=False,)
  362. badargs = set(kwargs) - set(result)
  363. if badargs:
  364. err = 'create_cookie() got unexpected keyword arguments: %s'
  365. raise TypeError(err % list(badargs))
  366. result.update(kwargs)
  367. result['port_specified'] = bool(result['port'])
  368. result['domain_specified'] = bool(result['domain'])
  369. result['domain_initial_dot'] = result['domain'].startswith('.')
  370. result['path_specified'] = bool(result['path'])
  371. return cookielib.Cookie(**result)
  372. def morsel_to_cookie(morsel):
  373. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  374. expires = None
  375. if morsel['max-age']:
  376. try:
  377. expires = int(time.time() + int(morsel['max-age']))
  378. except ValueError:
  379. raise TypeError('max-age: %s must be integer' % morsel['max-age'])
  380. elif morsel['expires']:
  381. time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
  382. expires = calendar.timegm(
  383. time.strptime(morsel['expires'], time_template)
  384. )
  385. return create_cookie(
  386. comment=morsel['comment'],
  387. comment_url=bool(morsel['comment']),
  388. discard=False,
  389. domain=morsel['domain'],
  390. expires=expires,
  391. name=morsel.key,
  392. path=morsel['path'],
  393. port=None,
  394. rest={'HttpOnly': morsel['httponly']},
  395. rfc2109=False,
  396. secure=bool(morsel['secure']),
  397. value=morsel.value,
  398. version=morsel['version'] or 0,
  399. )
  400. def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
  401. """Returns a CookieJar from a key/value dictionary.
  402. :param cookie_dict: Dict of key/values to insert into CookieJar.
  403. :param cookiejar: (optional) A cookiejar to add the cookies to.
  404. :param overwrite: (optional) If False, will not replace cookies
  405. already in the jar with new ones.
  406. """
  407. if cookiejar is None:
  408. cookiejar = RequestsCookieJar()
  409. if cookie_dict is not None:
  410. names_from_jar = [cookie.name for cookie in cookiejar]
  411. for name in cookie_dict:
  412. if overwrite or (name not in names_from_jar):
  413. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  414. return cookiejar
  415. def merge_cookies(cookiejar, cookies):
  416. """Add cookies to cookiejar and returns a merged CookieJar.
  417. :param cookiejar: CookieJar object to add the cookies to.
  418. :param cookies: Dictionary or CookieJar object to be added.
  419. """
  420. if not isinstance(cookiejar, cookielib.CookieJar):
  421. raise ValueError('You can only merge into CookieJar')
  422. if isinstance(cookies, dict):
  423. cookiejar = cookiejar_from_dict(
  424. cookies, cookiejar=cookiejar, overwrite=False)
  425. elif isinstance(cookies, cookielib.CookieJar):
  426. try:
  427. cookiejar.update(cookies)
  428. except AttributeError:
  429. for cookie_in_jar in cookies:
  430. cookiejar.set_cookie(cookie_in_jar)
  431. return cookiejar