54 lines
1.9 KiB
Python
54 lines
1.9 KiB
Python
import io
|
|
from dataclasses import dataclass
|
|
|
|
from PIL import Image, ImageFile, UnidentifiedImageError
|
|
|
|
from app.errors import AppError
|
|
|
|
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
|
|
|
_PNG = b"\x89PNG\r\n\x1a\n"
|
|
_JPEG = b"\xff\xd8\xff"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ImageMeta:
|
|
content_type: str
|
|
|
|
|
|
def declared_content_type(header: str | None) -> str:
|
|
value = (header or "").split(";", 1)[0].strip().lower()
|
|
if value in {"image/png", "image/jpeg"}:
|
|
return value
|
|
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
|
|
|
|
|
|
def sniff_content_type(data: bytes) -> str | None:
|
|
if data.startswith(_PNG):
|
|
return "image/png"
|
|
if data.startswith(_JPEG):
|
|
return "image/jpeg"
|
|
return None
|
|
|
|
|
|
def inspect_image(data: bytes, declared: str, max_pixels: int) -> ImageMeta:
|
|
sniffed = sniff_content_type(data)
|
|
if sniffed is None or sniffed != declared:
|
|
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
|
|
Image.MAX_IMAGE_PIXELS = max_pixels
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
width, height = image.size
|
|
if width < 1 or height < 1:
|
|
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
|
|
if width * height > max_pixels:
|
|
raise AppError(413, "payload_too_large", "Слишком большое изображение")
|
|
image.verify()
|
|
except AppError:
|
|
raise
|
|
except Image.DecompressionBombError:
|
|
raise AppError(413, "payload_too_large", "Слишком большое изображение") from None
|
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
|
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") from None
|
|
return ImageMeta(content_type=declared)
|