import asyncio import warnings from io import BytesIO from PIL import Image from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage from messenger.attachments.domain.values import ImageInfo, ImageKind from messenger.attachments.infrastructure.png import SIGNATURE, read_png_header, verify_png_pixels KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG} BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning) JPEG_SCALE = 8 class PillowImageInspector: __slots__ = ("_max_pixels", "_slots") def __init__(self, max_pixels: int, concurrency: int) -> None: self._max_pixels = max_pixels self._slots = asyncio.Semaphore(concurrency) warnings.simplefilter("error", Image.DecompressionBombWarning) async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: async with self._slots: return await asyncio.to_thread(self._inspect, data, declared) def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: try: header = read_png_header(data) if data.startswith(SIGNATURE) else None image = Image.open(BytesIO(data), formats=tuple(KINDS)) except BOMBS as error: raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error except Exception as error: raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error with image: kind = KINDS[str(image.format)] width, height = image.size if header is None else header[:2] if kind is not declared: raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type") if width * height > self._max_pixels: raise PayloadTooLarge("изображение больше допустимого числа пикселей") try: if header is None: image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1)) image.load() else: image.verify() verify_png_pixels(data, header) except Exception as error: raise UnsupportedImage("изображение повреждено или обрезано") from error return ImageInfo(kind, width, height)