diff --git a/app/main.py b/app/main.py index 862e90d..c4a0bd0 100644 --- a/app/main.py +++ b/app/main.py @@ -18,8 +18,8 @@ from sqlalchemy.ext.asyncio import AsyncSession from starlette.middleware.base import BaseHTTPMiddleware from .auth import ( - SESSION_TTL, create_session, get_current_user, - hash_password, revoke_current_session, verify_password, + SESSION_TTL, create_session, get_current_user, hash_password, + revoke_current_session, verify_password, ) from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment from .db.session import get_db @@ -29,6 +29,7 @@ from .repositories import messages as messages_repo from .repositories import users as users_repo from .s3_client import s3, BUCKET, ensure_bucket from .image_utils import validate_image +from .queue import publish_task INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}") request_id_var: ContextVar[str] = ContextVar("request_id", default="") @@ -53,7 +54,7 @@ class RequestIdMiddleware(BaseHTTPMiddleware): response.headers["X-Instance-Id"] = INSTANCE_ID return response -app = FastAPI(title="MTUSI Messenger — lab4") +app = FastAPI(title="MTUSI Messenger — lab5") app.add_middleware(RequestIdMiddleware) security = HTTPBasic(auto_error=False) @@ -100,7 +101,7 @@ def _attachment_json(att: Attachment) -> dict: "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, "error_code": att.error_code, - "variants": [], + "variants": att.variants or [], "created_at": _iso_z(att.created_at), "updated_at": _iso_z(att.updated_at), } @@ -238,7 +239,7 @@ async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), l nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None return {"items": items, "next_cursor": nxt} -@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) +@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202) async def upload_attachment(chat_id: UUID, request: Request, filename: str = Query(..., min_length=1, max_length=255), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): chat = await chats_repo.get_if_member(db, chat_id, user.id) if not chat: raise HTTPException(404, "Chat not found") @@ -252,10 +253,19 @@ async def upload_attachment(chat_id: UUID, request: Request, filename: str = Que s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime) - att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="ready", s3_key=s3_key) + att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="queued", s3_key=s3_key) db.add(att) await db.commit() await db.refresh(att) + + # отправляем задачу в rabbitmq + publish_task({ + "attachment_id": str(att.id), + "chat_id": str(chat_id), + "s3_key": s3_key, + "mime": mime, + }) + return _attachment_json(att) @app.get("/api/v1/attachments/{attachment_id}") @@ -267,15 +277,23 @@ async def get_attachment(attachment_id: UUID, user: User = Depends(get_current_u return _attachment_json(att) @app.get("/api/v1/attachments/{attachment_id}/content") -async def download_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): +async def download_attachment(attachment_id: UUID, variant: str = Query("original"), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): att = await db.get(Attachment, attachment_id) if not att: raise HTTPException(404, "Attachment not found") chat = await chats_repo.get_if_member(db, att.chat_id, user.id) if not chat: raise HTTPException(404, "Attachment not found") - obj = s3.get_object(Bucket=BUCKET, Key=att.s3_key) + if att.status != "ready": + raise HTTPException(409, "Attachment not ready") + + key = att.s3_key + if variant == "thumbnail": + key = f"{att.s3_key}_thumb.jpg" + + obj = s3.get_object(Bucket=BUCKET, Key=key) content = obj["Body"].read() - return Response(content=content, media_type=att.content_type) + mime = "image/jpeg" if variant == "thumbnail" else att.content_type + return Response(content=content, media_type=mime) if __name__ == "__main__": import uvicorn