Skip to content

Commit

Permalink
feat: when secure_1psid is not provided, loop through all local cache…
Browse files Browse the repository at this point in the history
…d cookies instead of raising value error

ref #33
  • Loading branch information
HanaokaYuzu committed Sep 11, 2024
1 parent 17b786f commit 84021ab
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 16 deletions.
7 changes: 2 additions & 5 deletions src/gemini_webapi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,7 @@ class GeminiClient:
Raises
------
`ValueError`
If `secure_1psid` is not provided and optional dependency `browser-cookie3` is not installed, or
`browser-cookie3` is installed but cookies for google.com are not found in your local browser storage.
If `browser-cookie3` is installed but cookies for google.com are not found in your local browser storage.
"""

__slots__ = [
Expand Down Expand Up @@ -132,9 +131,7 @@ def __init__(
"Failed to load cookies from local browser. Please pass cookie values manually."
)
except ImportError:
raise ValueError(
"'secure_1psid' must be provided if optional dependency 'browser-cookie3' is not installed."
)
pass

async def init(
self,
Expand Down
41 changes: 32 additions & 9 deletions src/gemini_webapi/utils/get_access_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,25 +58,47 @@ async def send_request(cookies: dict) -> tuple[Response | None, dict]:

tasks = []

if "__Secure-1PSID" in base_cookies:
# Base cookies passed directly on initializing client
if "__Secure-1PSID" in base_cookies and "__Secure-1PSIDTS" in base_cookies:
tasks.append(Task(send_request(base_cookies)))
elif verbose:
logger.debug(
"Skipping loading base cookies. Either __Secure-1PSID or __Secure-1PSIDTS is not provided."
)

# Cached cookies in local file
cache_dir = Path(__file__).parent / "temp"
if "__Secure-1PSID" in base_cookies:
filename = f".cached_1psidts_{base_cookies['__Secure-1PSID']}.txt"
path = Path(__file__).parent / "temp" / filename
if path.is_file():
cached_1psidts = path.read_text()
cache_file = cache_dir / filename
if cache_file.is_file():
cached_1psidts = cache_file.read_text()
if cached_1psidts:
cached_cookies = {**base_cookies, "__Secure-1PSIDTS": cached_1psidts}
tasks.append(Task(send_request(cached_cookies)))
elif verbose:
logger.debug("Skipping loading cached cookies. Cache file is empty.")
elif verbose:
logger.debug("Skipping loading cached cookies. Cache file not found.")
elif verbose:
logger.debug(
"Skipping loading base cookies and cached cookies. __Secure-1PSID is not provided."
)
else:
valid_caches = 0
cache_files = cache_dir.glob(".cached_1psidts_*.txt")
for cache_file in cache_files:
cached_1psidts = cache_file.read_text()
if cached_1psidts:
cached_cookies = {
"__Secure-1PSID": cache_file.stem[16:],
"__Secure-1PSIDTS": cached_1psidts,
}
tasks.append(Task(send_request(cached_cookies)))
valid_caches += 1

if valid_caches == 0 and verbose:
logger.debug(
"Skipping loading cached cookies. Cookies will be cached after successful initialization."
)

# Browser cookies (if browser-cookie3 is installed)
try:
browser_cookies = load_browser_cookies(
domain_name="google.com", verbose=verbose
Expand Down Expand Up @@ -120,5 +142,6 @@ async def send_request(cookies: dict) -> tuple[Response | None, dict]:
)

raise AuthError(
"Failed to initialize client. SECURE_1PSIDTS could get expired frequently, please make sure cookie values are up to date."
"Failed to initialize client. SECURE_1PSIDTS could get expired frequently, please make sure cookie values are up to date. "
f"(Failed initialization attempts: {len(tasks)})"
)
4 changes: 2 additions & 2 deletions tests/test_client_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ async def asyncSetUp(self):

try:
await self.geminiclient.init()
except AuthError:
self.skipTest("Test was skipped due to invalid cookies")
except AuthError as e:
self.skipTest(e)

@logger.catch(reraise=True)
async def test_successful_request(self):
Expand Down

0 comments on commit 84021ab

Please sign in to comment.