cookies.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. "huggingface.co",
  55. ".huggingface.co"
  56. ]
  57. if has_browser_cookie3 and os.environ.get('DBUS_SESSION_BUS_ADDRESS') == "/dev/null":
  58. _LinuxPasswordManager.get_password = lambda a, b: b"secret"
  59. def get_cookies(domain_name: str = '', raise_requirements_error: bool = True, single_browser: bool = False) -> Dict[str, str]:
  60. """
  61. Load cookies for a given domain from all supported browsers and cache the results.
  62. Args:
  63. domain_name (str): The domain for which to load cookies.
  64. Returns:
  65. Dict[str, str]: A dictionary of cookie names and values.
  66. """
  67. if domain_name in CookiesConfig.cookies:
  68. return CookiesConfig.cookies[domain_name]
  69. cookies = load_cookies_from_browsers(domain_name, raise_requirements_error, single_browser)
  70. CookiesConfig.cookies[domain_name] = cookies
  71. return cookies
  72. def set_cookies(domain_name: str, cookies: Cookies = None) -> None:
  73. if cookies:
  74. CookiesConfig.cookies[domain_name] = cookies
  75. elif domain_name in CookiesConfig.cookies:
  76. CookiesConfig.cookies.pop(domain_name)
  77. def load_cookies_from_browsers(domain_name: str, raise_requirements_error: bool = True, single_browser: bool = False) -> Cookies:
  78. """
  79. Helper function to load cookies from various browsers.
  80. Args:
  81. domain_name (str): The domain for which to load cookies.
  82. Returns:
  83. Dict[str, str]: A dictionary of cookie names and values.
  84. """
  85. if not has_browser_cookie3:
  86. if raise_requirements_error:
  87. raise MissingRequirementsError('Install "browser_cookie3" package')
  88. return {}
  89. cookies = {}
  90. for cookie_fn in browsers:
  91. try:
  92. cookie_jar = cookie_fn(domain_name=domain_name)
  93. if len(cookie_jar) and debug.logging:
  94. print(f"Read cookies from {cookie_fn.__name__} for {domain_name}")
  95. for cookie in cookie_jar:
  96. if cookie.name not in cookies:
  97. if not cookie.expires or cookie.expires > time.time():
  98. cookies[cookie.name] = cookie.value
  99. if single_browser and len(cookie_jar):
  100. break
  101. except BrowserCookieError:
  102. pass
  103. except Exception as e:
  104. if debug.logging:
  105. print(f"Error reading cookies from {cookie_fn.__name__} for {domain_name}: {e}")
  106. return cookies
  107. def set_cookies_dir(dir: str) -> None:
  108. CookiesConfig.cookies_dir = dir
  109. def get_cookies_dir() -> str:
  110. return CookiesConfig.cookies_dir
  111. def read_cookie_files(dirPath: str = None):
  112. dirPath = CookiesConfig.cookies_dir if dirPath is None else dirPath
  113. if not os.access(dirPath, os.R_OK):
  114. debug.log(f"Read cookies: {dirPath} dir is not readable")
  115. return
  116. def get_domain(v: dict) -> str:
  117. host = [h["value"] for h in v['request']['headers'] if h["name"].lower() in ("host", ":authority")]
  118. if not host:
  119. return
  120. host = host.pop()
  121. for d in DOMAINS:
  122. if d in host:
  123. return d
  124. harFiles = []
  125. cookieFiles = []
  126. for root, _, files in os.walk(dirPath):
  127. for file in files:
  128. if file.endswith(".har"):
  129. harFiles.append(os.path.join(root, file))
  130. elif file.endswith(".json"):
  131. cookieFiles.append(os.path.join(root, file))
  132. CookiesConfig.cookies = {}
  133. for path in harFiles:
  134. with open(path, 'rb') as file:
  135. try:
  136. harFile = json.load(file)
  137. except json.JSONDecodeError:
  138. # Error: not a HAR file!
  139. continue
  140. debug.log(f"Read .har file: {path}")
  141. new_cookies = {}
  142. for v in harFile['log']['entries']:
  143. domain = get_domain(v)
  144. if domain is None:
  145. continue
  146. v_cookies = {}
  147. for c in v['request']['cookies']:
  148. v_cookies[c['name']] = c['value']
  149. if len(v_cookies) > 0:
  150. CookiesConfig.cookies[domain] = v_cookies
  151. new_cookies[domain] = len(v_cookies)
  152. for domain, new_values in new_cookies.items():
  153. debug.log(f"Cookies added: {new_values} from {domain}")
  154. for path in cookieFiles:
  155. with open(path, 'rb') as file:
  156. try:
  157. cookieFile = json.load(file)
  158. except json.JSONDecodeError:
  159. # Error: not a json file!
  160. continue
  161. if not isinstance(cookieFile, list) or not isinstance(cookieFile[0], dict) or "domain" not in cookieFile[0]:
  162. continue
  163. debug.log(f"Read cookie file: {path}")
  164. new_cookies = {}
  165. for c in cookieFile:
  166. if isinstance(c, dict) and "domain" in c:
  167. if c["domain"] not in new_cookies:
  168. new_cookies[c["domain"]] = {}
  169. new_cookies[c["domain"]][c["name"]] = c["value"]
  170. for domain, new_values in new_cookies.items():
  171. debug.log(f"Cookies added: {len(new_values)} from {domain}")
  172. CookiesConfig.cookies[domain] = new_values