forked from mtusi2026/mtusi2026lab2
72 lines
2.6 KiB
Python
72 lines
2.6 KiB
Python
import base64
|
|
import json
|
|
from datetime import datetime
|
|
from uuid import UUID
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
|
from ..storage.postgres import storage
|
|
from .security import current_user
|
|
|
|
|
|
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
|
|
|
|
|
def _require_member(chat_id: UUID, user_id: UUID):
|
|
chat = storage.get_chat(chat_id)
|
|
if chat is None or user_id not in chat.member_ids:
|
|
raise HTTPException(status_code=404, detail="not_found")
|
|
return chat
|
|
|
|
|
|
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
|
data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()}
|
|
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
|
|
|
|
|
def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
|
try:
|
|
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
|
if data.get("chat_id") != str(chat_id):
|
|
raise ValueError("cursor_chat_mismatch")
|
|
return datetime.fromisoformat(data["created_at"]), UUID(data["id"])
|
|
except Exception:
|
|
raise HTTPException(status_code=400, detail="invalid_request")
|
|
|
|
|
|
@router.post(
|
|
path="/{chat_id}/messages",
|
|
summary="Отправить сообщение в чат",
|
|
response_model=Message,
|
|
status_code=201,
|
|
)
|
|
def create_message(
|
|
chat_id: UUID,
|
|
payload: CreateMessage,
|
|
user: User = Depends(current_user),
|
|
) -> Message:
|
|
_require_member(chat_id, user.id)
|
|
if not payload.text.strip():
|
|
raise HTTPException(status_code=400, detail="invalid_request")
|
|
return storage.add_message(chat_id, user.id, payload.text)
|
|
|
|
|
|
@router.get(
|
|
path="/{chat_id}/messages",
|
|
summary="Получить историю сообщений чата",
|
|
response_model=MessagePage,
|
|
)
|
|
def list_messages(
|
|
chat_id: UUID,
|
|
user: User = Depends(current_user),
|
|
limit: int = Query(50, ge=1, le=100),
|
|
cursor: str | None = None,
|
|
) -> MessagePage:
|
|
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию, без полного scan истории."""
|
|
_require_member(chat_id, user.id)
|
|
after = _decode_cursor(chat_id, cursor) if cursor else None
|
|
# Берём limit+1, чтобы понять, есть ли следующая страница
|
|
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
|
|
has_more = len(rows) > limit
|
|
items = rows[:limit]
|
|
next_cursor = _encode_cursor(chat_id, items[-1]) if has_more and items else None
|
|
return MessagePage(items=items, next_cursor=next_cursor) |