cookies.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from __future__ import annotations
  2. import os
  3. import time
  4. try:
  5. from platformdirs import user_config_dir
  6. has_platformdirs = True
  7. except ImportError:
  8. has_platformdirs = False
  9. try:
  10. from browser_cookie3 import (
  11. chrome, chromium, opera, opera_gx,
  12. brave, edge, vivaldi, firefox,
  13. _LinuxPasswordManager, BrowserCookieError
  14. )
  15. has_browser_cookie3 = True
  16. except ImportError:
  17. has_browser_cookie3 = False
  18. from .typing import Dict, Cookies
  19. from .errors import MissingRequirementsError
  20. from . import debug
  21. # Global variable to store cookies
  22. _cookies: Dict[str, Cookies] = {}
  23. if has_browser_cookie3 and os.environ.get('DBUS_SESSION_BUS_ADDRESS') == "/dev/null":
  24. _LinuxPasswordManager.get_password = lambda a, b: b"secret"
  25. def get_cookies(domain_name: str = '', raise_requirements_error: bool = True, single_browser: bool = False) -> Dict[str, str]:
  26. """
  27. Load cookies for a given domain from all supported browsers and cache the results.
  28. Args:
  29. domain_name (str): The domain for which to load cookies.
  30. Returns:
  31. Dict[str, str]: A dictionary of cookie names and values.
  32. """
  33. if domain_name in _cookies:
  34. return _cookies[domain_name]
  35. cookies = load_cookies_from_browsers(domain_name, raise_requirements_error, single_browser)
  36. _cookies[domain_name] = cookies
  37. return cookies
  38. def set_cookies(domain_name: str, cookies: Cookies = None) -> None:
  39. if cookies:
  40. _cookies[domain_name] = cookies
  41. elif domain_name in _cookies:
  42. _cookies.pop(domain_name)
  43. def load_cookies_from_browsers(domain_name: str, raise_requirements_error: bool = True, single_browser: bool = False) -> Cookies:
  44. """
  45. Helper function to load cookies from various browsers.
  46. Args:
  47. domain_name (str): The domain for which to load cookies.
  48. Returns:
  49. Dict[str, str]: A dictionary of cookie names and values.
  50. """
  51. if not has_browser_cookie3:
  52. if raise_requirements_error:
  53. raise MissingRequirementsError('Install "browser_cookie3" package')
  54. return {}
  55. cookies = {}
  56. for cookie_fn in [_g4f, chrome, chromium, opera, opera_gx, brave, edge, vivaldi, firefox]:
  57. try:
  58. cookie_jar = cookie_fn(domain_name=domain_name)
  59. if len(cookie_jar) and debug.logging:
  60. print(f"Read cookies from {cookie_fn.__name__} for {domain_name}")
  61. for cookie in cookie_jar:
  62. if cookie.name not in cookies:
  63. if not cookie.expires or cookie.expires > time.time():
  64. cookies[cookie.name] = cookie.value
  65. if single_browser and len(cookie_jar):
  66. break
  67. except BrowserCookieError:
  68. pass
  69. except Exception as e:
  70. if debug.logging:
  71. print(f"Error reading cookies from {cookie_fn.__name__} for {domain_name}: {e}")
  72. return cookies
  73. def _g4f(domain_name: str) -> list:
  74. """
  75. Load cookies from the 'g4f' browser (if exists).
  76. Args:
  77. domain_name (str): The domain for which to load cookies.
  78. Returns:
  79. list: List of cookies.
  80. """
  81. if not has_platformdirs:
  82. return []
  83. user_data_dir = user_config_dir("g4f")
  84. cookie_file = os.path.join(user_data_dir, "Default", "Cookies")
  85. return [] if not os.path.exists(cookie_file) else chrome(cookie_file, domain_name)