Spaces:
Sleeping
Sleeping
add content type auto-detection from magic bytes
Browse files6 unmodified lines789101112131415161718192021227 unmodified lines30313233343536373839406 unmodified linesfrom aiohttp import webPORT = int(os.environ.get("PORT", 7860))TARGET_ORIGIN = "https://shabakaty.com"pending = {}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("/")rid = str(uuid.uuid4())event = asyncio.Event()7 unmodified linespending.pop(rid, None)status = result.get("status", 502)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):6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455567 unmodified lines64656667686970717273747576776 unmodified linesfrom aiohttp import webPORT = int(os.environ.get("PORT", 7860))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 = Trueif len(sig) == 3:magic, ct = sigelse:magic, ct, extra_check = sigcondition = extra_check(body[:16]) if callable(extra_check) else Trueif body.startswith(magic) and condition:return ct# Check if it looks like HTMLtext = 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 texttry:body.decode('utf-8')# It's valid UTF-8 text - keep the fallbackreturn fallbackexcept (UnicodeDecodeError, ValueError):# Binary data - use detected type or octet-streamreturn "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 = "https://" + target_url.lstrip("/")rid = str(uuid.uuid4())event = asyncio.Event()7 unmodified linespending.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 = detectedif status != 200:return web.Response(body=body, status=status, content_type="text/plain")return web.Response(body=body, content_type=ct)async def poll_handler(request):
app.py+42-5