cookies.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. from __future__ import annotations
  2. import os
  3. import time
  4. import json
  5. try:
  6. from platformdirs import user_config_dir
  7. has_platformdirs = True
  8. except ImportError:
  9. has_platformdirs = False
  10. try:
  11. from browser_cookie3 import (
  12. chrome, chromium, opera, opera_gx,
  13. brave, edge, vivaldi, firefox,
  14. _LinuxPasswordManager, BrowserCookieError
  15. )
  16. has_browser_cookie3 = True
  17. except ImportError:
  18. has_browser_cookie3 = False
  19. from .typing import Dict, Cookies
  20. from .errors import MissingRequirementsError
  21. from . import debug
  22. class CookiesConfig():
  23. cookies: Dict[str, Cookies] = {}
  24. cookies_dir: str = "./har_and_cookies"
  25. DOMAINS = [
  26. ".bing.com",
  27. ".meta.ai",
  28. ".google.com",
  29. "www.whiterabbitneo.com",
  30. "huggingface.co",
  31. "chat.reka.ai",
  32. "chatgpt.com"
  33. ]
  34. if has_browser_cookie3 and os.environ.get('DBUS_SESSION_BUS_ADDRESS') == "/dev/null":
  35. _LinuxPasswordManager.get_password = lambda a, b: b"secret"
  36. def get_cookies(domain_name: str = '', raise_requirements_error: bool = True, single_browser: bool = False) -> Dict[str, str]:
  37. """
  38. Load cookies for a given domain from all supported browsers and cache the results.
  39. Args:
  40. domain_name (str): The domain for which to load cookies.
  41. Returns:
  42. Dict[str, str]: A dictionary of cookie names and values.
  43. """
  44. if domain_name in CookiesConfig.cookies:
  45. return CookiesConfig.cookies[domain_name]
  46. cookies = load_cookies_from_browsers(domain_name, raise_requirements_error, single_browser)
  47. CookiesConfig.cookies[domain_name] = cookies
  48. return cookies
  49. def set_cookies(domain_name: str, cookies: Cookies = None) -> None:
  50. if cookies:
  51. CookiesConfig.cookies[domain_name] = cookies
  52. elif domain_name in CookiesConfig.cookies:
  53. CookiesConfig.cookies.pop(domain_name)
  54. def load_cookies_from_browsers(domain_name: str, raise_requirements_error: bool = True, single_browser: bool = False) -> Cookies:
  55. """
  56. Helper function to load cookies from various browsers.
  57. Args:
  58. domain_name (str): The domain for which to load cookies.
  59. Returns:
  60. Dict[str, str]: A dictionary of cookie names and values.
  61. """
  62. if not has_browser_cookie3:
  63. if raise_requirements_error:
  64. raise MissingRequirementsError('Install "browser_cookie3" package')
  65. return {}
  66. cookies = {}
  67. for cookie_fn in [_g4f, chrome, chromium, opera, opera_gx, brave, edge, vivaldi, firefox]:
  68. try:
  69. cookie_jar = cookie_fn(domain_name=domain_name)
  70. if len(cookie_jar) and debug.logging:
  71. print(f"Read cookies from {cookie_fn.__name__} for {domain_name}")
  72. for cookie in cookie_jar:
  73. if cookie.name not in cookies:
  74. if not cookie.expires or cookie.expires > time.time():
  75. cookies[cookie.name] = cookie.value
  76. if single_browser and len(cookie_jar):
  77. break
  78. except BrowserCookieError:
  79. pass
  80. except Exception as e:
  81. if debug.logging:
  82. print(f"Error reading cookies from {cookie_fn.__name__} for {domain_name}: {e}")
  83. return cookies
  84. def set_cookies_dir(dir: str) -> None:
  85. CookiesConfig.cookies_dir = dir
  86. def get_cookies_dir() -> str:
  87. return CookiesConfig.cookies_dir
  88. def read_cookie_files(dirPath: str = None):
  89. def get_domain(v: dict) -> str:
  90. host = [h["value"] for h in v['request']['headers'] if h["name"].lower() in ("host", ":authority")]
  91. if not host:
  92. return
  93. host = host.pop()
  94. for d in DOMAINS:
  95. if d in host:
  96. return d
  97. harFiles = []
  98. cookieFiles = []
  99. for root, dirs, files in os.walk(CookiesConfig.cookies_dir if dirPath is None else dirPath):
  100. for file in files:
  101. if file.endswith(".har"):
  102. harFiles.append(os.path.join(root, file))
  103. elif file.endswith(".json"):
  104. cookieFiles.append(os.path.join(root, file))
  105. CookiesConfig.cookies = {}
  106. for path in harFiles:
  107. with open(path, 'rb') as file:
  108. try:
  109. harFile = json.load(file)
  110. except json.JSONDecodeError:
  111. # Error: not a HAR file!
  112. continue
  113. if debug.logging:
  114. print("Read .har file:", path)
  115. new_cookies = {}
  116. for v in harFile['log']['entries']:
  117. domain = get_domain(v)
  118. if domain is None:
  119. continue
  120. v_cookies = {}
  121. for c in v['request']['cookies']:
  122. v_cookies[c['name']] = c['value']
  123. if len(v_cookies) > 0:
  124. CookiesConfig.cookies[domain] = v_cookies
  125. new_cookies[domain] = len(v_cookies)
  126. if debug.logging:
  127. for domain, new_values in new_cookies.items():
  128. print(f"Cookies added: {new_values} from {domain}")
  129. for path in cookieFiles:
  130. with open(path, 'rb') as file:
  131. try:
  132. cookieFile = json.load(file)
  133. except json.JSONDecodeError:
  134. # Error: not a json file!
  135. continue
  136. if not isinstance(cookieFile, list):
  137. continue
  138. if debug.logging:
  139. print("Read cookie file:", path)
  140. new_cookies = {}
  141. for c in cookieFile:
  142. if isinstance(c, dict) and "domain" in c:
  143. if c["domain"] not in new_cookies:
  144. new_cookies[c["domain"]] = {}
  145. new_cookies[c["domain"]][c["name"]] = c["value"]
  146. for domain, new_values in new_cookies.items():
  147. if debug.logging:
  148. print(f"Cookies added: {len(new_values)} from {domain}")
  149. CookiesConfig.cookies[domain] = new_values
  150. def _g4f(domain_name: str) -> list:
  151. """
  152. Load cookies from the 'g4f' browser (if exists).
  153. Args:
  154. domain_name (str): The domain for which to load cookies.
  155. Returns:
  156. list: List of cookies.
  157. """
  158. if not has_platformdirs:
  159. return []
  160. user_data_dir = user_config_dir("g4f")
  161. cookie_file = os.path.join(user_data_dir, "Default", "Cookies")
  162. return [] if not os.path.exists(cookie_file) else chrome(cookie_file, domain_name)