forked from mtusi2026/mtusi2026lab4
94 lines
2.9 KiB
Python
94 lines
2.9 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
|
|
|
from ..domain.models import Attachment
|
|
from ..models.attachment import AttachmentRow
|
|
from ..models.chat import ChatMemberRow, ChatRow
|
|
|
|
|
|
class AttachmentRepository:
|
|
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
|
self._sessions = sessions
|
|
|
|
@staticmethod
|
|
def _to_domain(row: AttachmentRow) -> Attachment:
|
|
return Attachment(
|
|
id=row.id,
|
|
chat_id=row.chat_id,
|
|
owner_id=row.owner_id,
|
|
filename=row.filename,
|
|
object_key=row.object_key,
|
|
content_type=row.content_type,
|
|
size_bytes=row.size_bytes,
|
|
sha256=row.sha256,
|
|
width=row.width,
|
|
height=row.height,
|
|
status=row.status,
|
|
error_code=row.error_code,
|
|
created_at=row.created_at,
|
|
updated_at=row.updated_at,
|
|
)
|
|
|
|
async def chat_exists_for_member(self, chat_id: UUID, user_id: UUID) -> bool:
|
|
async with self._sessions() as session:
|
|
found = await session.scalar(
|
|
select(ChatRow.id)
|
|
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
|
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
|
|
)
|
|
return found is not None
|
|
|
|
async def create(
|
|
self,
|
|
*,
|
|
attachment_id: UUID,
|
|
chat_id: UUID,
|
|
owner_id: UUID,
|
|
filename: str,
|
|
object_key: str,
|
|
content_type: str,
|
|
size_bytes: int,
|
|
sha256: str,
|
|
width: int,
|
|
height: int,
|
|
now: datetime,
|
|
) -> Attachment:
|
|
row = AttachmentRow(
|
|
id=attachment_id,
|
|
chat_id=chat_id,
|
|
owner_id=owner_id,
|
|
filename=filename,
|
|
object_key=object_key,
|
|
content_type=content_type,
|
|
size_bytes=size_bytes,
|
|
sha256=sha256,
|
|
width=width,
|
|
height=height,
|
|
status='ready',
|
|
error_code=None,
|
|
created_at=now,
|
|
updated_at=now,
|
|
)
|
|
async with self._sessions() as session:
|
|
async with session.begin():
|
|
session.add(row)
|
|
await session.flush()
|
|
return self._to_domain(row)
|
|
|
|
async def get_for_member(self, attachment_id: UUID, user_id: UUID) -> Attachment | None:
|
|
async with self._sessions() as session:
|
|
row = await session.scalar(
|
|
select(AttachmentRow)
|
|
.join(ChatMemberRow, ChatMemberRow.chat_id == AttachmentRow.chat_id)
|
|
.where(
|
|
AttachmentRow.id == attachment_id,
|
|
ChatMemberRow.user_id == user_id,
|
|
)
|
|
)
|
|
return self._to_domain(row) if row is not None else None
|