Files
mtusi2026lab4/app/api/routers/attachments.py
T

67 lines
2.1 KiB
Python

from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request
from fastapi.responses import StreamingResponse
from ...domain.models import User
from ...services.attachments import AttachmentService
from ..deps import attachment_service, current_user
from ..schemas import AttachmentOut
router = APIRouter(tags=['attachments'])
@router.post(
'/api/v1/chats/{chat_id}/attachments',
status_code=201,
response_model=AttachmentOut,
)
async def upload(
chat_id: UUID,
request: Request,
filename: str = Query(..., min_length=1, max_length=255),
content_type: Annotated[str | None, Header(alias='Content-Type')] = None,
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> AttachmentOut:
attachment = await attachments.upload(
actor,
chat_id,
filename,
content_type or '',
request.stream(),
)
return AttachmentOut.from_domain(attachment)
@router.get('/api/v1/attachments/{attachment_id}', response_model=AttachmentOut)
async def metadata(
attachment_id: UUID,
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> AttachmentOut:
return AttachmentOut.from_domain(await attachments.get(actor, attachment_id))
@router.get('/api/v1/attachments/{attachment_id}/content')
async def content(
attachment_id: UUID,
variant: str = Query('original'),
actor: User = Depends(current_user),
attachments: AttachmentService = Depends(attachment_service),
) -> StreamingResponse:
if variant != 'original':
from ...domain.errors import NotFound
raise NotFound('вариант вложения не найден')
attachment, stream = await attachments.content(actor, attachment_id)
return StreamingResponse(
stream.chunks(),
media_type=attachment.content_type,
headers={
'Content-Length': str(attachment.size_bytes),
'Content-Disposition': f'inline; filename="attachment-{attachment.id}"',
},
)