forked from mtusi2026/mtusi2026lab4
95 lines
2.5 KiB
Python
95 lines
2.5 KiB
Python
import uuid
|
|
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.models import Chat
|
|
from app.repositories.chat_repository import ChatRepository
|
|
from app.repositories.user_repository import UserRepository
|
|
|
|
|
|
class ChatNotFoundError(Exception):
|
|
pass
|
|
|
|
|
|
class ChatAccessError(Exception):
|
|
pass
|
|
|
|
|
|
class InvalidChatDataError(Exception):
|
|
pass
|
|
|
|
|
|
class ChatService:
|
|
def __init__(self, db: Session):
|
|
self.db = db
|
|
self.chats = ChatRepository(db)
|
|
self.users = UserRepository(db)
|
|
|
|
def create_chat(
|
|
self,
|
|
title: str,
|
|
member_ids: list[str],
|
|
creator_id: uuid.UUID,
|
|
) -> Chat:
|
|
title = title.strip()
|
|
|
|
if not title or len(title) > 100:
|
|
raise InvalidChatDataError("Invalid chat title")
|
|
|
|
if not member_ids or len(member_ids) > 100:
|
|
raise InvalidChatDataError("Invalid members")
|
|
|
|
try:
|
|
parsed_ids = [uuid.UUID(str(value)) for value in member_ids]
|
|
except (ValueError, TypeError, AttributeError):
|
|
raise InvalidChatDataError("Invalid member UUID") from None
|
|
|
|
if len(parsed_ids) != len(set(parsed_ids)):
|
|
raise InvalidChatDataError("Duplicate members")
|
|
|
|
if creator_id not in parsed_ids:
|
|
raise InvalidChatDataError("Creator must be a member")
|
|
|
|
for user_id in parsed_ids:
|
|
if self.users.get_by_id(user_id) is None:
|
|
raise InvalidChatDataError("Unknown member")
|
|
|
|
try:
|
|
chat = self.chats.create(
|
|
title=title,
|
|
member_ids=parsed_ids,
|
|
)
|
|
self.db.commit()
|
|
self.db.refresh(chat)
|
|
return chat
|
|
|
|
except IntegrityError as exc:
|
|
self.db.rollback()
|
|
raise InvalidChatDataError("Unable to create chat") from exc
|
|
|
|
except Exception:
|
|
self.db.rollback()
|
|
raise
|
|
|
|
def get_chat(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat:
|
|
chat = self.chats.get_by_id(chat_id)
|
|
|
|
if chat is None:
|
|
raise ChatNotFoundError()
|
|
|
|
if not self.chats.is_member(chat_id, user_id):
|
|
raise ChatNotFoundError()
|
|
|
|
return chat
|
|
|
|
def list_chats(self, user_id: uuid.UUID) -> list[Chat]:
|
|
return self.chats.get_by_user(user_id)
|
|
|
|
def check_membership(
|
|
self,
|
|
chat_id: uuid.UUID,
|
|
user_id: uuid.UUID,
|
|
) -> bool:
|
|
return self.chats.is_member(chat_id, user_id)
|