feat(chat): 聊天单向删除

This commit is contained in:
xingc
2025-05-15 18:24:05 +08:00
parent 99f15cff84
commit cc097a587f
8 changed files with 147 additions and 43 deletions

View File

@@ -17,7 +17,7 @@ from sqlalchemy.orm import selectinload
from core.base import schema as base_schema
from core.db.crud import CRUD
from core.db.engine import get_async_session
from core.db.models import Message, Chat, User, ReadStatus, chat_participant
from core.db.models import Message, Chat, User, ReadStatus, ChatParticipant
from core.routers.auth.schema import LoginUser
from core.routers.auth.services import get_current_user_form_http, get_current_user_form_ws
from core.base.exceptions import WebsocketTooManyRequests
@@ -46,11 +46,13 @@ async def get_all_chats(
page_size: int = Query(default=15, gt=0, le=200),
):
filter_conditions = (
exists().where(
(chat_participant.c.chat_id == Chat.id) &
(chat_participant.c.user_id == login_user.user_id)
) &
Chat.is_deleted.is_(False)
exists().where(
and_(
ChatParticipant.chat_id == Chat.id,
ChatParticipant.user_id == login_user.user_id,
ChatParticipant.is_deleted == False
)
)
)
query = (
select(Chat)
@@ -163,12 +165,12 @@ async def create_new_chat(
.where(
and_(
exists().where(
(chat_participant.c.chat_id == Chat.id) &
(chat_participant.c.user_id == login_user.user_id)
(ChatParticipant.chat_id == Chat.id) &
(ChatParticipant.user_id == login_user.user_id)
),
exists().where(
(chat_participant.c.chat_id == Chat.id) &
(chat_participant.c.user_id == recipient_user.user_id)
(ChatParticipant.chat_id == Chat.id) &
(ChatParticipant.user_id == recipient_user.user_id)
),
Chat.is_deleted == False
)
@@ -209,23 +211,34 @@ async def delete_single_chat(
db_session: AsyncSession = Depends(get_async_session),
):
subquery = (
select(chat_participant.c.chat_id)
.where(chat_participant.c.user_id == login_user.user_id)
select(ChatParticipant.chat_id)
.where(ChatParticipant.user_id == login_user.user_id)
).scalar_subquery()
query = (
update(Chat)
select(Chat)
.where(and_(
Chat.id.in_(subquery),
Chat.guid == chat_guid
))
.values(is_deleted=True)
)
result = await db_session.execute(query)
await db_session.commit()
chat = result.scalar_one_or_none()
if result.rowcount == 0:
if chat is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='聊天不存在')
else:
db_curd = CRUD(db_session, Chat)
await db_curd.update(
data={'is_deleted': True},
filters={'id': chat.id},
)
await db_curd.update(
model=ChatParticipant,
data={'is_deleted': True},
filters={'user_id': login_user.user_id, 'chat_id': chat.id},
)
return {'message': '聊天已删除'}