import unicodedata from dataclasses import dataclass from enum import StrEnum from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage FILENAME_MAX = 255 SEPARATORS = frozenset("/\\") @dataclass(frozen=True, slots=True) class Filename: value: str def __post_init__(self) -> None: if not self.value.strip(): raise InvalidFilename("параметр filename обязателен и не может быть пустым") if len(self.value) > FILENAME_MAX: raise InvalidFilename(f"параметр filename длиннее {FILENAME_MAX} символов Unicode") if any(c in SEPARATORS or unicodedata.category(c) == "Cc" for c in self.value): raise InvalidFilename( "параметр filename содержит разделитель пути или управляющий символ" ) def __str__(self) -> str: return self.value class ImageKind(StrEnum): PNG = "image/png" JPEG = "image/jpeg" @classmethod def declared(cls, content_type: str | None) -> ImageKind: media = (content_type or "").partition(";")[0].strip().lower() try: return cls(media) except ValueError as error: raise UnsupportedImage("Content-Type должен быть image/png или image/jpeg") from error @dataclass(frozen=True, slots=True) class ImageInfo: kind: ImageKind width: int height: int