"""Authorize metadata and stream originals from the private bucket.""" import logging from uuid import UUID from fastapi import HTTPException from fastapi.responses import StreamingResponse from .attachments import BUCKET, attachment_view, storage from .store import connection logger = logging.getLogger(__name__) def metadata(actor_id: str, attachment_id: UUID) -> dict: with connection() as conn: row = conn.execute( "SELECT a.* FROM attachments a " "JOIN memberships m ON m.chat_id=a.chat_id " "WHERE a.id=%s AND m.user_id=%s", (attachment_id, UUID(actor_id)), ).fetchone() if row is None: raise HTTPException(404) return row def download(actor_id: str, attachment_id: UUID, variant: str) -> StreamingResponse: row = metadata(actor_id, attachment_id) if row["status"] != "ready": raise HTTPException(409) if variant != "original": raise HTTPException(404) try: obj = storage().get_object(BUCKET, row["object_key"]) except Exception as exc: logger.warning("S3 read failed for attachment %s (%s)", attachment_id, type(exc).__name__) raise HTTPException(503) from None def chunks(): try: yield from obj.stream(64 * 1024) finally: obj.close() obj.release_conn() return StreamingResponse( chunks(), media_type=row["content_type"], headers={"Content-Length": str(row["size_bytes"])} ) def get_view(actor_id: str, attachment_id: UUID) -> dict: return attachment_view(metadata(actor_id, attachment_id))