longxingdeng commited on
Commit
bf0a455
·
1 Parent(s): 22fdea8

Retry Gemini image proxy without cookies

Browse files
Files changed (1) hide show
  1. main.py +64 -50
main.py CHANGED
@@ -1985,58 +1985,72 @@ async def proxy_image(url: str, sig: str):
1985
  jar.set("__Secure-1PSID", psid, domain=".googleusercontent.com")
1986
  jar.set("__Secure-1PSIDTS", psidts, domain=".googleusercontent.com")
1987
 
1988
- async with httpx.AsyncClient(http2=True, cookies=jar, follow_redirects=True) as client:
1989
- try:
1990
- # Fetch original resolution to keep watermark at expected size/position
1991
- fetch_url = re.sub(r"=s\d+$", "=s0", url) if re.search(r"=s\d+$", url) else url + "=s0"
1992
-
1993
- async with client.stream("GET", fetch_url, timeout=15.0, headers=headers) as resp:
1994
- if resp.status_code != 200:
1995
- logger.error(f"Google returned {resp.status_code} for image: {url}")
1996
-
1997
- resp.raise_for_status()
1998
-
1999
- content = bytearray()
2000
- async for chunk in resp.aiter_bytes():
2001
- content.extend(chunk)
2002
- if len(content) > MAX_BYTES:
2003
- logger.warning(f"Image too large: {url} (exceeded {MAX_BYTES} bytes)")
2004
- raise HTTPException(status_code=413, detail="Image too large")
2005
- # Validate Content-Type to prevent XSS/MIME sniffing
2006
- upstream_content_type = resp.headers.get("content-type", "image/png").lower()
2007
- if not upstream_content_type.startswith("image/"):
2008
- logger.warning(f"Rejected non-image Content-Type: {upstream_content_type} for {url}")
2009
- media_type = "image/png"
2010
- else:
2011
- media_type = upstream_content_type
2012
-
2013
- # Process watermark removal
2014
- if media_type in ["image/png", "image/jpeg", "image/webp"]:
2015
- processed_content = remove_gemini_watermark(bytes(content))
2016
- else:
2017
- processed_content = bytes(content)
2018
-
2019
- return Response(
2020
- content=processed_content,
2021
- media_type=media_type,
2022
- headers={
2023
- "Cross-Origin-Resource-Policy": "cross-origin",
2024
- "Access-Control-Allow-Origin": "*",
2025
- "Cache-Control": "public, max-age=86400", # Cache for 24 hours
2026
- "X-Content-Type-Options": "nosniff",
2027
- },
2028
- )
2029
- except httpx.HTTPStatusError as e:
2030
- logger.error(f"Failed to fetch image: {e.response.status_code} for {url}")
 
 
 
 
 
 
 
 
2031
  raise HTTPException(
2032
- status_code=e.response.status_code,
2033
- detail=f"Failed to fetch image: Google returned {e.response.status_code}",
2034
  )
2035
- except HTTPException:
2036
- raise
2037
- except Exception as e:
2038
- logger.error(f"Proxy error: {str(e)}")
2039
- raise HTTPException(status_code=500, detail="Internal proxy error")
 
 
 
 
 
 
2040
 
2041
 
2042
  @app.get("/")
 
1985
  jar.set("__Secure-1PSID", psid, domain=".googleusercontent.com")
1986
  jar.set("__Secure-1PSIDTS", psidts, domain=".googleusercontent.com")
1987
 
1988
+ # Try the authenticated request first, then retry without Google cookies. Some
1989
+ # signed Gemini image redirects reject account cookies even though the original
1990
+ # image URL is valid for an anonymous CDN request.
1991
+ # Keep the URL exactly as issued by Gemini; changing its size suffix can invalidate
1992
+ # the short-lived signature on the redirected resource.
1993
+ fetch_url = url
1994
+ request_attempts = [("authenticated", jar), ("anonymous", None)]
1995
+ last_status = None
1996
+ try:
1997
+ for attempt_name, request_cookies in request_attempts:
1998
+ async with httpx.AsyncClient(http2=True, cookies=request_cookies, follow_redirects=True) as client:
1999
+ async with client.stream("GET", fetch_url, timeout=15.0, headers=headers) as resp:
2000
+ if resp.status_code != 200:
2001
+ last_status = resp.status_code
2002
+ if resp.status_code == 403 and attempt_name == "authenticated":
2003
+ logger.warning("Google rejected the authenticated image fetch; retrying anonymously")
2004
+ continue
2005
+ logger.error(f"Google returned {resp.status_code} for image: {url}")
2006
+ resp.raise_for_status()
2007
+
2008
+ content = bytearray()
2009
+ async for chunk in resp.aiter_bytes():
2010
+ content.extend(chunk)
2011
+ if len(content) > MAX_BYTES:
2012
+ logger.warning(f"Image too large: {url} (exceeded {MAX_BYTES} bytes)")
2013
+ raise HTTPException(status_code=413, detail="Image too large")
2014
+ # Validate Content-Type to prevent XSS/MIME sniffing
2015
+ upstream_content_type = resp.headers.get("content-type", "image/png").lower()
2016
+ if not upstream_content_type.startswith("image/"):
2017
+ logger.warning(f"Rejected non-image Content-Type: {upstream_content_type} for {url}")
2018
+ media_type = "image/png"
2019
+ else:
2020
+ media_type = upstream_content_type
2021
+
2022
+ # Process watermark removal
2023
+ if media_type in ["image/png", "image/jpeg", "image/webp"]:
2024
+ processed_content = remove_gemini_watermark(bytes(content))
2025
+ else:
2026
+ processed_content = bytes(content)
2027
+
2028
+ return Response(
2029
+ content=processed_content,
2030
+ media_type=media_type,
2031
+ headers={
2032
+ "Cross-Origin-Resource-Policy": "cross-origin",
2033
+ "Access-Control-Allow-Origin": "*",
2034
+ "Cache-Control": "public, max-age=86400", # Cache for 24 hours
2035
+ "X-Content-Type-Options": "nosniff",
2036
+ },
2037
+ )
2038
+ if last_status is not None:
2039
  raise HTTPException(
2040
+ status_code=last_status,
2041
+ detail=f"Failed to fetch image: Google returned {last_status}",
2042
  )
2043
+ except httpx.HTTPStatusError as e:
2044
+ logger.error(f"Failed to fetch image: {e.response.status_code} for {url}")
2045
+ raise HTTPException(
2046
+ status_code=e.response.status_code,
2047
+ detail=f"Failed to fetch image: Google returned {e.response.status_code}",
2048
+ )
2049
+ except HTTPException:
2050
+ raise
2051
+ except Exception as e:
2052
+ logger.error(f"Proxy error: {str(e)}")
2053
+ raise HTTPException(status_code=500, detail="Internal proxy error")
2054
 
2055
 
2056
  @app.get("/")