_cookiejar.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import http.cookies
  2. from typing import Optional
  3. """
  4. _cookiejar.py
  5. websocket - WebSocket client library for Python
  6. Copyright 2024 engn33r
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. class SimpleCookieJar:
  18. def __init__(self) -> None:
  19. self.jar: dict = {}
  20. def add(self, set_cookie: Optional[str]) -> None:
  21. if set_cookie:
  22. simple_cookie = http.cookies.SimpleCookie(set_cookie)
  23. for v in simple_cookie.values():
  24. if domain := v.get("domain"):
  25. if not domain.startswith("."):
  26. domain = f".{domain}"
  27. cookie = (
  28. self.jar.get(domain)
  29. if self.jar.get(domain)
  30. else http.cookies.SimpleCookie()
  31. )
  32. cookie.update(simple_cookie)
  33. self.jar[domain.lower()] = cookie
  34. def set(self, set_cookie: str) -> None:
  35. if set_cookie:
  36. simple_cookie = http.cookies.SimpleCookie(set_cookie)
  37. for v in simple_cookie.values():
  38. if domain := v.get("domain"):
  39. if not domain.startswith("."):
  40. domain = f".{domain}"
  41. self.jar[domain.lower()] = simple_cookie
  42. def get(self, host: str) -> str:
  43. if not host:
  44. return ""
  45. cookies = []
  46. for domain, _ in self.jar.items():
  47. host = host.lower()
  48. if host.endswith(domain) or host == domain[1:]:
  49. cookies.append(self.jar.get(domain))
  50. return "; ".join(
  51. filter(
  52. None,
  53. sorted(
  54. [
  55. f"{k}={v.value}"
  56. for cookie in filter(None, cookies)
  57. for k, v in cookie.items()
  58. ]
  59. ),
  60. )
  61. )