from dataclasses import dataclass, field from datetime import datetime from enum import StrEnum from uuid import UUID from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentStored from messenger.attachments.domain.values import Filename, ImageInfo from messenger.shared.domain.events import DomainEvent OBJECT_PREFIX = "attachments/" class AttachmentStatus(StrEnum): PENDING = "pending" READY = "ready" class Quarantine(StrEnum): MISSING = "missing" SIZE_MISMATCH = "size_mismatch" SHA_MISMATCH = "sha_mismatch" @dataclass(slots=True) class Attachment: id: UUID chat_id: UUID owner_id: UUID filename: Filename image: ImageInfo size_bytes: int sha256: str object_key: str status: AttachmentStatus created_at: datetime updated_at: datetime quarantine: Quarantine | None = None _events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False) @classmethod def stage( cls, *, attachment_id: UUID, chat_id: UUID, owner_id: UUID, filename: Filename, image: ImageInfo, size_bytes: int, sha256: str, now: datetime, ) -> Attachment: return cls( id=attachment_id, chat_id=chat_id, owner_id=owner_id, filename=filename, image=image, size_bytes=size_bytes, sha256=sha256, object_key=f"{OBJECT_PREFIX}{attachment_id}", status=AttachmentStatus.PENDING, created_at=now, updated_at=now, ) @property def content_type(self) -> str: return self.image.kind.value def store(self, now: datetime) -> None: self.status = AttachmentStatus.READY self.updated_at = max(now, self.created_at) self._events.append( AttachmentStored( attachment_id=self.id, chat_id=self.chat_id, owner_id=self.owner_id, size_bytes=self.size_bytes, ) ) def discard(self, reason: str) -> None: self._events.append( AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason) ) def isolate(self, reason: Quarantine) -> None: if self.status is AttachmentStatus.READY: self.quarantine = reason def release(self) -> None: self.quarantine = None def collect_events(self) -> list[DomainEvent]: events, self._events = self._events, [] return events