"""Authorize metadata and stream versioned variants 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) with connection() as conn: selected = conn.execute( "SELECT object_key,content_type,size_bytes FROM attachment_variants " "WHERE attachment_id=%s AND pipeline_version=%s AND name=%s", (attachment_id, row["pipeline_version"], variant), ).fetchone() if selected is None: raise HTTPException(404) try: obj = storage().get_object(BUCKET, selected["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=selected["content_type"], headers={"Content-Length": str(selected["size_bytes"])} ) def get_view(actor_id: str, attachment_id: UUID) -> dict: row = metadata(actor_id, attachment_id) view = attachment_view(row) if row["status"] == "ready": with connection() as conn: variants = conn.execute( "SELECT name,content_type,size_bytes,width,height,sha256 " "FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s " "AND name <> 'original' ORDER BY name", (attachment_id, row["pipeline_version"]), ).fetchall() view["variants"] = [dict(variant) for variant in variants] return view