응원가 영구 보존·종료 경기 노출 — 음원 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
@@ -21,7 +21,7 @@ from sqlalchemy import select
|
||||
from ..config import settings
|
||||
from ..database import SessionLocal
|
||||
from ..domain import ensure_aware, now_utc
|
||||
from ..models import DataCache, Match, Song
|
||||
from ..models import DataCache, Match, Song, SongAudio
|
||||
from . import suno
|
||||
|
||||
log = logging.getLogger("triplepick.songs")
|
||||
@@ -758,8 +758,76 @@ async def poll_generating(db) -> int:
|
||||
return done
|
||||
|
||||
|
||||
PERSIST_MAX_FAILS = 3 # 트랙별 다운로드 실패 상한 (만료 URL 무한 재시도 방지)
|
||||
PERSIST_PER_TICK = 5 # 틱당 다운로드 곡 수 상한 — 틱 지연 방지
|
||||
|
||||
|
||||
async def persist_audio(db, limit: int = PERSIST_PER_TICK) -> int:
|
||||
"""완성 곡의 노출 트랙(첫 트랙) 음원을 DB(SongAudio)로 보존.
|
||||
|
||||
Suno CDN URL 은 임시라 종료된 경기의 응원가도 계속 재생하려면 원본을
|
||||
내려받아야 한다. audioUrl 이 아직 원격(http)인 complete 곡을 골라
|
||||
다운로드 → SongAudio 교체 저장 → audioUrl 을 자체 경로로 재작성.
|
||||
업그레이드로 트랙이 원격 URL 로 갈리면 자동으로 다시 저장된다.
|
||||
"""
|
||||
import httpx
|
||||
|
||||
rows = (
|
||||
await db.execute(select(Song).where(Song.status == "complete"))
|
||||
).scalars().all()
|
||||
todo = []
|
||||
for row in rows:
|
||||
t = (row.tracks or [None])[0]
|
||||
if not t or not (t.get("audioUrl") or "").startswith("http"):
|
||||
continue
|
||||
if (t.get("persistFails") or 0) >= PERSIST_MAX_FAILS:
|
||||
continue
|
||||
todo.append(row)
|
||||
saved = 0
|
||||
for row in todo[:limit]:
|
||||
t = dict(row.tracks[0])
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=90, follow_redirects=True) as c:
|
||||
r = await c.get(t["audioUrl"])
|
||||
r.raise_for_status()
|
||||
body = r.content
|
||||
if not body:
|
||||
raise ValueError("빈 응답")
|
||||
mime = (r.headers.get("content-type") or "audio/mpeg").split(";")[0]
|
||||
except Exception as e: # noqa: BLE001
|
||||
t["persistFails"] = (t.get("persistFails") or 0) + 1
|
||||
row.tracks = [t, *row.tracks[1:]]
|
||||
await db.commit()
|
||||
log.warning(
|
||||
"song 음원 보존 실패 %s %s (%d회): %s",
|
||||
row.match_id, row.team_code, t["persistFails"], e,
|
||||
)
|
||||
continue
|
||||
existing = (
|
||||
await db.execute(
|
||||
select(SongAudio).where(
|
||||
SongAudio.song_id == row.id, SongAudio.track_idx == 0
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if existing:
|
||||
await db.delete(existing)
|
||||
await db.flush()
|
||||
db.add(SongAudio(song_id=row.id, track_idx=0, mime=mime, size=len(body), data=body))
|
||||
t["sourceUrl"] = t["audioUrl"]
|
||||
t["audioUrl"] = f"/api/songs/audio/{row.id}/0?v={(row.task_id or '')[:8]}"
|
||||
t.pop("persistFails", None)
|
||||
row.tracks = [t, *row.tracks[1:]]
|
||||
await db.commit()
|
||||
saved += 1
|
||||
log.info(
|
||||
"song 음원 보존: %s %s (%.1fMB)", row.match_id, row.team_code, len(body) / 1e6
|
||||
)
|
||||
return saved
|
||||
|
||||
|
||||
async def tick_songs() -> None:
|
||||
"""워커 주기 작업 — 생성 시작 + 폴링. 미설정 시 no-op."""
|
||||
"""워커 주기 작업 — 생성 시작 + 폴링 + 음원 보존. 미설정 시 no-op."""
|
||||
if not _enabled():
|
||||
return
|
||||
async with SessionLocal() as db:
|
||||
@@ -771,3 +839,7 @@ async def tick_songs() -> None:
|
||||
await poll_generating(db)
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.error("song poll 오류: %s", e)
|
||||
try:
|
||||
await persist_audio(db)
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.error("song 음원 보존 오류: %s", e)
|
||||
Reference in new issue
Block a user