import base64 from fastapi import HTTPException, APIRouter, Query, status from typing import Optional from uuid import UUID from src.pydantic_valid.message import Message, CreateMessage from src.pydantic_valid.page_response import PageResponse from src.api.dependencies import DbSession, CurrentUser from src.api.repositories.main_repo import Repository from src.utils import generate_id, get_now_iso import datetime router = APIRouter() def _encode_msg_cursor(chat_id: str, created_at: str, msg_id: str) -> str: raw = f"m|{chat_id}|{created_at}|{msg_id}" return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=") def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]: try: padded = cursor + "=" * (-len(cursor) % 4) raw = base64.urlsafe_b64decode(padded).decode("utf-8") parts = raw.split("|", 3) if len(parts) != 4 or parts[0] != "m": raise ValueError("bad cursor structure") chat_id, created_at, msg_id = parts[1], parts[2], parts[3] except Exception as e: raise HTTPException(status_code=400, detail="invalid cursor") from e if scope_chat_id != chat_id: raise HTTPException(status_code=400, detail="cursor from another chat") return created_at, msg_id @router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) async def send_message(chat_id: UUID, msg_in: CreateMessage, session: DbSession, current_user: CurrentUser): repo = Repository(session) if not await repo.chats.is_user_member(chat_id, current_user.id): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="chat not found") message = await repo.messages.create(chat_id=chat_id, sender_id=current_user.id, text=msg_in.text) return Message( id=str(message.id), chat_id=str(message.chat_id), sender_id=str(message.sender_id), text=message.text, created_at=message.created_at.strftime("%Y-%m-%dT%H:%M:%SZ") ) @router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200) async def list_messages(session: DbSession, current_user: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)): repo = Repository(session) chat = await repo.chats.get_by_id_with_members(chat_id) if not chat: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="chat not found") member_ids = {str(m.user_id) for m in chat.members} if str(current_user.id) not in member_ids: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="chat not found") cursor_created_at = None cursor_msg_id = None if cursor: created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor) cursor_created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00")) cursor_msg_id = UUID(msg_id_str) messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id) next_cursor = None if has_more and messages: last = messages[-1] next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"), msg_id=str(last.id)) return PageResponse( items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%SZ")) for msg in messages], next_cursor=next_cursor, )