forked from mtusi2026/mtusi2026lab4
133 lines
4.1 KiB
Python
133 lines
4.1 KiB
Python
"""Вложения: upload в S3, метаданные в PostgreSQL, download через API."""
|
|
import re
|
|
import uuid
|
|
|
|
from fastapi import APIRouter, Depends, Query, Request, Security
|
|
from fastapi.responses import Response
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..deps import current_user, get_db, parse_uuid
|
|
from ..errors import ApiError
|
|
from ..models import Attachment, ChatMember, User
|
|
from ..schemas import AttachmentOut
|
|
from .. import s3
|
|
|
|
router = APIRouter()
|
|
|
|
_FILENAME_BAD = re.compile(r"[/\\\x00-\x1f\x7f]")
|
|
|
|
|
|
def _validate_filename(raw: str) -> str:
|
|
if not isinstance(raw, str) or not (1 <= len(raw) <= 255):
|
|
raise ApiError(400, "invalid_request", "Некорректный filename")
|
|
if _FILENAME_BAD.search(raw):
|
|
raise ApiError(400, "invalid_request", "Некорректный filename")
|
|
return raw
|
|
|
|
|
|
def _require_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
|
if db.get(ChatMember, (chat_id, user_id)) is None:
|
|
raise ApiError(404, "not_found", "Чат не найден")
|
|
|
|
|
|
def _to_out(att: Attachment) -> AttachmentOut:
|
|
return AttachmentOut(
|
|
id=att.id,
|
|
chat_id=att.chat_id,
|
|
owner_id=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=att.error_code,
|
|
created_at=att.created_at,
|
|
updated_at=att.updated_at,
|
|
)
|
|
|
|
|
|
@router.post(
|
|
"/api/v1/chats/{chat_id}/attachments",
|
|
response_model=AttachmentOut,
|
|
status_code=201,
|
|
)
|
|
async def upload_attachment(
|
|
chat_id: str,
|
|
request: Request,
|
|
filename: str = Query(...),
|
|
user: User = Security(current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
cid = parse_uuid(chat_id)
|
|
_require_member(db, cid, user.id)
|
|
name = _validate_filename(filename)
|
|
|
|
declared = (request.headers.get("content-type") or "").split(";")[0].strip().lower()
|
|
if declared not in ("image/png", "image/jpeg"):
|
|
raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg")
|
|
|
|
# Читаем тело потоково с жёстким лимитом.
|
|
data, sha, actual = s3.read_upload(request.stream(), declared)
|
|
|
|
att_id = uuid.uuid4()
|
|
key = s3.new_object_key(str(cid), str(att_id))
|
|
s3.put_object(key, data, actual)
|
|
|
|
att = Attachment(
|
|
id=att_id,
|
|
chat_id=cid,
|
|
owner_id=user.id,
|
|
filename=name,
|
|
content_type=actual,
|
|
size_bytes=len(data),
|
|
sha256=sha,
|
|
object_key=key,
|
|
status="ready",
|
|
error_code=None,
|
|
)
|
|
db.add(att)
|
|
try:
|
|
db.commit()
|
|
except Exception:
|
|
db.rollback()
|
|
# Компенсация: удаляем объект, чтобы не оставить orphan в S3.
|
|
s3.delete_object(key)
|
|
raise
|
|
db.refresh(att)
|
|
return _to_out(att)
|
|
|
|
|
|
@router.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentOut)
|
|
def get_attachment(
|
|
attachment_id: str,
|
|
user: User = Security(current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
aid = parse_uuid(attachment_id)
|
|
att = db.get(Attachment, aid)
|
|
if att is None:
|
|
raise ApiError(404, "not_found", "Вложение не найдено")
|
|
_require_member(db, att.chat_id, user.id)
|
|
return _to_out(att)
|
|
|
|
|
|
@router.get("/api/v1/attachments/{attachment_id}/content")
|
|
def download_attachment(
|
|
attachment_id: str,
|
|
variant: str = Query("original"),
|
|
user: User = Security(current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
aid = parse_uuid(attachment_id)
|
|
att = db.get(Attachment, aid)
|
|
if att is None:
|
|
raise ApiError(404, "not_found", "Вложение не найдено")
|
|
_require_member(db, att.chat_id, user.id)
|
|
if variant != "original":
|
|
raise ApiError(404, "not_found", "Вариант не найден")
|
|
if att.status != "ready":
|
|
raise ApiError(409, "conflict", "Вложение не готово")
|
|
body, ctype = s3.get_object(att.object_key)
|
|
return Response(content=body, media_type=ctype)
|