lab4
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
import os
|
||||
import uuid
|
||||
import hashlib
|
||||
import magic
|
||||
import tempfile
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.database import get_db
|
||||
from app.models import Attachment, ChatMember
|
||||
from app.schemas import Attachment as AttachmentSchema, Variant, ErrorResponse
|
||||
from app.dependencies import get_current_user
|
||||
from app.s3_client import get_s3_client, upload_file_to_s3
|
||||
from minio import Minio
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=AttachmentSchema, status_code=status.HTTP_201_CREATED, responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}, 413: {"model": ErrorResponse}, 415: {"model": ErrorResponse}})
|
||||
async def upload_attachment(
|
||||
chat_id: uuid.UUID,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
request: Request = None,
|
||||
current_user = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
s3: Minio = Depends(get_s3_client)
|
||||
):
|
||||
# 1. Проверка доступа к чату
|
||||
is_member = await db.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == current_user.id)
|
||||
)
|
||||
if not is_member.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Chat not found or access denied"})
|
||||
|
||||
# 2. Чтение сырых байтов
|
||||
body = await request.body()
|
||||
|
||||
# 3. Проверка размера (макс. 10 MiB)
|
||||
MAX_SIZE = 10 * 1024 * 1024
|
||||
if len(body) > MAX_SIZE:
|
||||
raise HTTPException(status_code=413, detail={"code": "payload_too_large", "message": "File size exceeds 10 MiB limit"})
|
||||
if len(body) == 0:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Empty file"})
|
||||
|
||||
# 4. Определение MIME-типа по содержимому
|
||||
mime = magic.from_buffer(body, mime=True)
|
||||
if mime not in ("image/png", "image/jpeg"):
|
||||
raise HTTPException(status_code=415, detail={"code": "unsupported_media_type", "message": "Only image/png and image/jpeg are supported"})
|
||||
|
||||
# 5. Проверка размеров изображения (макс. 40 млн пикселей)
|
||||
try:
|
||||
img = Image.open(io.BytesIO(body))
|
||||
width, height = img.size
|
||||
if width * height > 40_000_000:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Image resolution exceeds 40 million pixels"})
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_request", "message": "Invalid or corrupted image file"})
|
||||
|
||||
# 6. Вычисление SHA256
|
||||
sha256_hash = hashlib.sha256(body).hexdigest()
|
||||
|
||||
# 7. Генерация уникального ключа для S3
|
||||
ext = "png" if mime == "image/png" else "jpeg"
|
||||
s3_key = f"attachments/{uuid.uuid4()}.{ext}"
|
||||
|
||||
# 8. Загрузка в S3 через временный файл
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{ext}") as tmp:
|
||||
tmp.write(body)
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
await upload_file_to_s3(s3_key, tmp_path, mime)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Failed to upload to S3"})
|
||||
finally:
|
||||
os.unlink(tmp_path)
|
||||
|
||||
# 9. Сохранение метаданных в БД
|
||||
new_attachment = Attachment(
|
||||
owner_id=current_user.id,
|
||||
chat_id=chat_id,
|
||||
s3_key=s3_key,
|
||||
original_filename=filename,
|
||||
content_type=mime,
|
||||
size_bytes=len(body),
|
||||
width=width,
|
||||
height=height,
|
||||
sha256=sha256_hash,
|
||||
status="ready",
|
||||
error_code=None
|
||||
)
|
||||
db.add(new_attachment)
|
||||
await db.commit()
|
||||
await db.refresh(new_attachment)
|
||||
|
||||
now_str = new_attachment.created_at.isoformat().replace('+00:00', 'Z')
|
||||
return AttachmentSchema(
|
||||
id=str(new_attachment.id),
|
||||
chat_id=str(new_attachment.chat_id),
|
||||
owner_id=str(new_attachment.owner_id),
|
||||
filename=new_attachment.original_filename,
|
||||
content_type=new_attachment.content_type,
|
||||
size_bytes=new_attachment.size_bytes,
|
||||
sha256=new_attachment.sha256,
|
||||
status=new_attachment.status,
|
||||
variants=[],
|
||||
error_code=new_attachment.error_code,
|
||||
created_at=now_str,
|
||||
updated_at=now_str
|
||||
)
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}/content", responses={400: {"model": ErrorResponse}, 401: {"model": ErrorResponse}, 404: {"model": ErrorResponse}})
|
||||
async def download_attachment(
|
||||
attachment_id: uuid.UUID,
|
||||
variant: str = Query(default="original"),
|
||||
current_user = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
s3: Minio = Depends(get_s3_client)
|
||||
):
|
||||
# 1. Проверяем существование вложения
|
||||
stmt = select(Attachment).where(Attachment.id == attachment_id)
|
||||
result = await db.execute(stmt)
|
||||
attachment = result.scalar_one_or_none()
|
||||
|
||||
if not attachment:
|
||||
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Attachment not found"})
|
||||
|
||||
# 2. Проверяем, что пользователь является участником чата
|
||||
is_member = await db.execute(
|
||||
select(ChatMember).where(ChatMember.chat_id == attachment.chat_id, ChatMember.user_id == current_user.id)
|
||||
)
|
||||
if not is_member.scalar_one_or_none():
|
||||
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Access denied"})
|
||||
|
||||
# 3. Получаем объект из S3
|
||||
try:
|
||||
response = s3.get_object("messenger-attachments", attachment.s3_key)
|
||||
data = response.read()
|
||||
response.close()
|
||||
response.release_conn()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail={"code": "internal_error", "message": "Failed to download from S3"})
|
||||
|
||||
# 4. Возвращаем байты с правильным Content-Type
|
||||
return Response(content=data, media_type=attachment.content_type)
|
||||
Reference in New Issue
Block a user