Spaces:
Sleeping
Sleeping
server-side cache (200 entries, 5min TTL), long-polling
Browse files1 unmodified line2345673 unmodified lines11121314151621 unmodified lines383940414243444546472 unmodified lines50515253545556575859606162636465666768697071727314 unmodified lines88899091929338 unmodified lines1321331341351361371381391401411421431441451 unmodified lineimport jsonimport osimport sysimport uuidimport urllib.parsefrom aiohttp import web3 unmodified linespending = {}poll_cond = asyncio.Condition()MAGIC_SIGNATURES = [(b'\xff\xd8\xff', 'image/jpeg'),(b'\x89PNG\r\n\x1a\n', 'image/png'),21 unmodified linesexcept (UnicodeDecodeError, ValueError):return "application/octet-stream"import aiohttpDIRECT_PREFIXES = ("https://cnth2.shabakaty.com/", "https://img.shabakaty.com/","https://cdn.shabakaty.com/", "https://static.shabakaty.com/")async def proxy_handler(request):target_url = request.query.get("url")2 unmodified linesif not target_url.startswith(("http://", "https://")):target_url = "https://" + target_url.lstrip("/")# Fetch CDN assets directly (fast, no router needed)if target_url.startswith(DIRECT_PREFIXES):try:import urllib.requestdef _fetch():req = urllib.request.Request(target_url, headers={"User-Agent": "Mozilla/5.0"})r = urllib.request.urlopen(req, timeout=20)return r.read(), r.getcode(), r.headers.get("Content-Type", "application/octet-stream")body, status, ct = await asyncio.to_thread(_fetch)if ct in ("text/html", "text/plain", "application/octet-stream"):detected = detect_content_type(body, ct)if detected != ct:ct = detectedreturn web.Response(body=body, status=status, content_type=ct)except Exception as e:return web.Response(body=str(e).encode(), status=502, content_type="text/plain")# Tunnel via router for geo-restricted URLsrid = str(uuid.uuid4())event = asyncio.Event()result = {"body": b"", "status": 502, "content_type": "text/plain"}14 unmodified linesdetected = 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)38 unmodified linesreturn web.json_response({"status": "ok"})async def health(request):return web.json_response({"status": "ok", "pending": len(pending), "port": PORT})async def root(request):return web.json_response({"status": "ok","service": "HTTP Long-Poll Tunnel Server","pending": len(pending),"port": PORT})async def cors_middleware(app, handler):1 unmodified line23456783 unmodified lines1213141516171819202121 unmodified lines434445464748495051525354555657585960612 unmodified lines6465666768697071727314 unmodified lines8889909192939438 unmodified lines1331341351361371381391401411421431441451461471 unmodified lineimport jsonimport osimport sysimport timeimport uuidimport urllib.parsefrom aiohttp import web3 unmodified linespending = {}poll_cond = asyncio.Condition()CACHE = {}CACHE_MAX = 200CACHE_TTL = 300MAGIC_SIGNATURES = [(b'\xff\xd8\xff', 'image/jpeg'),(b'\x89PNG\r\n\x1a\n', 'image/png'),21 unmodified linesexcept (UnicodeDecodeError, ValueError):return "application/octet-stream"def cache_get(url):if url in CACHE:entry = CACHE[url]if time.time() - entry["ts"] < CACHE_TTL:return entrydel CACHE[url]return Nonedef cache_set(url, status, ct, body):if len(CACHE) >= CACHE_MAX:oldest = min(CACHE.keys(), key=lambda k: CACHE[k]["ts"])del CACHE[oldest]CACHE[url] = {"ts": time.time(), "status": status, "ct": ct, "body": body}async def proxy_handler(request):target_url = request.query.get("url")2 unmodified linesif not target_url.startswith(("http://", "https://")):target_url = "https://" + target_url.lstrip("/")cached = cache_get(target_url)if cached:return web.Response(body=cached["body"], status=cached["status"], content_type=cached["ct"])rid = str(uuid.uuid4())event = asyncio.Event()result = {"body": b"", "status": 502, "content_type": "text/plain"}14 unmodified linesdetected = detect_content_type(body, ct)if detected != ct:ct = detectedcache_set(target_url, status, ct, body)if status != 200:return web.Response(body=body, status=status, content_type="text/plain")return web.Response(body=body, content_type=ct)38 unmodified linesreturn web.json_response({"status": "ok"})async def health(request):return web.json_response({"status": "ok", "pending": len(pending), "port": PORT, "cache": len(CACHE)})async def root(request):return web.json_response({"status": "ok","service": "HTTP Long-Poll Tunnel Server","pending": len(pending),"port": PORT,"cache": len(CACHE)})async def cors_middleware(app, handler):
app.py+25-23