lab4 for lab5

This commit is contained in:
Матвей
2026-10-26 10:05:24 +03:00
parent 276dbdad8a
commit 3b67201e5e
40 changed files with 3522 additions and 0 deletions
+116
View File
@@ -0,0 +1,116 @@
import asyncio
from hashlib import sha256
import os
from tempfile import TemporaryFile
import unicodedata
from uuid import UUID, uuid4
import warnings
from fastapi import APIRouter, Depends, Query, Request, Response
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from .errors import ApiError
from .models import Attachment
from .routes import get_current_user, get_store
from .storage.postgres import PostgresStore
router = APIRouter()
Image.MAX_IMAGE_PIXELS = 40000000
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)
def inspect_image(file, content_type, max_pixels):
try:
file.seek(0)
with Image.open(file, formats=("PNG", "JPEG")) as image:
if image.width * image.height > max_pixels:
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format]
if actual != content_type or getattr(image, "n_frames", 1) != 1:
raise ApiError(415, "unsupported_media_type", "Нужен обычный PNG или JPEG")
image.verify()
# verify checks PNG CRC; load also catches truncated pixel streams/JPEGs.
file.seek(0)
with Image.open(file, formats=("PNG", "JPEG")) as image:
image.load()
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as error:
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from error
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as error:
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from error
file.seek(0)
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=201)
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
await store.get_chat_for_member(chat_id, user["id"])
if (not 1 <= len(filename) <= 255 or not filename.strip() or
any(c in "/\\" or unicodedata.category(c) in {"Cc", "Cs"} for c in filename)):
raise ApiError(400, "invalid_request", "Некорректное имя файла")
content_type = request.headers.get("content-type", "").lower()
if content_type not in {"image/png", "image/jpeg"}:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
s3 = request.app.state.s3
limit = s3.settings.max_bytes
if "content-length" in request.headers:
try:
length = int(request.headers["content-length"])
if length < 0:
raise ValueError()
except ValueError:
raise ApiError(400, "invalid_request", "Некорректная длина") from None
if length > limit:
raise ApiError(413, "payload_too_large", "Файл больше лимита")
try:
timeout = int(os.environ.get("UPLOAD_TIMEOUT_SECONDS", "30"))
if not 1 <= timeout <= 120:
raise ApiError(503, "unavailable", "Некорректный лимит времени загрузки")
async with asyncio.timeout(timeout):
async with request.app.state.upload_slot:
# Temporary scratch space only; deleted on every exit, never used for downloads.
with TemporaryFile() as file:
size = 0
digest = sha256()
async for chunk in request.stream():
size += len(chunk)
if size > limit:
raise ApiError(413, "payload_too_large", "Файл больше лимита")
digest.update(chunk)
await run_in_threadpool(file.write, chunk)
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
attachment_id = uuid4()
key = f"originals/{attachment_id}"
async with store.attachment_transaction() as connection:
await s3.put(key, file, size, content_type)
# Disabled by default; models a crash after PUT, before INSERT.
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
attachment = await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key, connection=connection,
)
return attachment # Transaction has committed before 201.
except ClientDisconnect:
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
except TimeoutError:
raise ApiError(503, "unavailable", "Время загрузки истекло") from None
@router.get("/api/v1/attachments/{attachment_id}", response_model=Attachment)
async def metadata(attachment_id: UUID, user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store)):
return await store.attachment_for_member(attachment_id, user["id"])
@router.get("/api/v1/attachments/{attachment_id}/content")
async def download(attachment_id: UUID, request: Request,
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
attachment = await store.attachment_for_member(attachment_id, user["id"])
if variant != "original":
raise ApiError(404, "not_found", "Вариант не найден")
data = await request.app.state.s3.download(attachment)
return Response(data, media_type=attachment["content_type"],
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})