47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
|
from core.errors.errors import not_a_member_of_chat
|
||
|
from core.models.message.db import MPProfile, MPMessage
|
||
|
from core.models.message.requests import SendMessageRequest
|
||
|
from core.models.message.responses import MessageResponse, ProfileResponse, ChatResponse
|
||
|
from core.storage import message_storage, auth_storage, chat_storage
|
||
|
|
||
|
|
||
|
class Service:
|
||
|
|
||
|
async def build_message_response(self, msg: MPMessage) -> MessageResponse:
|
||
|
"""
|
||
|
Build a message response
|
||
|
"""
|
||
|
return MessageResponse(
|
||
|
id=msg.id,
|
||
|
sender=ProfileResponse(id=msg.sender.id, external_id=msg.sender.external_id,
|
||
|
created_at=msg.sender.created_at, modified_at=msg.sender.modified_at),
|
||
|
content=msg.content,
|
||
|
chat=ChatResponse(id=msg.chat.id,
|
||
|
name=msg.chat.name,
|
||
|
admin=ProfileResponse(id=msg.chat.admin.id, external_id=msg.chat.admin.external_id,
|
||
|
created_at=msg.chat.admin.created_at,
|
||
|
modified_at=msg.chat.admin.modified_at),
|
||
|
users=None,
|
||
|
created_at=msg.chat.created_at,
|
||
|
modified_at=msg.chat.modified_at),
|
||
|
created_at=msg.created_at,
|
||
|
modified_at=msg.modified_at
|
||
|
)
|
||
|
|
||
|
async def send_message(self, user: MPProfile, message: SendMessageRequest) -> MessageResponse:
|
||
|
"""
|
||
|
Send message to chat
|
||
|
"""
|
||
|
|
||
|
# Check chat exists
|
||
|
chat = await chat_storage.get_chat(message.chat_id)
|
||
|
|
||
|
# Check user is in chat
|
||
|
if user.id not in [x.id for x in chat.users]:
|
||
|
not_a_member_of_chat()
|
||
|
|
||
|
# Add message to Database
|
||
|
msg = await message_storage.insert_message(user.id, message.chat_id, message.content)
|
||
|
|
||
|
return await self.build_message_response(msg)
|