from urllib.parse import urlsplit import httpx from config.settings import settings # 공유 이미지에 행사 사진을 그리려고 대신 받아 준다. 사진 서버가 브라우저가 픽셀을 읽는 것(CORS)을 막기 때문. 허용 호스트는 IMAGE_PROXY_HOSTS. MAX_BYTES = 5 * 1024 * 1024 TIMEOUT_SEC = 10.0 class ImageFetchFailed(Exception): pass def allowed(url: str) -> bool: """https, 허용한 호스트, 기본 포트, 계정 정보 없음일 때만.""" try: u = urlsplit(url) port = u.port except ValueError: return False return u.scheme == "https" and u.hostname in settings.image_proxy_host_set and port in (None, 443) and not u.username and not u.password async def fetch_image(client: httpx.AsyncClient, url: str) -> tuple[bytes, str]: """이미지 바이트와 content-type. 리다이렉트는 따라가지 않는다.""" async with client.stream("GET", url, follow_redirects=False) as res: if res.status_code != 200: raise ImageFetchFailed(f"status {res.status_code}") ctype = res.headers.get("content-type", "").split(";")[0].strip().lower() if not ctype.startswith("image/") or ctype == "image/svg+xml": raise ImageFetchFailed(f"content-type {ctype or '-'}") buf = bytearray() async for chunk in res.aiter_bytes(): buf += chunk if len(buf) > MAX_BYTES: raise ImageFetchFailed("too large") return bytes(buf), ctype