59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
import uuid
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from fastapi.responses import Response
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from botocore.exceptions import ClientError
|
|
|
|
from ..outbound.postgres.database import get_db
|
|
from ..outbound.postgres.repositories.translated_article_repository import TranslatedArticleRepository
|
|
from ..outbound.postgres.repositories.adventure_repository import PostgresAdventureEntryAudioRepository
|
|
from ..storage import download_audio
|
|
|
|
router = APIRouter(prefix="/media", tags=["media"])
|
|
|
|
|
|
@router.get("/adventure-audio/{filename:path}")
|
|
async def get_adventure_audio_file(
|
|
filename: str,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> Response:
|
|
try:
|
|
eid = uuid.UUID(filename.rsplit(".", 1)[0])
|
|
except ValueError:
|
|
raise HTTPException(status_code=400, detail="Invalid file ID")
|
|
|
|
print(f"Looking for adventure audio with entry ID: {eid}")
|
|
|
|
adventure_audio = await PostgresAdventureEntryAudioRepository(db).get_for_entry(entry_id=eid, component_type="story_text")
|
|
|
|
if adventure_audio is None:
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
try:
|
|
audio_bytes, content_type = download_audio("adventure-audio/" + filename)
|
|
except ClientError as e:
|
|
if e.response["Error"]["Code"] in ("NoSuchKey", "404"):
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
raise HTTPException(status_code=500, detail="Storage error")
|
|
|
|
return Response(content=audio_bytes, media_type=content_type)
|
|
|
|
@router.get("/{filename:path}")
|
|
async def get_media_file(
|
|
filename: str,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> Response:
|
|
article = await TranslatedArticleRepository(db).get_by_audio_url(filename)
|
|
|
|
if article is None:
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
|
|
try:
|
|
audio_bytes, content_type = download_audio(filename)
|
|
except ClientError as e:
|
|
if e.response["Error"]["Code"] in ("NoSuchKey", "404"):
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
raise HTTPException(status_code=500, detail="Storage error")
|
|
|
|
return Response(content=audio_bytes, media_type=content_type)
|
|
|