from uuid import UUID from fastapi import APIRouter, Depends, Query, Request from fastapi.responses import Response from app.crud.attachments import create_attachment, metadata_for_member, open_content from app.deps import get_current_user from app.errors import AppError from app.present import PublicUser from app.runtime import require_settings, require_store from app.schemas.attachment import AttachmentOut router = APIRouter() async def read_limited_body(request: Request) -> bytes: limit = require_settings().max_upload_bytes raw_length = request.headers.get("content-length") if raw_length is not None: try: announced = int(raw_length) except ValueError: raise AppError(400, "invalid_request", "Некорректный запрос") from None if announced > limit: raise AppError(413, "payload_too_large", "Файл слишком большой") chunks: list[bytes] = [] total = 0 async for chunk in request.stream(): total += len(chunk) if total > limit: raise AppError(413, "payload_too_large", "Файл слишком большой") if chunk: chunks.append(chunk) return b"".join(chunks) @router.post("/chats/{chat_id}/attachments", status_code=202, response_model=AttachmentOut) async def upload_attachment( chat_id: UUID, request: Request, filename: str = Query(min_length=1, max_length=255), user: PublicUser = Depends(get_current_user), ) -> dict: payload = await read_limited_body(request) created = await create_attachment( chat_id, user.id, filename, request.headers.get("content-type"), payload, ) return created.to_dict() @router.get("/attachments/{attachment_id}", response_model=AttachmentOut) async def get_attachment( attachment_id: UUID, user: PublicUser = Depends(get_current_user), ) -> dict: return (await metadata_for_member(attachment_id, user.id)).to_dict() @router.get("/attachments/{attachment_id}/content") async def download_attachment( attachment_id: UUID, user: PublicUser = Depends(get_current_user), variant: str = Query(default="original"), ) -> Response: key, media_type = await open_content(attachment_id, user.id, variant) payload = await require_store().get(key) return Response(content=payload, media_type=media_type)