forked from mtusi2026/mtusi2026lab5
88 lines
4.0 KiB
Python
88 lines
4.0 KiB
Python
import os
|
|
import unicodedata
|
|
from uuid import uuid4
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
from sqlalchemy import func, select
|
|
|
|
from .errors import APIError
|
|
from .admission import reserve_capacity
|
|
from .models import Attachment, AttachmentJob, ChatMember
|
|
from .object_storage import BUCKET, PREFIX, s3_client
|
|
from .store import ensure_uuid, serialize, store
|
|
|
|
MAX_BYTES = min(int(os.getenv('MAX_UPLOAD_BYTES', '10485760')), 10485760)
|
|
MAX_PIXELS = min(int(os.getenv('MAX_IMAGE_PIXELS', '40000000')), 40000000)
|
|
if MAX_BYTES < 1 or MAX_PIXELS < 1:
|
|
raise ValueError('Upload limits must be positive')
|
|
|
|
|
|
def validate_filename(filename):
|
|
if (not filename or not filename.strip() or len(filename) > 255
|
|
or any(c in '/\\' or unicodedata.category(c) == 'Cc' for c in filename)):
|
|
raise APIError(400, 'invalid_request', 'Неверное имя файла')
|
|
|
|
|
|
def validate_image(source, content_type):
|
|
try:
|
|
source.seek(0)
|
|
with Image.open(source, formats=['PNG', 'JPEG']) as picture:
|
|
if picture.width * picture.height > MAX_PIXELS:
|
|
raise APIError(413, 'payload_too_large', 'Слишком много пикселей')
|
|
if Image.MIME[picture.format] != content_type:
|
|
raise APIError(415, 'unsupported_media_type', 'Тип изображения не совпадает с Content-Type')
|
|
picture.verify()
|
|
source.seek(0)
|
|
with Image.open(source, formats=['PNG', 'JPEG']) as picture:
|
|
picture.load() # verify alone does not decode JPEG or detect truncated pixel data.
|
|
except Image.DecompressionBombError as exc:
|
|
raise APIError(413, 'payload_too_large', 'Слишком много пикселей') from exc
|
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc:
|
|
raise APIError(415, 'unsupported_media_type', 'Повреждённое изображение') from exc
|
|
source.seek(0)
|
|
|
|
|
|
def lock_object(session, key):
|
|
# Shared by upload and cleanup: no deletion while a COMMIT is in flight.
|
|
session.execute(select(func.pg_advisory_xact_lock(func.hashtextextended(key, 0))))
|
|
|
|
|
|
def metadata(attachment):
|
|
result = serialize(attachment, 'id', 'chat_id', 'owner_id', 'filename',
|
|
'content_type', 'size_bytes', 'sha256', 'created_at',
|
|
'updated_at', 'status', 'error_code')
|
|
return {**result, 'variants': [{k: v for k, v in item.items() if k != 'object_key'}
|
|
for item in attachment.variants]}
|
|
|
|
|
|
def save_attachment(source, chat_id, actor_id, filename, content_type, size, digest):
|
|
validate_image(source, content_type)
|
|
attachment_id = str(uuid4())
|
|
key = PREFIX + attachment_id
|
|
staging_key = 'staging/' + attachment_id
|
|
with store.sessions.begin() as session:
|
|
store._chat(session, chat_id, actor_id)
|
|
reserve_capacity(session)
|
|
lock_object(session, staging_key)
|
|
s3_client().put_object(Bucket=BUCKET, Key=staging_key, Body=source,
|
|
ContentLength=size, ContentType=content_type)
|
|
attachment = Attachment(id=attachment_id, chat_id=chat_id, owner_id=actor_id,
|
|
object_key=key, filename=filename, content_type=content_type,
|
|
size_bytes=size, sha256=digest, staging_key=staging_key)
|
|
session.add(attachment)
|
|
session.flush()
|
|
session.add(AttachmentJob(attachment_id=attachment_id))
|
|
result = metadata(attachment)
|
|
# An uncertain COMMIT is not followed by DELETE: cleanup checks the DB later.
|
|
return result
|
|
|
|
|
|
def get_attachment(attachment_id, actor_id):
|
|
with store.sessions() as session:
|
|
attachment = session.scalar(select(Attachment).join(
|
|
ChatMember, ChatMember.chat_id == Attachment.chat_id).where(
|
|
Attachment.id == ensure_uuid(attachment_id), ChatMember.user_id == actor_id))
|
|
if attachment is None:
|
|
raise APIError(404, 'not_found', 'Объект не найден')
|
|
return attachment
|