Files

172 lines
5.0 KiB
Python

import uuid
import filetype
import io
import hashlib
from datetime import datetime, timezone
from PIL import Image
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.dependencies import get_session
from app.security import get_current_user
from app.models.user import User
from app.models.attachment import Attachment
from app.models.chat import ChatMember
from app.storage import minio_client, BUCKET
router_upload = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
router_download = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
MAX_SIZE = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
CHUNK_SIZE = 64 * 1024
def build_attachment_response(att: Attachment) -> dict:
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
return {
"id": str(att.id),
"chat_id": str(att.chat_id),
"owner_id": str(att.user_id),
"filename": att.filename,
"content_type": att.mime_type,
"size_bytes": att.size_bytes,
"sha256": att.sha256,
"status": "ready",
"variants": [],
"error_code": None,
"created_at": now,
"updated_at": now,
}
@router_upload.post("", status_code=201)
async def upload_attachment(
chat_id: uuid.UUID,
filename: str = Query(..., min_length=1, max_length=255, pattern=r"^[^/\\\x00]+$"),
request: Request = None,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
result = await session.execute(
select(ChatMember).where(
ChatMember.chat_id == chat_id,
ChatMember.user_id == user.id,
)
)
if not result.scalar_one_or_none():
raise HTTPException(404, "Чат не найден")
sha_hasher = hashlib.sha256()
buffer = io.BytesIO()
total = 0
first_bytes = b""
async for chunk in request.stream():
if not chunk:
continue
total += len(chunk)
if total > MAX_SIZE:
raise HTTPException(413, "File too large")
sha_hasher.update(chunk)
buffer.write(chunk)
if len(first_bytes) < 262:
need = 262 - len(first_bytes)
first_bytes += chunk[:need]
kind = filetype.guess(first_bytes)
if not kind or kind.mime not in ("image/png", "image/jpeg"):
raise HTTPException(400, "Only PNG/JPEG allowed")
contents = buffer.getvalue()
try:
img = Image.open(io.BytesIO(contents))
if img.width * img.height > MAX_PIXELS:
raise HTTPException(400, "Image too large (pixels)")
except HTTPException:
raise
except Exception:
raise HTTPException(400, "Corrupted image")
object_key = f"{uuid.uuid4()}.{kind.extension}"
minio_client.put_object(
BUCKET,
object_key,
io.BytesIO(contents),
len(contents),
content_type=kind.mime,
)
sha_hash = sha_hasher.hexdigest()
att = Attachment(
object_key=object_key,
filename=filename,
mime_type=kind.mime,
size_bytes=len(contents),
chat_id=chat_id,
user_id=user.id,
sha256=sha_hash,
)
session.add(att)
await session.commit()
await session.refresh(att)
return build_attachment_response(att)
@router_download.get("/{attachment_id}/content")
async def download_attachment_content(
attachment_id: uuid.UUID,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
att = await session.get(Attachment, attachment_id)
if not att:
raise HTTPException(404, "Not found")
result = await session.execute(
select(ChatMember).where(
ChatMember.chat_id == att.chat_id,
ChatMember.user_id == user.id,
)
)
if not result.scalar_one_or_none():
raise HTTPException(404, "Not found")
try:
response = minio_client.get_object(BUCKET, att.object_key)
return StreamingResponse(
response,
media_type=att.mime_type,
headers={"Content-Disposition": f'attachment; filename="{att.filename}"'},
)
except Exception:
raise HTTPException(404, "File not found in storage")
@router_download.get("/{attachment_id}")
async def get_attachment_metadata(
attachment_id: uuid.UUID,
user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_session),
):
att = await session.get(Attachment, attachment_id)
if not att:
raise HTTPException(404, "Not found")
result = await session.execute(
select(ChatMember).where(
ChatMember.chat_id == att.chat_id,
ChatMember.user_id == user.id,
)
)
if not result.scalar_one_or_none():
raise HTTPException(404, "Not found")
return build_attachment_response(att)