Spaces:
Sleeping
Sleeping
add content type auto-detection from magic bytes
Browse files6 unmodified lines789101011121314151617181920212223242526272829303132333435363738394041424344454647484950515219535455567 unmodified lines64656667686970717273347436377576776 unmodified linesfrom aiohttp import web
PORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"
pending = {}
# Magic byte signatures for content type detectionMAGIC_SIGNATURES = [ (b'\xff\xd8\xff', 'image/jpeg'), (b'\x89PNG\r\n\x1a\n', 'image/png'), (b'GIF87a', 'image/gif'), (b'GIF89a', 'image/gif'), (b'RIFF', 'image/webp', lambda b: b[8:12] == b'WEBP'), (b'%PDF', 'application/pdf'), (b'PK\x03\x04', 'application/zip'), (b'\x1aE\xdf\xa3', 'application/octet-stream'), # Matroska/WebM container]
def detect_content_type(body, fallback="application/octet-stream"): for sig in MAGIC_SIGNATURES: condition = True if len(sig) == 3: magic, ct = sig else: magic, ct, extra_check = sig condition = extra_check(body[:16]) if callable(extra_check) else True if body.startswith(magic) and condition: return ct # Check if it looks like HTML text = body[:500].decode('utf-8', errors='ignore').strip().lower() if text.startswith('<!doctype') or text.startswith('<html') or text.startswith('<!DOCTYPE') or text.startswith('<html'): return fallback if 'text/html' in fallback else fallback # Check if it looks like plain text try: body.decode('utf-8') # It's valid UTF-8 text - keep the fallback return fallback except (UnicodeDecodeError, ValueError): # Binary data - use detected type or octet-stream return "application/octet-stream"
async def proxy_handler(request): target_url = request.query.get("url") if not target_url: return web.json_response({"error": "missing url param"}, status=400) if not target_url.startswith(("http://", "https://")): target_url = TARGET_ORIGIN.rstrip("/") + "/" + target_url.lstrip("/") target_url = "https://" + target_url.lstrip("/")
rid = str(uuid.uuid4()) event = asyncio.Event()7 unmodified lines pending.pop(rid, None)
status = result.get("status", 502) body = result.get("body", b"upstream error") ct = result.get("content_type", "text/html") if ct in ("text/html", "text/plain", "application/octet-stream"): detected = detect_content_type(body, ct) if detected != ct: ct = detected if status != 200: body = result.get("body", b"upstream error") return web.Response(body=body, status=status, content_type="text/plain") body = result.get("body", b"") ct = result.get("content_type", "text/html") return web.Response(body=body, content_type=ct)
async def poll_handler(request):app.py+42-5