лаба 4

This commit is contained in:
2026-10-29 02:56:13 +03:00
parent f3bcdad9e8
commit 0ef8d739d7
19 changed files with 1900 additions and 58 deletions
+201 -5
View File
@@ -4,22 +4,24 @@ import os
import re
import base64
import binascii
import asyncio
from fastapi import Depends, FastAPI, Request, Header
from fastapi import Depends, FastAPI, Request, Header, Query
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.responses import JSONResponse, Response
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBearer,
)
from botocore.exceptions import BotoCoreError, ClientError
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.exceptions import HTTPException as StarletteHTTPException
from contextlib import asynccontextmanager
from src.database import engine, get_db_session, ping_database
from src.database import engine, get_db_session, ping_database, SessionFactory
from src.errors import APIError
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage
from src.models import CreateUser, SessionResponse, User, CreateChat, Chat, ChatPage, CreateMessage, Message, MessagePage, Attachment
from src.repositories import (
create_chat,
list_chats,
@@ -29,6 +31,9 @@ from src.repositories import (
get_user_credentials_by_username,
create_message,
get_messages,
create_attachment,
get_attachment,
attachment_key_exists,
)
from src.security import verify_password
from src.sessions import (
@@ -38,6 +43,8 @@ from src.sessions import (
ping_session_store,
redis_client,
)
from src.images import MAX_UPLOAD_BYTES, validate_image
from src.storage import delete_object, put_object, get_object
@asynccontextmanager
@@ -105,7 +112,21 @@ async def request_middleware(request: Request, call_next):
if content_type is not None:
media_type = content_type.split(";", 1)[0].strip().lower()
if media_type != "application/json":
is_attachment_upload = (
request.method == "POST"
and re.fullmatch(
r"/api/v1/chats/[^/]+/attachments",
request.url.path,
) is not None
)
allowed_media_types = (
{"image/png", "image/jpeg"}
if is_attachment_upload
else {"application/json"}
)
if media_type not in allowed_media_types:
return JSONResponse(
status_code=415,
content={
@@ -526,3 +547,178 @@ async def get_messages_endpoint(
limit=limit,
cursor=cursor,
)
@app.post(
"/api/v1/chats/{chat_id}/attachments",
response_model=Attachment,
status_code=201,
)
async def upload_attachment_endpoint(
chat_id: UUID,
request: Request,
filename: str = Query(min_length=1, max_length=255),
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Attachment:
chat = await get_chat_by_id(
session=session,
chat_id=chat_id,
current_user_id=current_user.id,
)
if chat is None:
raise APIError(
status_code=404,
code="not_found",
message="Chat not found",
)
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type not in {"image/png", "image/jpeg"}:
raise APIError(
status_code=415,
code="unsupported_media_type",
message="Only PNG and JPEG images are supported",
)
body = bytearray()
async for chunk in request.stream():
if len(body) + len(chunk) > MAX_UPLOAD_BYTES:
raise APIError(
status_code=413,
code="payload_too_large",
message="Image exceeds maximum upload size",
)
body.extend(chunk)
image_bytes = bytes(body)
size_bytes, sha256 = validate_image(image_bytes, content_type)
attachment_id = uuid4()
extension = "png" if content_type == "image/png" else "jpg"
s3_key = f"attachments/{chat_id}/{attachment_id}.{extension}"
try:
await put_object(
key=s3_key,
body=image_bytes,
content_type=content_type,
)
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
raise APIError(
status_code=503,
code="unavailable",
message="Object storage unavailable",
) from exc
try:
attachment = await create_attachment(
session=session,
attachment_id=attachment_id,
chat_id=chat_id,
owner_id=current_user.id,
filename=filename,
content_type=content_type,
size_bytes=size_bytes,
sha256=sha256,
s3_key=s3_key,
)
await session.commit()
except BaseException:
try:
await session.rollback()
except Exception:
pass
try:
async with SessionFactory() as verification_session:
exists = await attachment_key_exists(
verification_session,
s3_key,
)
except Exception:
exists = True
if not exists:
try:
await asyncio.shield(delete_object(s3_key))
except Exception:
pass
raise
return attachment
@app.get(
"/api/v1/attachments/{attachment_id}",
response_model=Attachment,
)
async def get_attachment_endpoint(
attachment_id: UUID,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> Attachment:
result = await get_attachment(
session=session,
attachment_id=attachment_id,
current_user_id=current_user.id,
)
if result is None:
raise APIError(
status_code=404,
code="not_found",
message="Attachment not found",
)
attachment, s3_key = result
return attachment
@app.get("/api/v1/attachments/{attachment_id}/content")
async def get_attachment_content_endpoint(
attachment_id: UUID,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
):
result = await get_attachment(
session=session,
attachment_id=attachment_id,
current_user_id=current_user.id,
)
if result is None:
raise APIError(
status_code=404,
code="not_found",
message="Attachment not found",
)
attachment, s3_key = result
try:
body = await get_object(s3_key)
except (BotoCoreError, ClientError, OSError, TimeoutError) as exc:
raise APIError(
status_code=503,
code="unavailable",
message="Object storage unavailable",
) from exc
return Response(
content=body,
media_type=attachment.content_type,
headers={
"Cache-Control": "private, no-store",
"X-Content-Type-Options": "nosniff",
},
)