Lab4: S3 attachments (grade 3)
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import hashlib
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..models import Attachment, ChatMember
|
||||
from ..auth import current_user
|
||||
from ..errors import ApiError
|
||||
from .. import s3, config
|
||||
from ..images import validate_image
|
||||
from ..schemas import AttachmentOut
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
def _bad_filename(name: str) -> bool:
|
||||
return (not name) or len(name) > 255 or any(c in name for c in ("/", "\\", "\x00")) or any(ord(c) < 32 for c in name)
|
||||
|
||||
def _member_chat_or_404(db, chat_id, user_id):
|
||||
if not db.get(ChatMember, (chat_id, user_id)):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
|
||||
def _attachment_for_member(db, att_id, user_id) -> Attachment:
|
||||
att = db.get(Attachment, att_id)
|
||||
if not att:
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
_member_chat_or_404(db, att.chat_id, user_id)
|
||||
return att
|
||||
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=201, response_model=AttachmentOut)
|
||||
async def upload(chat_id: uuid.UUID,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
request: Request = None,
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(current_user)):
|
||||
_member_chat_or_404(db, chat_id, user.id)
|
||||
if _bad_filename(filename):
|
||||
raise ApiError(400, "invalid_request", "invalid filename")
|
||||
ctype_header = request.headers.get("content-type", "").split(";")[0].strip()
|
||||
if ctype_header not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(415, "unsupported_media_type", "expected image/png or image/jpeg")
|
||||
data = await request.body()
|
||||
ctype, w, h, size = validate_image(data)
|
||||
if ctype != ctype_header:
|
||||
raise ApiError(415, "unsupported_media_type", "content-type mismatch with file")
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
key = f"chats/{chat_id}/attachments/{uuid.uuid4()}"
|
||||
s3.client().put_object(Bucket=config.S3_BUCKET, Key=key, Body=data, ContentType=ctype)
|
||||
att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename,
|
||||
content_type=ctype, size_bytes=size, sha256=digest, s3_key=key,
|
||||
status="ready")
|
||||
try:
|
||||
db.add(att); db.commit(); db.refresh(att)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
try:
|
||||
s3.client().delete_object(Bucket=config.S3_BUCKET, Key=key)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return att
|
||||
|
||||
@router.get("/attachments/{att_id}", response_model=AttachmentOut)
|
||||
def meta(att_id: uuid.UUID, db=Depends(get_db), user=Depends(current_user)):
|
||||
return _attachment_for_member(db, att_id, user.id)
|
||||
|
||||
@router.get("/attachments/{att_id}/content")
|
||||
def content(att_id: uuid.UUID, db=Depends(get_db), user=Depends(current_user)):
|
||||
att = _attachment_for_member(db, att_id, user.id)
|
||||
obj = s3.client().get_object(Bucket=config.S3_BUCKET, Key=att.s3_key)
|
||||
body = obj["Body"].read()
|
||||
return Response(content=body, media_type=att.content_type)
|
||||
Reference in New Issue
Block a user