from datetime import timedelta from messenger.messaging.application.commands import CreateChat, PostMessage from messenger.messaging.application.ports import AttachmentStates, MessagingUnitOfWork from messenger.messaging.domain.errors import AttachmentUnavailable, ChatNotFound from messenger.messaging.domain.models import Chat, Message, Receipt from messenger.shared.application.ports import Clock, IdGenerator class CreateChatHandler: __slots__ = ("_clock", "_ids", "_uow") def __init__(self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator) -> None: self._uow = uow self._clock = clock self._ids = ids async def __call__(self, command: CreateChat) -> Chat: chat = Chat.create( chat_id=self._ids.new_id(), title=command.title, member_ids=command.member_ids, creator_id=command.creator_id, created_at=self._clock.now(), ) async with self._uow.transaction(): await self._uow.chats.add(chat) await self._uow.commit() return chat class PostMessageHandler: __slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow") def __init__( self, uow: MessagingUnitOfWork, attachments: AttachmentStates, clock: Clock, ids: IdGenerator, ttl: timedelta, ) -> None: self._uow = uow self._attachments = attachments self._clock = clock self._ids = ids self._ttl = ttl async def __call__(self, command: PostMessage) -> Message: async with self._uow.transaction(): chat = await self._uow.chats.get(command.chat_id) if chat is None: raise ChatNotFound("чат не найден") now = self._clock.now() message = chat.post( message_id=self._ids.new_id(), sender_id=command.sender_id, text=command.text, now=now, attachment_ids=command.attachment_ids, ) known = await self._uow.chats.receipt( chat.id, command.sender_id, command.key, now - self._ttl ) if known is not None: return known.replay(command.fingerprint) if message.attachment_ids and await self._attachments.unusable( chat.id, message.attachment_ids ): raise AttachmentUnavailable("вложение не обработано и не может быть отправлено") await self._uow.chats.append(Receipt(command.key, command.fingerprint, message)) await self._uow.commit() return message