fix(chat): 修复多个聊天错误 消息格式错误导致断连、新消息会通知到发件人、加强消息发送的成员验证

This commit is contained in:
xingc
2025-05-14 21:19:46 +08:00
parent 854f5bcbea
commit 99f15cff84
4 changed files with 33 additions and 12 deletions

View File

@@ -239,6 +239,7 @@ async def get_chat_websocket(
await socket_manager.connect_socket(websocket=websocket)
logger.info(f'Websocket connection is established: {login_user.user_id}')
user_id = str(login_user.user_id)
websocket.user_id = login_user.user_id
await socket_manager.add_user_socket_connection(user_id, websocket)
ratelimit = WebSocketRateLimiter(times=50, seconds=10, callback=websocket_callback)
@@ -258,13 +259,13 @@ async def get_chat_websocket(
try:
message = schema.WSMessage(**incoming_message)
except ValueError:
await socket_manager.send_error(websocket, 'The message type or format you sent is invalid')
await socket_manager.send_error('The message type or format you sent is invalid', websocket)
continue
handler = socket_manager.handlers.get(message.type)
if not handler:
logger.error(f'No handler [{message.type}] exists')
await socket_manager.send_error(websocket, f'Type: {message.type} was not found')
await socket_manager.send_error(f'Type: {message.type} was not found', websocket)
continue
await handler(
@@ -277,14 +278,14 @@ async def get_chat_websocket(
except (JSONDecodeError, AttributeError) as exc:
logger.exception(f'Websocket error, detail: {exc}')
await websocket.send_json({'status': 'error', 'message': 'Wrong message format'})
await socket_manager.send_error('Wrong message format', websocket)
except ValueError as exc:
logger.exception(f'Websocket error, detail: {exc}')
await websocket.send_json({'status': 'error', 'message': 'Could not validate incoming message'})
await socket_manager.send_error('Could not validate incoming message', websocket)
except WebsocketTooManyRequests:
logger.exception(f'User: {login_user} sent too many ws requests')
await websocket.send_json({'status': 'error', 'message': 'You have sent too many requests'})
await socket_manager.send_error('You have sent too many requests', websocket)
except WebSocketDisconnect:
logging.info(f'Websocket is disconnected: {login_user.user_id}')