import re from collections.abc import AsyncIterator from typing import Annotated from uuid import UUID from dishka.integrations.fastapi import FromDishka, inject from fastapi import APIRouter, Query, Request, status from fastapi.responses import StreamingResponse from starlette.requests import ClientDisconnect from messenger.attachments.application.bus import AttachmentsCommandBus from messenger.attachments.application.commands import UploadAttachment from messenger.attachments.application.queries import GetAttachment, OpenAttachment from messenger.attachments.domain.errors import UploadAborted from messenger.attachments.entrypoints.schemas import AttachmentOut, VariantName from messenger.shared.entrypoints.actor import Actor UPLOAD_PATH = re.compile(r"/api/v1/chats/[^/]+/attachments/?") CONTENT_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"} uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"]) attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"]) async def body_of(request: Request) -> AsyncIterator[bytes]: try: async for chunk in request.stream(): yield chunk except ClientDisconnect as error: raise UploadAborted("клиент оборвал загрузку до конца тела") from error @uploads_router.post("", status_code=status.HTTP_202_ACCEPTED) @inject async def upload_attachment( chat_id: UUID, actor: Actor, request: Request, bus: FromDishka[AttachmentsCommandBus], filename: Annotated[str | None, Query()] = None, ) -> AttachmentOut: attachment = await bus.execute( UploadAttachment( owner_id=actor, chat_id=chat_id, filename=filename, content_type=request.headers.get("content-type"), body=body_of(request), ) ) return AttachmentOut.of(attachment) @attachments_router.get("/{attachment_id}") @inject async def read_attachment( attachment_id: UUID, actor: Actor, query: FromDishka[GetAttachment], ) -> AttachmentOut: return AttachmentOut.of(await query(attachment_id, actor)) @attachments_router.get("/{attachment_id}/content") @inject async def download_attachment( attachment_id: UUID, actor: Actor, query: FromDishka[OpenAttachment], variant: Annotated[VariantName, Query()] = "original", ) -> StreamingResponse: content_type, content = await query(attachment_id, actor, variant) return StreamingResponse( content.chunks, media_type=content_type, headers={**CONTENT_HEADERS, "Content-Length": str(content.size)}, )