응원가 영구 보존·종료 경기 노출 — 음원 DB 저장 + 경기별 조회 API
- Suno CDN 임시 URL 만료 대비: 완성 곡 첫 트랙을 워커가 다운로드해
song_audio(bytea)로 보존하고 audioUrl을 /api/songs/audio/{id}/{idx}로 재작성
(틱당 5곡, 실패 3회 상한 — 기존 곡도 자동 백필)
- GET /api/songs/match/{match_id} 추가 — 날짜 무관 조회로 종료된 경기
상세에서도 '응원가 듣기' 버튼 노출
- 프론트 getTeamSongTracks를 오늘 전체 캐시 → 경기별 조회·캐시로 전환
- 음원 서빙은 Range(206) 지원, immutable 캐시 + task_id 캐시버스터
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bc333d64f4
commit
fdb04a2ccc
5 files changed
+186
-26
No files matched your search
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
@@ -10,8 +11,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..models import Match, Song
|
||||
from ..services.songs import poll_generating, start_due_songs
|
||||
from ..models import Match, Song, SongAudio
|
||||
from ..services.songs import persist_audio, poll_generating, start_due_songs
|
||||
from .admin import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/songs", tags=["songs"])
|
||||
@@ -143,6 +144,67 @@ async def today_songs(league: str = "", db: AsyncSession = Depends(get_db)) -> l
|
||||
return [_song_out(s) for s in rows if s.tracks]
|
||||
|
||||
|
||||
@router.get("/match/{match_id}")
|
||||
async def match_songs(match_id: str, db: AsyncSession = Depends(get_db)) -> list[dict]:
|
||||
"""경기별 응원가 — 날짜 무관. 종료된 경기 상세에서도 그날 곡을 노출한다."""
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Song)
|
||||
.where(
|
||||
Song.match_id == match_id,
|
||||
Song.status.in_(("complete", "generating")),
|
||||
)
|
||||
.order_by(Song.team_code)
|
||||
)
|
||||
).scalars().all()
|
||||
return [_song_out(s) for s in rows if s.tracks]
|
||||
|
||||
|
||||
@router.get("/audio/{song_id}/{track_idx}")
|
||||
async def song_audio_bytes(
|
||||
song_id: int,
|
||||
track_idx: int,
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> Response:
|
||||
"""DB 보존 음원 서빙 — Range 지원(재생 위치 탐색용). v= 쿼리로 캐시버스트."""
|
||||
row = (
|
||||
await db.execute(
|
||||
select(SongAudio).where(
|
||||
SongAudio.song_id == song_id, SongAudio.track_idx == track_idx
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="AUDIO_NOT_FOUND")
|
||||
data, total = row.data, len(row.data)
|
||||
headers = {
|
||||
"Accept-Ranges": "bytes",
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
}
|
||||
m = re.fullmatch(r"bytes=(\d*)-(\d*)", request.headers.get("range") or "")
|
||||
if m and (m.group(1) or m.group(2)):
|
||||
if m.group(1):
|
||||
start = int(m.group(1))
|
||||
end = int(m.group(2)) if m.group(2) else total - 1
|
||||
else: # suffix range: bytes=-N (마지막 N바이트)
|
||||
start = max(0, total - int(m.group(2)))
|
||||
end = total - 1
|
||||
if start >= total or start > end:
|
||||
return Response(
|
||||
status_code=416, headers={"Content-Range": f"bytes */{total}"}
|
||||
)
|
||||
end = min(end, total - 1)
|
||||
headers["Content-Range"] = f"bytes {start}-{end}/{total}"
|
||||
return Response(
|
||||
content=data[start : end + 1],
|
||||
status_code=206,
|
||||
media_type=row.mime,
|
||||
headers=headers,
|
||||
)
|
||||
return Response(content=data, media_type=row.mime, headers=headers)
|
||||
|
||||
|
||||
@router.post("/callback")
|
||||
async def suno_callback(request: Request) -> dict:
|
||||
"""Suno 게이트웨이 callBackUrl 싱크대 — 완료 감지는 워커 폴링이 담당."""
|
||||
@@ -158,4 +220,5 @@ async def force_generate(db: AsyncSession = Depends(get_db)) -> dict:
|
||||
"""관리자: 오늘 KBO 전 경기 응원가 즉시 생성 시작 + 폴링 1회."""
|
||||
started = await start_due_songs(db, force_today=True)
|
||||
done = await poll_generating(db)
|
||||
return {"ok": True, "started": started, "completed": done}
|
||||
saved = await persist_audio(db)
|
||||
return {"ok": True, "started": started, "completed": done, "persisted": saved}
|
||||
Reference in new issue
Block a user