import uuid from sqlalchemy import select from sqlalchemy.orm import Session from models import Attachment, ChatMember def object_key_for(attachment_id: uuid.UUID) -> str: # Ключ назначает сервер: случайный UUID, без имени файла и без данных пользователя. return f"originals/{attachment_id}" def create_attachment(db: Session, attachment_id: uuid.UUID, chat_id: uuid.UUID, owner_id: uuid.UUID, filename: str, content_type: str, size_bytes: int, sha256: str, object_key: str) -> Attachment: attachment = Attachment( id=attachment_id, chat_id=chat_id, owner_id=owner_id, filename=filename, content_type=content_type, size_bytes=size_bytes, sha256=sha256, object_key=object_key, ) db.add(attachment) db.commit() return attachment def get_member_attachment(db: Session, attachment_id: uuid.UUID, user_id: uuid.UUID) -> Attachment | None: """Вложение, если пользователь — участник его чата. Чужое и несуществующее неразличимы (None -> 404).""" query = ( select(Attachment) .join(ChatMember, ChatMember.chat_id == Attachment.chat_id) .where(Attachment.id == attachment_id, ChatMember.user_id == user_id) ) return db.scalar(query) def find_chat_attachments(db: Session, chat_id: uuid.UUID, attachment_ids: list[uuid.UUID]) -> list[Attachment]: # Вложения других чатов сюда не попадают: для отправителя они «не найдены». if not attachment_ids: return [] # FOR KEY SHARE: пока сообщение со ссылкой не закоммичено, сверка хранилищ не может удалить эти строки # (её DELETE ждёт, а потом откажет по FK); если сверка удалила раньше — вложение просто «не найдено». query = (select(Attachment) .where(Attachment.chat_id == chat_id, Attachment.id.in_(attachment_ids)) .with_for_update(key_share=True, read=True)) return list(db.scalars(query))