import uuid from datetime import datetime from fastapi import APIRouter, HTTPException, Depends, Header from pydantic import BaseModel, Field, ConfigDict, field_serializer, model_validator from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.redis_client import redis_client import json from app.models.message import Message from app.models.chat import Chat, ChatMember from app.models.user import User from app.models.attachment import Attachment from app.security import get_current_user from app.dependencies import get_session router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"]) class CreateMessage(BaseModel): model_config = ConfigDict(extra="forbid") text: str = Field(min_length=0, max_length=4000) attachment_ids: list[uuid.UUID] = [] @model_validator(mode="after") def check_text_or_attachment(self): if not self.text.strip() and not self.attachment_ids: raise ValueError("Сообщение должно содержать текст или вложение") return self class MessageResponse(BaseModel): id: uuid.UUID chat_id: uuid.UUID sender_id: uuid.UUID text: str created_at: datetime model_config = ConfigDict(from_attributes=True) attachment_ids: list[uuid.UUID] = [] @field_serializer('created_at') def serialize_dt(self, dt: datetime): return dt.isoformat().replace("+00:00", "Z") async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession): chat = await session.get(Chat, chat_id) if not chat: raise HTTPException(status_code=404, detail="чат не найден") result = await session.execute( select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id) ) if not result.scalar_one_or_none(): raise HTTPException(status_code=404, detail="чат не найден") return chat @router.post("", status_code=201, response_model=MessageResponse) async def create_message( chat_id: str, payload: CreateMessage, idempotency_key: str = Header( ..., alias="Idempotency-Key", min_length=1, max_length=128, pattern=r"^[A-Za-z0-9._:-]+$", ), user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session) ): await check_chat_access(chat_id, user.id, session) if payload.attachment_ids: result = await session.execute( select(Attachment.id).where( Attachment.id.in_(payload.attachment_ids), Attachment.chat_id == chat_id, ) ) found_ids = {str(row[0]) for row in result.all()} requested_ids = {str(a) for a in payload.attachment_ids} if found_ids != requested_ids: raise HTTPException( status_code=400, detail="attachment_ids содержат файлы из другого чата или несуществующие" ) redis_key = f"idem:{user.id}:{chat_id}:{idempotency_key}" body = payload.model_dump(mode="json") raw = await redis_client.get(redis_key) if raw: stored = json.loads(raw) if stored["state"] == "done": if stored["request_body"] == body: return stored["response"] raise HTTPException(status_code=409, detail="Idempotency-Key переиспользован с другим телом запроса") raise HTTPException(status_code=409, detail="Запрос с этим Idempotency-Key ещё обрабатывается") acquired = await redis_client.set( redis_key, json.dumps({"state": "processing", "request_body": body}), nx=True, ex=86400, ) if not acquired: raise HTTPException(409, "Одновременный запрос с тем же самым Idempotency-Key") message = Message( chat_id=chat_id, sender_id=user.id, text=payload.text, attachment_ids=[str(a) for a in payload.attachment_ids] ) session.add(message) await session.commit() await session.refresh(message) response_data = { "id": str(message.id), "chat_id": str(message.chat_id), "sender_id": str(message.sender_id), "text": message.text, "created_at": message.created_at.isoformat().replace("+00:00", "Z"), "attachment_ids": message.attachment_ids, } await redis_client.set( redis_key, json.dumps({"state": "done", "request_body": body, "response": response_data}), ex=86400, ) return response_data @router.get("") async def list_messages( chat_id: str, limit: int = 50, cursor: str | None = None, user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session) ): if limit < 1 or limit > 100: raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100") await check_chat_access(chat_id, user.id, session) offset = int(cursor) if cursor else 0 result = await session.execute( select(Message) .where(Message.chat_id == chat_id) .order_by(Message.created_at, Message.id) .limit(limit + 1) .offset(offset) ) msgs = result.scalars().all() has_next = len(msgs) > limit if has_next: msgs = msgs[:limit] my_messages = [ { "id": m.id, "chat_id": m.chat_id, "sender_id": m.sender_id, "text": m.text, "created_at": m.created_at.isoformat().replace("+00:00", "Z"), "attachment_ids": m.attachment_ids, } for m in msgs ] next_cursor = str(offset + limit) if has_next else None return {"items": my_messages, "next_cursor": next_cursor}