forked from mtusi2026/mtusi2026lab7
lab6_files
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
import hashlib
|
||||
import io
|
||||
import tempfile
|
||||
import uuid
|
||||
import json
|
||||
|
||||
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=202)
|
||||
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""
|
||||
|
||||
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]
|
||||
sha256.update(chunk)
|
||||
spooled.write(chunk)
|
||||
|
||||
if size == 0:
|
||||
raise ApiError(400, "invalid_request", "Пустой файл")
|
||||
|
||||
try:
|
||||
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
|
||||
except ValueError:
|
||||
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат")
|
||||
|
||||
sha256_hex = sha256.hexdigest()
|
||||
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
|
||||
|
||||
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:
|
||||
# 1. Сохраняем вложение
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued')
|
||||
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at
|
||||
""",
|
||||
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
# 2. Сохраняем задачу в Outbox в ТОЙ ЖЕ транзакции
|
||||
payload = {"attachment_id": str(att["id"]), "object_key": object_key}
|
||||
cur.execute(
|
||||
"INSERT INTO outbox_messages (attachment_id, payload) VALUES (%s, %s)",
|
||||
(att["id"], json.dumps(payload))
|
||||
)
|
||||
except Exception as e:
|
||||
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": att["status"],
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["updated_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:
|
||||
cur.execute("SELECT * FROM attachment_variants WHERE attachment_id = %s", (attachment_id,))
|
||||
variants = cur.fetchall()
|
||||
else:
|
||||
variants = []
|
||||
|
||||
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": att["status"],
|
||||
"variants": [
|
||||
{
|
||||
"name": v["name"],
|
||||
"content_type": v["content_type"],
|
||||
"size_bytes": v["size_bytes"],
|
||||
"width": v["width"],
|
||||
"height": v["height"],
|
||||
"sha256": v["sha256"],
|
||||
} for v in variants
|
||||
],
|
||||
"error_code": att["error_code"],
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/content")
|
||||
def download_attachment(
|
||||
attachment_id: str,
|
||||
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
|
||||
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, a.status
|
||||
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", "Вложение не найдено")
|
||||
|
||||
if variant == "original":
|
||||
if att["status"] == "failed":
|
||||
raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой")
|
||||
obj_key = att["object_key"]
|
||||
content_type = att["content_type"]
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT object_key, content_type FROM attachment_variants WHERE attachment_id = %s AND name = %s",
|
||||
(attachment_id, variant)
|
||||
)
|
||||
var = cur.fetchone()
|
||||
if not var:
|
||||
raise ApiError(404, "not_found", "Вариант еще не готов или недоступен")
|
||||
obj_key = var["object_key"]
|
||||
content_type = var["content_type"]
|
||||
|
||||
try:
|
||||
body = download_fileobj(obj_key)
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||
|
||||
def iter_body():
|
||||
yield from body.iter_chunks(1024 * 1024)
|
||||
|
||||
return StreamingResponse(
|
||||
iter_body(),
|
||||
media_type=content_type,
|
||||
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'},
|
||||
)
|
||||
Reference in New Issue
Block a user