from uuid import UUID from messenger.attachments.application.errors import ObjectMissingError from messenger.attachments.application.ports import ( AttachmentDirectory, ChatMembership, ObjectContent, ObjectStorage, ) from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady from messenger.attachments.domain.models import Attachment from messenger.shared.application.ports import Logger ORIGINAL = "original" class GetAttachment: __slots__ = ("_attachments", "_membership") def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None: self._attachments = attachments self._membership = membership async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment: attachment = await self._attachments.visible(attachment_id) if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id): raise AttachmentNotFound("вложение не найдено") return attachment class OpenAttachment: __slots__ = ("_get", "_logger", "_storage") def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None: self._get = get self._storage = storage self._logger = logger async def __call__( self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL ) -> tuple[str, ObjectContent]: attachment = await self._get(attachment_id, user_id) if not attachment.ready: raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась") if variant == ORIGINAL: key, content_type = attachment.original_key, attachment.content_type else: found = attachment.variant(variant) if found is None: raise AttachmentNotFound("у вложения нет такого варианта") key, content_type = found.object_key, found.content_type if attachment.quarantine is not None: self._logger.warning("attachment.quarantined", attachment_id=str(attachment.id)) raise AttachmentNotFound("вложение не найдено") try: content = await self._storage.open(str(key)) except ObjectMissingError as error: self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id)) raise AttachmentNotFound("вложение не найдено") from error return content_type, content