import base64 import binascii from datetime import timedelta from fastapi import APIRouter, Depends, HTTPException, Path, Query from fastapi.responses import Response from common.auth import require_admin from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import CardSet from common.enums import CardStatus, ErrorType from common.logger import LOG from common.models.errors import error_info from common.utils.kma_time import KST, kst_midnight, now_kst from crud.card_crud import CardCRUD from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList from services.external import instagram from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day router = APIRouter(prefix="/v1/card", tags=["card"]) _MAX_IMAGE_BYTES = 5 * 1024 * 1024 _crud = CardCRUD() def image_url(card_id: int, seq: int) -> str: return f"/v1/card/{card_id}/{seq}.jpg" def _jpegs(images: list[str]) -> list[bytes]: out = [] for i, b64 in enumerate(images, 1): try: data = base64.b64decode(b64.split(",", 1)[-1], validate=True) except (binascii.Error, ValueError) as e: raise HTTPException(status_code=400, detail=f"image {i}: base64 아님") from e if not data.startswith(b"\xff\xd8") or len(data) > _MAX_IMAGE_BYTES: raise HTTPException(status_code=400, detail=f"image {i}: 5MB 이하 JPEG 만") out.append(data) return out async def _publish(card_id: int) -> tuple[ErrorType, Res_Card]: """그날(03:00 기준) 전국 피드에 올리고 피드 캐시를 지워 바로 보이게 한다. 다음 날 03:00 에 피드에서 빠진다.""" now = now_kst() day = feed_day(now) end = kst_midnight(day + timedelta(days=1)) + timedelta(hours=_FEED_DAY_START) async def run(s): card = await _crud.get(s, card_id) if card is None: return None if card.status != CardStatus.PUBLISHED.value: await _crud.publish(s, card, day, now, end) return card err, card = await DB_SESSION_MNG.execute_lambda_write(run) if err is not ErrorType.SUCCESS: return err, Res_Card(result=error_info(err)) if card is None: return ErrorType.NOT_FOUND, Res_Card(result=error_info(ErrorType.NOT_FOUND)) await clear_feed_cache() LOG.info(f"[card] publish {card_id} → post {card.post_id}") return ErrorType.SUCCESS, Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id) @router.get("", response_model=Res_CardList, response_model_exclude_none=True, summary="만든 카드뉴스 목록 (관리자). 다시 내려받거나 올릴 때", dependencies=[Depends(require_admin)]) async def list_cards(limit: int = Query(50, ge=1, le=200)) -> Res_CardList: err, cards = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.recent(s, limit)) if err is not ErrorType.SUCCESS: return Res_CardList(result=error_info(err)) _, counts = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image_counts(s, [c.card_id for c in cards])) counts = counts or {} return Res_CardList(items=[ CardItem(card_id=c.card_id, template=c.template, topic=c.topic, title=c.title, status=CardStatus(c.status), post_id=c.post_id, created_at=c.created_at.astimezone(KST), published_at=c.published_at.astimezone(KST) if c.published_at else None, image_urls=[image_url(c.card_id, i) for i in range(1, counts.get(c.card_id, 0) + 1)], ig_media_id=c.ig_media_id) for c in cards ]) @router.post("", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스 저장 (관리자). publish 면 바로 그날 피드에 올린다", dependencies=[Depends(require_admin)]) async def create_card(req: Req_CardCreate) -> Res_Card: images = _jpegs(req.images) card = CardSet(template=req.template, topic=req.topic, title=req.title, caption=req.caption, copy=req.texts, status=CardStatus.WAITING.value) err, card = await DB_SESSION_MNG.execute_lambda_write(lambda s: _crud.create(s, card, images)) if err is not ErrorType.SUCCESS: return Res_Card(result=error_info(err)) urls = [image_url(card.card_id, i) for i in range(1, len(images) + 1)] if req.publish: _, res = await _publish(card.card_id) res.image_urls = urls return res return Res_Card(card_id=card.card_id, status=CardStatus.WAITING, image_urls=urls) @router.post("/{card_id}/publish", response_model=Res_Card, response_model_exclude_none=True, summary="승인 대기 카드뉴스를 그날 피드에 올리기 (관리자)", dependencies=[Depends(require_admin)]) async def publish_card(card_id: int = Path(...)) -> Res_Card: _, res = await _publish(card_id) return res @router.post("/{card_id}/reject", response_model=Res_Card, response_model_exclude_none=True, summary="승인 대기 카드뉴스 반려 (관리자)", dependencies=[Depends(require_admin)]) async def reject_card(card_id: int = Path(...)) -> Res_Card: async def run(s): card = await _crud.get(s, card_id) if card is not None and card.status == CardStatus.WAITING.value: card.status = CardStatus.REJECTED.value return card err, card = await DB_SESSION_MNG.execute_lambda_write(run) if err is not ErrorType.SUCCESS: return Res_Card(result=error_info(err)) if card is None: return Res_Card(result=error_info(ErrorType.NOT_FOUND)) return Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id) @router.post("/{card_id}/instagram", response_model=Res_Card, response_model_exclude_none=True, summary="카드뉴스를 인스타그램에 캐러셀로 올리기 (관리자). 같은 카드는 한 번만", dependencies=[Depends(require_admin)]) async def publish_instagram(card_id: int = Path(...)) -> Res_Card: if not instagram.configured(): return Res_Card(result=error_info(ErrorType.INVALID_INPUT), msg="INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 설정되지 않았어요") err, card = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.get(s, card_id)) if err is not ErrorType.SUCCESS: return Res_Card(result=error_info(err)) if card is None: return Res_Card(result=error_info(ErrorType.NOT_FOUND)) if card.ig_media_id: return Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id, ig_media_id=card.ig_media_id) _, counts = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image_counts(s, [card_id])) urls = [instagram.public_image_url(image_url(card_id, i)) for i in range(1, (counts or {}).get(card_id, 0) + 1)] caption = f"{card.title}\n\n{card.caption}".strip() try: media_id = await instagram.publish_carousel(urls, caption) except instagram.InstagramError as e: LOG.error(f"[card] instagram {card_id}: {e}") return Res_Card(result=error_info(ErrorType.EXTERNAL_API_ERROR), msg=str(e), card_id=card_id) async def save(s): c = await _crud.get(s, card_id) if c is not None: c.ig_media_id = media_id return c err, saved = await DB_SESSION_MNG.execute_lambda_write(save) if err is not ErrorType.SUCCESS or saved is None: return Res_Card(result=error_info(err if err is not ErrorType.SUCCESS else ErrorType.NOT_FOUND), msg=f"인스타엔 올라갔지만({media_id}) 저장 실패") return Res_Card(card_id=card_id, status=CardStatus(saved.status), post_id=saved.post_id, ig_media_id=media_id) # 이미지 자체를 돌려주므로 실패는 HTTP 상태 코드로 알린다 @router.get("/{card_id}/{seq}.jpg", summary="카드뉴스 이미지", responses={200: {"content": {"image/jpeg": {}}}, 404: {}}) async def get_card_image(card_id: int = Path(...), seq: int = Path(..., ge=1, le=20)) -> Response: err, data = await DB_SESSION_MNG.execute_lambda(lambda s: _crud.image(s, card_id, seq)) if err is not ErrorType.SUCCESS or data is None: raise HTTPException(status_code=404, detail="not found") return Response(content=data, media_type="image/jpeg", headers={"Cache-Control": "public, max-age=31536000, immutable", "X-Content-Type-Options": "nosniff"})