import hashlib import io import unicodedata import uuid import warnings from fastapi import APIRouter, Query, Request from fastapi.responses import JSONResponse, Response from PIL import Image, UnidentifiedImageError from app.api.deps import current_user, require_chat_member from app.core.config import settings from app.core.errors import ApiError router = APIRouter() MIME_BY_FORMAT = {'PNG': 'image/png', 'JPEG': 'image/jpeg'} def _validate_filename(filename: str) -> None: if not filename or len(filename) > 255 or not filename.strip(): raise ApiError(400, 'Invalid filename') if any(ch in filename for ch in ('/', chr(92))): raise ApiError(400, 'Invalid filename') if any(ord(ch) == 0 or unicodedata.category(ch).startswith('C') for ch in filename): raise ApiError(400, 'Invalid filename') async def _read_bounded_body(request: Request) -> bytes: length = request.headers.get('content-length') if length: try: size = int(length) except ValueError: raise ApiError(400, 'Invalid Content-Length') from None if size < 0: raise ApiError(400, 'Invalid Content-Length') if size > settings.max_upload_bytes: raise ApiError(413, 'Image exceeds the maximum size') chunks = [] total = 0 async for chunk in request.stream(): total += len(chunk) if total > settings.max_upload_bytes: raise ApiError(413, 'Image exceeds the maximum size') chunks.append(chunk) if total == 0: raise ApiError(415, 'Empty or invalid image') return b''.join(chunks) def _validate_image(data: bytes, declared_type: str) -> None: if declared_type not in {'image/png', 'image/jpeg'}: raise ApiError(415, 'Only PNG and JPEG images are accepted') try: with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) with Image.open(io.BytesIO(data)) as image: actual_type = MIME_BY_FORMAT.get(image.format) width, height = image.size if actual_type is None or actual_type != declared_type: raise ApiError(415, 'Image content does not match Content-Type') if width < 1 or height < 1: raise ApiError(415, 'Invalid image dimensions') if width * height > settings.max_image_pixels: raise ApiError(413, 'Image exceeds the maximum pixel count') image.verify() except ApiError: raise except (UnidentifiedImageError, Image.DecompressionBombError, Image.DecompressionBombWarning, OSError, SyntaxError, ValueError): raise ApiError(415, 'Image content is invalid or unsupported') from None def attachment_out(row) -> dict: return { 'id': row.id, 'chat_id': row.chat_id, 'owner_id': row.owner_id, 'filename': row.filename, 'content_type': row.content_type, 'size_bytes': row.size_bytes, 'sha256': row.sha256, 'status': row.status, 'variants': row.variants, 'error_code': row.error_code, 'created_at': row.created_at, 'updated_at': row.updated_at, } @router.post('/api/v1/chats/{chat_id}/attachments', status_code=202) async def upload_attachment( chat_id: str, request: Request, filename: str = Query(min_length=1, max_length=255), ): user = await current_user(request) chat = await require_chat_member(request, chat_id, user) _validate_filename(filename) content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower() if content_type not in {'image/png', 'image/jpeg'}: raise ApiError(415, 'Only PNG and JPEG images are accepted') data = await _read_bounded_body(request) _validate_image(data, content_type) attachment_id = str(uuid.uuid4()) job_id = str(uuid.uuid4()) staging_key = f'staging/{attachment_id}' object_key = f'original/{attachment_id}' digest = hashlib.sha256(data).hexdigest() object_store = request.app.state.object_store # Ответ 202 появится только после долговременной записи исходника и задания. await object_store.put(staging_key, data, content_type) try: row = await request.app.state.storage.create_attachment( attachment_id=attachment_id, job_id=job_id, chat_id=chat.id, owner_id=user.id, object_key=object_key, staging_key=staging_key, filename=filename, content_type=content_type, size_bytes=len(data), sha256=digest, ) except Exception: try: await object_store.delete(staging_key) except ApiError: pass raise return JSONResponse(status_code=202, content=attachment_out(row)) @router.get('/api/v1/attachments/{attachment_id}') async def get_attachment(attachment_id: str, request: Request): user = await current_user(request) row = await request.app.state.storage.attachment_for_member(attachment_id, user.id) if row is None: raise ApiError(404, 'Attachment is not available for this user') return attachment_out(row) @router.get('/api/v1/attachments/{attachment_id}/content') async def download_attachment( attachment_id: str, request: Request, variant: str = Query(default='original', min_length=1, max_length=32), ): user = await current_user(request) row = await request.app.state.storage.attachment_for_member(attachment_id, user.id) if row is None: raise ApiError(404, 'Attachment is not available for this user') if row.status in {'queued', 'processing', 'failed'}: raise ApiError(409, 'Attachment content is not ready') if variant == 'original': object_key, content_type = row.object_key, row.content_type else: metadata = next((item for item in row.variants if item.get('name') == variant), None) if metadata is None: raise ApiError(404, 'Attachment variant does not exist') object_key = f"variants/{row.id}/v1/{variant}.jpg" content_type = metadata['content_type'] data = await request.app.state.object_store.get(object_key) return Response( content=data, media_type=content_type, headers={'Cache-Control': 'private, no-store'}, )