diff --git a/core/routers/chat/routes.py b/core/routers/chat/routes.py index eba7e0d..3b6c460 100644 --- a/core/routers/chat/routes.py +++ b/core/routers/chat/routes.py @@ -24,7 +24,7 @@ from core.base.exceptions import WebsocketTooManyRequests from . import schema from .handlers import socket_manager -from .services import websocket_callback, get_user_active_direct_chats, get_unread_messages_per_chat +from .services import websocket_callback, get_user_active_direct_chats, get_unread_messages_per_chat, get_chat logger = logging.getLogger(__name__) @@ -95,15 +95,10 @@ async def get_single_chat_messages( page_size: int = Query(default=15, gt=0, le=200), last_read_message_id: int = Query(default=0, ge=0), ): - db_crud = CRUD(db_session, Chat) - chat: Chat | None = await db_crud.get(filters={'guid': chat_guid, 'is_deleted': False}) + chat: Chat | None = await get_chat(chat_guid, login_user, db_session, is_query_messages=True) if not chat: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='您访问的聊天不存在') - chat_user_ids = [user.user_id for user in await chat.awaitable_attrs.users] - if login_user.user_id not in chat_user_ids: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='您无权访问此聊天') - # 组装查询条件 conditions = and_( Message.chat_id == chat.id, diff --git a/core/routers/chat/services.py b/core/routers/chat/services.py index e31fa10..472078b 100644 --- a/core/routers/chat/services.py +++ b/core/routers/chat/services.py @@ -94,18 +94,31 @@ async def get_unread_messages_per_chat( return results -async def get_chat(chat_guid, login_user: User, db_session: AsyncSession) -> Chat | None: +async def get_chat(chat_guid, login_user: User, db_session: AsyncSession, + is_query_messages: bool = False) -> Chat | None: subquery = ( select(ChatParticipant.chat_id) - .where(ChatParticipant.user_id == login_user.user_id) + .where( + and_( + ChatParticipant.user_id == login_user.user_id, + ChatParticipant.is_deleted == False + ) + ) ).scalar_subquery() + conditions = [ + Chat.id.in_(subquery), + Chat.guid == chat_guid + ] + if is_query_messages is False: + conditions.append( + Chat.is_deleted == False + ) + query = ( select(Chat) .where(and_( - Chat.id.in_(subquery), - Chat.guid == chat_guid, - Chat.is_deleted == False + *conditions )) ) result = await db_session.execute(query)