import httpx from fastapi import APIRouter, HTTPException, Query from fastapi.responses import Response from common.logger import LOG from services.external.image_proxy import TIMEOUT_SEC, ImageFetchFailed, allowed, fetch_image router = APIRouter(prefix="/v1/image", tags=["image"]) # 이미지 자체를 돌려주므로 다른 API 와 달리 실패는 HTTP 상태 코드로 알린다 @router.get("", summary="행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)", responses={200: {"content": {"image/*": {}}}, 400: {}, 502: {}}) async def get_image(url: str = Query(..., max_length=2048, description="원본 이미지 주소")) -> Response: if not allowed(url): raise HTTPException(status_code=400, detail="url not allowed") try: async with httpx.AsyncClient(timeout=TIMEOUT_SEC, headers={"User-Agent": "nalssigak-bot"}) as client: data, ctype = await fetch_image(client, url) except (ImageFetchFailed, httpx.HTTPError) as e: LOG.warning(f"[image] fetch failed {url}: {e!r}") raise HTTPException(status_code=502, detail="image fetch failed") from e return Response(content=data, media_type=ctype, headers={"Cache-Control": "public, max-age=86400", "X-Content-Type-Options": "nosniff"})