lab4_
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
import hashlib
|
||||
import io
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..db import transaction, connection
|
||||
from ..errors import ApiError
|
||||
from ..s3 import upload_fileobj, download_fileobj, delete_file
|
||||
from ..image_check import check_image
|
||||
from ..serializers import iso_z
|
||||
from .sessions import require_actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
MAX_SIZE = 10 * 1024 * 1024
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=201)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
filename: str = Query(..., max_length=255),
|
||||
actor: dict = Depends(require_actor),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный chat_id")
|
||||
|
||||
if "/" in filename or "\\" in filename or "\0" in filename:
|
||||
raise ApiError(400, "invalid_request", "Опасное имя файла")
|
||||
|
||||
# Проверяем доступ к чату
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, actor["user_id"]),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
|
||||
sha256 = hashlib.sha256()
|
||||
size = 0
|
||||
first_chunk = b""
|
||||
|
||||
# Читаем потоково во временный файл (чтобы не забивать RAM)
|
||||
with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled:
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_SIZE:
|
||||
raise ApiError(413, "payload_too_large", "Файл слишком большой")
|
||||
if not first_chunk:
|
||||
first_chunk = chunk[:16] # для детекта MIME
|
||||
sha256.update(chunk)
|
||||
spooled.write(chunk)
|
||||
|
||||
if size == 0:
|
||||
raise ApiError(400, "invalid_request", "Пустой файл")
|
||||
|
||||
# Полная проверка картинки через Pillow
|
||||
try:
|
||||
spooled.seek(0)
|
||||
content = spooled.read()
|
||||
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
|
||||
from PIL import Image
|
||||
Image.open(io.BytesIO(content)).verify()
|
||||
except Exception:
|
||||
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый или битый формат")
|
||||
|
||||
sha256_hex = sha256.hexdigest()
|
||||
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
|
||||
|
||||
# Загружаем в S3
|
||||
try:
|
||||
spooled.seek(0)
|
||||
upload_fileobj(spooled, object_key, content_type)
|
||||
except Exception as e:
|
||||
print(f"S3 error: {e}")
|
||||
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||
|
||||
# Сохраняем в БД (с компенсацией)
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at
|
||||
""",
|
||||
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
except Exception as e:
|
||||
# КОМПЕНСАЦИЯ: удаляем из S3, если БД упала
|
||||
print(f"DB failed, compensating S3: {e}")
|
||||
try:
|
||||
delete_file(object_key)
|
||||
except Exception as s3_e:
|
||||
print(f"Failed to compensate S3: {s3_e}")
|
||||
raise ApiError(500, "internal_error", "Ошибка сохранения")
|
||||
|
||||
return {
|
||||
"id": str(att["id"]),
|
||||
"chat_id": str(att["chat_id"]),
|
||||
"owner_id": str(att["owner_id"]),
|
||||
"filename": att["filename"],
|
||||
"content_type": att["content_type"],
|
||||
"size_bytes": att["size_bytes"],
|
||||
"sha256": att["sha256"],
|
||||
"status": "ready",
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}")
|
||||
def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный id")
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.*
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(actor["user_id"], attachment_id),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
if att is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
|
||||
return {
|
||||
"id": str(att["id"]),
|
||||
"chat_id": str(att["chat_id"]),
|
||||
"owner_id": str(att["owner_id"]),
|
||||
"filename": att["filename"],
|
||||
"content_type": att["content_type"],
|
||||
"size_bytes": att["size_bytes"],
|
||||
"sha256": att["sha256"],
|
||||
"status": "ready",
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/content")
|
||||
def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный id")
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.object_key, a.content_type, a.filename
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(actor["user_id"], attachment_id),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
if att is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
|
||||
try:
|
||||
body = download_fileobj(att["object_key"])
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||
|
||||
def iter_body():
|
||||
yield from body.iter_chunks(1024 * 1024)
|
||||
|
||||
return StreamingResponse(
|
||||
iter_body(),
|
||||
media_type=att["content_type"],
|
||||
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'},
|
||||
)
|
||||
Reference in New Issue
Block a user