cookies.py 6.4 KB

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