language-learning-app/api/app/routers/media.py
2026-05-18 21:18:19 +01:00

61 lines
2.3 KiB
Python

import uuid
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import Response
from sqlalchemy.ext.asyncio import AsyncSession
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 ..outbound.storage_client import get_storage_client
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")
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 = get_storage_client().download("adventure-audio/" + filename)
except FileNotFoundError:
raise HTTPException(status_code=404, detail="File not found")
except NotImplementedError:
raise HTTPException(status_code=501, detail="Media proxy not available with current storage provider")
except Exception:
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 = get_storage_client().download(filename)
except FileNotFoundError:
raise HTTPException(status_code=404, detail="File not found")
except NotImplementedError:
raise HTTPException(status_code=501, detail="Media proxy not available with current storage provider")
except Exception:
raise HTTPException(status_code=500, detail="Storage error")
return Response(content=audio_bytes, media_type=content_type)