37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
|
|
"""
|
||
|
|
Platform Gateway — Image proxy (bypass hotlink protection).
|
||
|
|
"""
|
||
|
|
|
||
|
|
import urllib.request
|
||
|
|
import urllib.parse
|
||
|
|
|
||
|
|
from config import _ssl_ctx
|
||
|
|
|
||
|
|
|
||
|
|
def handle_image_proxy(handler):
|
||
|
|
"""Proxy external images to bypass hotlink protection (e.g. Reddit)."""
|
||
|
|
qs = urllib.parse.urlparse(handler.path).query
|
||
|
|
params = urllib.parse.parse_qs(qs)
|
||
|
|
url = params.get("url", [None])[0]
|
||
|
|
if not url:
|
||
|
|
handler._send_json({"error": "Missing url parameter"}, 400)
|
||
|
|
return
|
||
|
|
try:
|
||
|
|
req = urllib.request.Request(url, headers={
|
||
|
|
"User-Agent": "Mozilla/5.0 (compatible; PlatformProxy/1.0)",
|
||
|
|
"Accept": "image/*,*/*",
|
||
|
|
"Referer": urllib.parse.urlparse(url).scheme + "://" + urllib.parse.urlparse(url).netloc + "/",
|
||
|
|
})
|
||
|
|
resp = urllib.request.urlopen(req, timeout=10, context=_ssl_ctx)
|
||
|
|
body = resp.read()
|
||
|
|
ct = resp.headers.get("Content-Type", "image/jpeg")
|
||
|
|
handler.send_response(200)
|
||
|
|
handler.send_header("Content-Type", ct)
|
||
|
|
handler.send_header("Content-Length", len(body))
|
||
|
|
handler.send_header("Cache-Control", "public, max-age=86400")
|
||
|
|
handler.end_headers()
|
||
|
|
handler.wfile.write(body)
|
||
|
|
except Exception as e:
|
||
|
|
print(f"[ImageProxy] Error fetching {url}: {e}")
|
||
|
|
handler._send_json({"error": "Failed to fetch image"}, 502)
|