Files
mtusi2026lab4/app/routes/attachments.py
T

86 lines
2.6 KiB
Python

from uuid import UUID
from fastapi import APIRouter, Depends, Query, Request, Response, status
from app.dependencies import get_current_user
from app.errors import InvalidRequestError
from app.schemas import AttachmentResponse, UserResponse
from app.storage import storage
router = APIRouter(tags=["attachments"])
def validate_uuid(value: str, field_name: str = "id") -> str:
try:
UUID(value)
return value
except ValueError as exc:
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
@router.post(
"/api/v1/chats/{chat_id}/attachments",
response_model=AttachmentResponse,
status_code=status.HTTP_201_CREATED,
)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
current_user: UserResponse = Depends(get_current_user),
) -> AttachmentResponse:
"""Загрузка бинарного вложения в чат."""
valid_chat_id = validate_uuid(chat_id, "chat_id")
content_type = request.headers.get("content-type") or ""
data = await request.body()
return await storage.upload_attachment(
caller_id=current_user.id,
chat_id=valid_chat_id,
filename=filename,
content_type=content_type,
data=data,
)
@router.get(
"/api/v1/attachments/{attachment_id}",
response_model=AttachmentResponse,
status_code=status.HTTP_200_OK,
)
async def get_attachment_metadata(
attachment_id: str,
current_user: UserResponse = Depends(get_current_user),
) -> AttachmentResponse:
"""Получение метаданных вложения."""
valid_att_id = validate_uuid(attachment_id, "attachment_id")
return await storage.get_attachment(
caller_id=current_user.id,
attachment_id=valid_att_id,
)
@router.get(
"/api/v1/attachments/{attachment_id}/content",
status_code=status.HTTP_200_OK,
)
async def download_attachment_content(
attachment_id: str,
variant: str | None = Query(default=None),
current_user: UserResponse = Depends(get_current_user),
) -> Response:
"""Скачивание бинарного содержимого вложения."""
valid_att_id = validate_uuid(attachment_id, "attachment_id")
data, content_type = await storage.get_attachment_content(
caller_id=current_user.id,
attachment_id=valid_att_id,
variant=variant,
)
return Response(
content=data,
media_type=content_type,
headers={
"Content-Length": str(len(data)),
},
)