forked from mtusi2026/mtusi2026lab6
Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files. Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
61 lines
2.5 KiB
Python
61 lines
2.5 KiB
Python
from uuid import UUID
|
|
|
|
from messenger.attachments.application.errors import ObjectMissingError
|
|
from messenger.attachments.application.ports import (
|
|
AttachmentDirectory,
|
|
ChatMembership,
|
|
ObjectContent,
|
|
ObjectStorage,
|
|
)
|
|
from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady
|
|
from messenger.attachments.domain.models import Attachment
|
|
from messenger.shared.application.ports import Logger
|
|
|
|
ORIGINAL = "original"
|
|
|
|
|
|
class GetAttachment:
|
|
__slots__ = ("_attachments", "_membership")
|
|
|
|
def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None:
|
|
self._attachments = attachments
|
|
self._membership = membership
|
|
|
|
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
|
|
attachment = await self._attachments.visible(attachment_id)
|
|
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
|
|
raise AttachmentNotFound("вложение не найдено")
|
|
return attachment
|
|
|
|
|
|
class OpenAttachment:
|
|
__slots__ = ("_get", "_logger", "_storage")
|
|
|
|
def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None:
|
|
self._get = get
|
|
self._storage = storage
|
|
self._logger = logger
|
|
|
|
async def __call__(
|
|
self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL
|
|
) -> tuple[str, ObjectContent]:
|
|
attachment = await self._get(attachment_id, user_id)
|
|
if not attachment.ready:
|
|
raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась")
|
|
if variant == ORIGINAL:
|
|
key, content_type = attachment.original_key, attachment.content_type
|
|
else:
|
|
found = attachment.variant(variant)
|
|
if found is None:
|
|
raise AttachmentNotFound("у вложения нет такого варианта")
|
|
key, content_type = found.object_key, found.content_type
|
|
if attachment.quarantine is not None:
|
|
self._logger.warning("attachment.quarantined", attachment_id=str(attachment.id))
|
|
raise AttachmentNotFound("вложение не найдено")
|
|
try:
|
|
content = await self._storage.open(str(key))
|
|
except ObjectMissingError as error:
|
|
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
|
|
raise AttachmentNotFound("вложение не найдено") from error
|
|
return content_type, content
|