forked from mtusi2026/mtusi2026lab2
lab2 complete
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
import uuid
|
||||
import json
|
||||
import base64
|
||||
|
||||
|
||||
from datetime import timezone, datetime
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, status, Request
|
||||
from ..utils import authenticate_user, validate_uuid, get_utc_now, format_iso
|
||||
from ..exceptions import ApiException
|
||||
from ..models import SendMessageRequest
|
||||
from ..db import get_pool
|
||||
|
||||
router = APIRouter(tags=["messages"])
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED)
|
||||
async def send_message(chat_id: str, body: SendMessageRequest, request: Request):
|
||||
caller_id = await authenticate_user(request)
|
||||
validate_uuid(chat_id)
|
||||
|
||||
pool = get_pool()
|
||||
is_member = await pool.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
uuid.UUID(chat_id), uuid.UUID(caller_id)
|
||||
)
|
||||
if not is_member:
|
||||
raise ApiException(404, "not_found", "Chat not found")
|
||||
|
||||
if not body.text.strip() or len(body.text) > 4000:
|
||||
raise ApiException(400, "invalid_request", "Invalid text")
|
||||
|
||||
mid = uuid.uuid4()
|
||||
now = get_utc_now()
|
||||
|
||||
await pool.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)",
|
||||
mid, uuid.UUID(chat_id), uuid.UUID(caller_id), body.text, now
|
||||
)
|
||||
|
||||
return {
|
||||
"id": str(mid),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": caller_id,
|
||||
"text": body.text,
|
||||
"created_at": format_iso(now)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}/messages")
|
||||
async def get_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None
|
||||
):
|
||||
caller_id = await authenticate_user(request)
|
||||
validate_uuid(chat_id)
|
||||
|
||||
pool = get_pool()
|
||||
chat_uuid = uuid.UUID(chat_id)
|
||||
|
||||
is_member = await pool.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
chat_uuid,
|
||||
uuid.UUID(caller_id)
|
||||
)
|
||||
|
||||
if not is_member:
|
||||
raise ApiException(404, "not_found", "Chat not found")
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise ApiException(400, "invalid_request", "Invalid limit")
|
||||
|
||||
cursor_time = None
|
||||
cursor_id = None
|
||||
|
||||
if cursor is not None:
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(
|
||||
cursor + "=" * (-len(cursor) % 4)
|
||||
)
|
||||
data = json.loads(decoded)
|
||||
|
||||
cursor_time = datetime.fromisoformat(
|
||||
data["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
cursor_id = uuid.UUID(data["id"])
|
||||
|
||||
if cursor_time.tzinfo is None:
|
||||
raise ValueError()
|
||||
|
||||
cursor_time = cursor_time.astimezone(timezone.utc)
|
||||
|
||||
except (ValueError, KeyError, TypeError, UnicodeDecodeError):
|
||||
raise ApiException(
|
||||
400, "invalid_request", "Invalid cursor"
|
||||
)
|
||||
|
||||
rows = await pool.fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (created_at, id) > ($2::timestamptz, $3::uuid)
|
||||
)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
""",
|
||||
chat_uuid,
|
||||
cursor_time,
|
||||
cursor_id,
|
||||
limit + 1
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
|
||||
items = [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_iso(row["created_at"])
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
|
||||
cursor_data = {
|
||||
"created_at": format_iso(last["created_at"]),
|
||||
"id": str(last["id"])
|
||||
}
|
||||
|
||||
next_cursor = base64.urlsafe_b64encode(
|
||||
json.dumps(cursor_data).encode("utf-8")
|
||||
).decode("ascii").rstrip("=")
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"next_cursor": next_cursor
|
||||
}
|
||||
Reference in New Issue
Block a user