from __future__ import annotations import asyncio import hashlib from contextlib import asynccontextmanager from uuid import UUID from fastapi import APIRouter, Request from fastapi.responses import Response from starlette.concurrency import run_in_threadpool from starlette.requests import ClientDisconnect from app.db import pool from app.jobs import accept_upload from app.dependencies import accessible_chat, current_user from app.errors import ApiError, invalid, not_found from app.images import MAX_BYTES, inspect_image, validate_filename from app.responses import json_response from app.storage import get_object from app.validation import parse_uuid router = APIRouter() binary_slot = asyncio.Semaphore(1) PUBLIC_FIELDS = ( "id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "status", "created_at", "updated_at", ) @asynccontextmanager async def binary_operation(): try: await asyncio.wait_for(binary_slot.acquire(), timeout=3) except TimeoutError: raise ApiError( 503, "unavailable", "Обработка файлов временно занята", ) from None try: yield finally: binary_slot.release() def public_attachment(row: dict) -> dict: result = {field: row[field] for field in PUBLIC_FIELDS} result["variants"] = row.get("variants", []) result["error_code"] = row.get("error_code") return result async def read_image_body(request: Request) -> bytes: lengths = request.headers.getlist("content-length") if len(lengths) > 1: raise invalid("Некорректный Content-Length") expected = None if lengths: value = lengths[0] if not value.isascii() or not value.isdecimal(): raise invalid("Некорректный Content-Length") if len(value) > 20: raise ApiError( 413, "payload_too_large", "Файл превышает 10 MiB" ) expected = int(value) if expected > MAX_BYTES: raise ApiError( 413, "payload_too_large", "Файл превышает 10 MiB" ) data = bytearray() async for chunk in request.stream(): if len(data) + len(chunk) > MAX_BYTES: raise ApiError( 413, "payload_too_large", "Файл превышает 10 MiB" ) data.extend(chunk) if expected is not None and len(data) != expected: raise invalid("Размер тела не соответствует Content-Length") return bytes(data) async def accessible_attachment( attachment_id: UUID, user_id: UUID, ) -> dict: async with pool.connection() as conn: cursor = await conn.execute( """ SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, a.status, a.error_code, a.pipeline_version, a.created_at, a.updated_at FROM attachments AS a WHERE a.id = %s AND EXISTS ( SELECT 1 FROM chat_members AS cm WHERE cm.chat_id = a.chat_id AND cm.user_id = %s ) """, (attachment_id, user_id), ) row = await cursor.fetchone() if row is not None: cursor = await conn.execute( """ SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants WHERE attachment_id = %s AND pipeline_version = %s ORDER BY name """, (row["id"], row["pipeline_version"]), ) variants = await cursor.fetchall() row["_variant_objects"] = { variant["name"]: variant for variant in variants } row["variants"] = [ { key: value for key, value in variant.items() if key != "object_key" } for variant in variants ] if row["status"] == "ready" else [] if row is None: raise not_found() return row @router.post("/api/v1/chats/{chat_id}/attachments") async def upload_attachment(chat_id: str, request: Request): user, _ = await current_user(request) chat_uuid, _ = await accessible_chat(chat_id, user["id"]) filenames = request.query_params.getlist("filename") if len(filenames) != 1: raise invalid("Требуется одно имя файла") filename = validate_filename(filenames[0]) content_types = request.headers.getlist("content-type") if len(content_types) != 1: raise ApiError( 415, "unsupported_media_type", "Требуется Content-Type изображения", ) declared_type = content_types[0].split(";", 1)[0].strip().lower() if declared_type not in ("image/png", "image/jpeg"): raise ApiError( 415, "unsupported_media_type", "Допустимы только image/png и image/jpeg", ) async with binary_operation(): try: data = await asyncio.wait_for( read_image_body(request), timeout=60, ) except ClientDisconnect: raise invalid("Загрузка файла прервана") from None except TimeoutError: raise invalid("Превышено время загрузки файла") from None content_type = await run_in_threadpool( inspect_image, data, declared_type, ) row = await accept_upload( chat_id=chat_uuid, owner_id=user["id"], filename=filename, content_type=content_type, data=data, ) return json_response(public_attachment(row), 202) @router.get("/api/v1/attachments/{attachment_id}") async def get_attachment(attachment_id: str, request: Request): user, _ = await current_user(request) row = await accessible_attachment( parse_uuid(attachment_id), user["id"], ) return json_response(public_attachment(row)) @router.get("/api/v1/attachments/{attachment_id}/content") async def download_attachment(attachment_id: str, request: Request): user, _ = await current_user(request) row = await accessible_attachment( parse_uuid(attachment_id), user["id"], ) variants = request.query_params.getlist("variant") if len(variants) > 1: raise invalid("Допускается один вариант изображения") variant_name = variants[0] if variants else "original" if row["status"] != "ready": raise ApiError( 409, "conflict", "Вложение не готово к скачиванию", ) if variant_name == "original": selected = row else: selected = row["_variant_objects"].get(variant_name) if selected is None: raise not_found() async with binary_operation(): data = await get_object(selected["object_key"]) if ( len(data) != selected["size_bytes"] or hashlib.sha256(data).hexdigest() != selected["sha256"] ): raise ApiError( 503, "unavailable", "Изображение временно недоступно", ) return Response( content=data, media_type=selected["content_type"], headers={ "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store", }, )