2025-11-13 10:36:09 +01:00

64 lines
2.1 KiB
Python

from bottle import Bottle, request, response
from json import dumps, loads
from simple_chat_api.db_handler.db_handler import User, Message
from simple_chat_api.endpoints.auth import user_guard
from simple_chat_api.utils import read_keys_from_request
app = Bottle()
def serialize_message(messages: list[Message]) -> str:
"""
Serialize a list of Message objects into a JSON string.
:param messages: list of Message objects
:return: JSON string representing the messages
"""
return dumps({getattr(msg, "id"):
{key: getattr(msg, key)
for key in msg.__dict__.keys() if key[0] != '_' and key != 'id'}
for msg in messages})
@app.route('/<room>', method=['POST'])
@user_guard()
def recive_msg(user: User, room: str):
"""
Receive a new message for a specific room.
Rejected by user_guard if the requester is not authenticated.
Expects JSON body with "content" field.
:param user: authenticated user object
:param room: room to add the message to
:return: JSON string representing the newly added message
"""
msg = read_keys_from_request(keys=["content"])
if not msg:
response.status = 400
return {"error": "Missing 'content' in request body"}
new_msg = request.db_connector.add_msg_to_room(room, msg["content"], user.name)
return serialize_message([new_msg])
@app.route('/<room>', method=['GET'])
@user_guard()
def return_msgs(user: User, room: str):
"""
Get messages from a specific room.
Rejected by user_guard if the requester is not authenticated.
Accepts optional 'since' query parameter to get messages after a specific timestamp.
:param user: authenticated user object
:param room: room to get messages from
:return: JSON string representing the messages from the room
"""
since = request.query.get('since', None)
if since:
try:
since = int(since)
except ValueError:
response.status = 400
return {"error": "Invalid 'since' parameter"}
messages = request.db_connector.get_messages_from_room(room, since)
return serialize_message(messages)