96 lines
2.5 KiB
Python
96 lines
2.5 KiB
Python
from __future__ import annotations
|
|
|
|
import io
|
|
import unicodedata
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
|
|
from app.errors import ApiError, invalid
|
|
|
|
|
|
MAX_BYTES = 10 * 1024 * 1024
|
|
MAX_PIXELS = 40_000_000
|
|
|
|
FORMAT_TO_MIME = {
|
|
"PNG": "image/png",
|
|
"JPEG": "image/jpeg",
|
|
}
|
|
|
|
|
|
def validate_filename(value: str | None) -> str:
|
|
if (
|
|
value is None
|
|
or not 1 <= len(value) <= 255
|
|
or not value.strip()
|
|
):
|
|
raise invalid("Некорректное имя файла")
|
|
|
|
for char in value:
|
|
if char in "/\\" or unicodedata.category(char) == "Cc":
|
|
raise invalid("Некорректное имя файла")
|
|
|
|
return value
|
|
|
|
|
|
def inspect_image(data: bytes, declared_type: str) -> str:
|
|
if len(data) > MAX_BYTES:
|
|
raise ApiError(
|
|
413,
|
|
"payload_too_large",
|
|
"Файл превышает 10 MiB",
|
|
)
|
|
|
|
if declared_type not in FORMAT_TO_MIME.values():
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Допустимы только image/png и image/jpeg",
|
|
)
|
|
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
detected = FORMAT_TO_MIME.get(image.format or "")
|
|
width, height = image.size
|
|
pixels = width * height
|
|
except Image.DecompressionBombError:
|
|
raise ApiError(
|
|
413,
|
|
"payload_too_large",
|
|
"Слишком много пикселей",
|
|
) from None
|
|
except (UnidentifiedImageError, OSError, SyntaxError, ValueError):
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Файл не является корректным PNG/JPEG",
|
|
) from None
|
|
|
|
if detected is None or detected != declared_type:
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Содержимое не соответствует Content-Type",
|
|
)
|
|
|
|
if width < 1 or height < 1 or pixels > MAX_PIXELS:
|
|
raise ApiError(
|
|
413,
|
|
"payload_too_large",
|
|
"Слишком много пикселей",
|
|
)
|
|
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
image.verify()
|
|
|
|
with Image.open(io.BytesIO(data)) as image:
|
|
image.load()
|
|
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError):
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Файл повреждён",
|
|
) from None
|
|
|
|
return detected
|