forked from mtusi2026/mtusi2026lab5
105 lines
3.6 KiB
Python
105 lines
3.6 KiB
Python
from uuid import UUID
|
|
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.domain.pagination import (
|
|
KIND_CHATS,
|
|
build_next_cursor,
|
|
decode_cursor,
|
|
split_page,
|
|
)
|
|
from app.errors.exceptions import invalid_request, not_found
|
|
from app.models.chat import Chat as ChatModel
|
|
from app.schemas.chat import Chat, ChatPage, CreateChat
|
|
from app.schemas.user import User
|
|
from app.storage import chats as chats_storage
|
|
from app.storage import users as users_storage
|
|
from app.storage.types import Position
|
|
|
|
UNKNOWN_MEMBER_MESSAGE = "member_ids содержит неизвестного пользователя"
|
|
|
|
|
|
def to_chat_schema(chat: ChatModel) -> Chat:
|
|
"""Преобразует ORM-модель чата с загруженными участниками в схему."""
|
|
chat_schema = Chat(
|
|
id=chat.id,
|
|
title=chat.title,
|
|
member_ids=[member.user_id for member in chat.members],
|
|
created_at=chat.created_at,
|
|
)
|
|
return chat_schema
|
|
|
|
|
|
def validate_new_chat(creator: User, new_chat: CreateChat) -> None:
|
|
"""Проверяет состав участников без обращения к базе."""
|
|
member_ids = new_chat.member_ids
|
|
|
|
if creator.id not in member_ids:
|
|
raise invalid_request("Создатель чата должен входить в member_ids")
|
|
|
|
if len(set(member_ids)) != len(member_ids):
|
|
raise invalid_request("member_ids содержит дубликаты")
|
|
|
|
|
|
async def create_chat(
|
|
session: AsyncSession, creator: User, new_chat: CreateChat
|
|
) -> Chat:
|
|
"""Создаёт чат с участниками атомарно; неверный состав даёт 400."""
|
|
validate_new_chat(creator, new_chat)
|
|
|
|
existing_ids = await users_storage.get_existing_user_ids(
|
|
session, new_chat.member_ids
|
|
)
|
|
if existing_ids != set(new_chat.member_ids):
|
|
raise invalid_request(UNKNOWN_MEMBER_MESSAGE)
|
|
|
|
try:
|
|
chat = await chats_storage.create_chat(
|
|
session, title=new_chat.title, member_ids=new_chat.member_ids
|
|
)
|
|
await session.commit()
|
|
except IntegrityError:
|
|
await session.rollback()
|
|
raise invalid_request(UNKNOWN_MEMBER_MESSAGE) from None
|
|
|
|
created_chat = to_chat_schema(chat)
|
|
return created_chat
|
|
|
|
|
|
async def get_chat(session: AsyncSession, user: User, chat_id: UUID) -> Chat:
|
|
"""Возвращает чат участнику; чужой и несуществующий чат дают 404."""
|
|
chat = await chats_storage.get_chat_for_member(session, chat_id, user.id)
|
|
if chat is None:
|
|
raise not_found()
|
|
|
|
found_chat = to_chat_schema(chat)
|
|
return found_chat
|
|
|
|
|
|
async def ensure_chat_member(session: AsyncSession, user: User, chat_id: UUID) -> None:
|
|
"""Бросает 404, если пользователь не состоит в чате или чата нет."""
|
|
if not await chats_storage.is_chat_member(session, chat_id, user.id):
|
|
raise not_found()
|
|
|
|
|
|
async def list_chats(
|
|
session: AsyncSession,
|
|
user: User,
|
|
cursor: str | None,
|
|
limit: int,
|
|
) -> ChatPage:
|
|
"""Возвращает страницу чатов пользователя по (created_at, id)."""
|
|
after: Position | None = None
|
|
if cursor is not None:
|
|
after = decode_cursor(cursor, KIND_CHATS, user.id)
|
|
|
|
rows = await chats_storage.list_chats_for_user(session, user.id, after, limit + 1)
|
|
page_rows, has_next = split_page(rows, limit)
|
|
items = [to_chat_schema(chat) for chat in page_rows]
|
|
page = ChatPage(
|
|
items=items,
|
|
next_cursor=build_next_cursor(KIND_CHATS, user.id, items, has_next),
|
|
)
|
|
return page
|