Files
mtusi2026lab6/src/attachments.py
T
2026-12-03 20:20:07 +03:00

132 lines
5.9 KiB
Python

import asyncio
import hashlib
import tempfile
import unicodedata
import warnings
from uuid import uuid4
import anyio
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from .errors import ApiError, invalid, not_found
from .storage import serialize
MAX_BYTES = 10485760
MAX_PIXELS = 40000000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
FIELDS = ("id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,"
"status,variants,error_code")
def thumbnail_key(original_key):
return original_key + ".v1.thumbnail.jpg"
def filename_value(value):
if not 1 <= len(value) <= 255 or not value.strip():
raise invalid("Неверное имя файла")
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in value):
raise invalid("Неверное имя файла")
try:
value.encode("utf-8")
except UnicodeError:
raise invalid("Неверное имя файла") from None
return value
def validate_image(source, media_type):
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
source.seek(0)
with Image.open(source, 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 != media_type:
raise ApiError(415, "unsupported_media_type", "Формат не совпадает с Content-Type")
image.verify()
source.seek(0)
with Image.open(source, formats=["PNG", "JPEG"]) as image:
image.load()
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from None
class Attachments:
def __init__(self, store, objects):
self.store = store
self.objects = objects
self.slots = asyncio.Semaphore(2)
async def receive(self, request, chat_id, filename):
user_id = request.state.user_id
await run_in_threadpool(self.store.chat, user_id, chat_id)
filename = filename_value(filename)
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if media_type not in ("image/png", "image/jpeg"):
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
declared = request.headers.get("Content-Length")
if declared is not None:
if not declared.isascii() or not declared.isdecimal() or len(declared) > 18:
raise invalid("Неверный Content-Length")
if int(declared) > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
try:
await asyncio.wait_for(self.slots.acquire(), timeout=15)
except TimeoutError:
raise ApiError(429, "rate_limited", "Загрузки заняты", {"Retry-After": "1"}) from None
try:
with tempfile.TemporaryFile(mode="w+b") as source:
size, checksum = 0, hashlib.sha256()
try:
with anyio.fail_after(15):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
checksum.update(chunk)
await run_in_threadpool(source.write, chunk)
except (TimeoutError, ClientDisconnect):
raise invalid("Загрузка прервана или слишком медленная") from None
await run_in_threadpool(validate_image, source, media_type)
return await run_in_threadpool(
self.stage, user_id, chat_id, filename, media_type, size, checksum.hexdigest(), source,
)
finally:
self.slots.release()
def stage(self, user_id, chat_id, filename, media_type, size, checksum, source):
attachment_id = uuid4()
key = "originals/" + attachment_id.hex
staging_key = "staging/" + attachment_id.hex
self.objects.put(staging_key, source, size, media_type)
with self.store.connection() as connection:
self.store.require_chat(connection, user_id, chat_id)
row = connection.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING " + FIELDS,
(attachment_id, chat_id, user_id, filename, media_type, size, checksum, key),
).fetchone()
connection.execute(
"INSERT INTO attachment_jobs(id, attachment_id, source_key) VALUES (%s, %s, %s)",
(uuid4(), attachment_id, staging_key),
)
return serialize(row)
def get(self, user_id, attachment_id, internal=False):
with self.store.connection() as connection:
row = connection.execute(
"SELECT " + FIELDS + (",object_key" if internal else "") + " FROM attachments a "
"WHERE a.id=%s AND EXISTS (SELECT 1 FROM chat_members m "
"WHERE m.chat_id=a.chat_id AND m.user_id=%s)", (attachment_id, user_id),
).fetchone()
if not row:
raise not_found()
return row if internal else serialize(row)