Files
mtusi2026lab4-fork/app/api/routes/attachments.py

156 lines
5.7 KiB
Python

import hashlib
import io
import uuid
import warnings
from fastapi import APIRouter, Query, Request
from fastapi.responses import 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 __import__('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': 'ready',
'variants': [],
'error_code': None,
'created_at': row.created_at,
'updated_at': row.updated_at,
}
@router.post('/api/v1/chats/{chat_id}/attachments', status_code=201)
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())
object_key = 'original/' + uuid.uuid4().hex
digest = hashlib.sha256(data).hexdigest()
object_store = request.app.state.object_store
await object_store.put(object_key, data, content_type)
try:
row = await request.app.state.storage.create_attachment(
attachment_id=attachment_id,
chat_id=chat.id,
owner_id=user.id,
object_key=object_key,
filename=filename,
content_type=content_type,
size_bytes=len(data),
sha256=digest,
)
except Exception:
# Если запись метаданных не зафиксирована, пытаемся убрать только что загруженный объект.
try:
await object_store.delete(object_key)
except ApiError:
pass
raise
return 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', pattern=r'^original$'),
):
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')
data = await request.app.state.object_store.get(row.object_key)
return Response(
content=data,
media_type=row.content_type,
headers={'Cache-Control': 'private, no-store'},
)