Files
o2o-weather/backend/services/talk_image.py

88 lines
3.5 KiB
Python

import io
import os
import re
import uuid
from typing import Optional
from azure.core.exceptions import AzureError
from azure.storage.blob import BlobServiceClient, ContainerClient, ContentSettings
from PIL import Image, ImageOps, UnidentifiedImageError
from config.settings import settings
from common.enums import ErrorType
from common.logger import LOG
MAX_BYTES = 10 * 1024 * 1024 # 올릴 수 있는 원본 크기
MAX_SIDE = 1080 # 긴 변을 이만큼으로 줄인다
URL_PREFIX = "/v1/talk/image/"
_NAME = re.compile(r"^[0-9a-f]{32}\.webp$")
def folder() -> str:
path = os.path.join(settings.upload_dir, "talk")
os.makedirs(path, exist_ok=True)
return path
def _container() -> Optional[ContainerClient]:
"""Azure Blob 컨테이너: 접속 문자열 또는 컨테이너 주소 + SAS 토큰. 둘 다 없으면 None (서버 폴더에 저장)"""
if settings.azure_storage_connection_string and settings.azure_storage_container:
return BlobServiceClient.from_connection_string(settings.azure_storage_connection_string).get_container_client(settings.azure_storage_container)
if settings.azure_blob_base_url and settings.azure_blob_sas_token:
return ContainerClient.from_container_url(f"{settings.azure_blob_base_url.rstrip('/')}?{settings.azure_blob_sas_token.lstrip('?')}")
return None
def _public(url: str) -> str:
"""글에 붙일 주소: SAS 토큰(쓰기 권한)을 떼어 낸 공개 주소"""
return url.split("?", 1)[0]
def _blob_name(name: str) -> str:
return f"{settings.azure_storage_prefix.strip('/')}/talk/{name}"
def is_ours(url: str) -> bool:
"""우리가 올린 사진 주소인지: 서버 폴더에 있거나, 우리 Blob 폴더의 우리가 만든 이름"""
if file_of(url) is not None:
return True
c = _container()
if c is None:
return False
base = f"{_public(c.url)}/{_blob_name('')}"
return url.startswith(base) and bool(_NAME.match(url.removeprefix(base)))
def file_of(url: str) -> Optional[str]:
"""올린 사진 주소 → 저장된 파일 경로. 우리가 만든 이름이 아니거나 파일이 없으면 None."""
name = url.removeprefix(URL_PREFIX)
if not url.startswith(URL_PREFIX) or not _NAME.match(name):
return None
path = os.path.join(folder(), name)
return path if os.path.isfile(path) else None
def save(data: bytes) -> tuple[ErrorType, Optional[str]]:
"""사진을 다시 그려 저장한다(Azure Blob, 설정이 없으면 서버 폴더). 다시 그리면 찍은 위치(GPS)·기기 같은 메타데이터가 모두 빠진다. 돌려준 값은 글에 붙일 주소."""
if len(data) > MAX_BYTES:
return ErrorType.INVALID_INPUT, None
try:
with Image.open(io.BytesIO(data)) as src:
img = ImageOps.exif_transpose(src).convert("RGB")
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
return ErrorType.INVALID_INPUT, None
img.thumbnail((MAX_SIDE, MAX_SIDE))
name = f"{uuid.uuid4().hex}.webp"
c = _container()
if c is None:
img.save(os.path.join(folder(), name), "WEBP", quality=82)
return ErrorType.SUCCESS, URL_PREFIX + name
buf = io.BytesIO()
img.save(buf, "WEBP", quality=82)
try:
blob = c.upload_blob(_blob_name(name), buf.getvalue(), content_settings=ContentSettings(content_type="image/webp", cache_control="public, max-age=31536000, immutable"))
except AzureError as e:
LOG.error(f"[talk_image] blob upload: {e}")
return ErrorType.EXTERNAL_API_ERROR, None
return ErrorType.SUCCESS, _public(blob.url)