feat(lyrics): LRCLIB provider + cached lyrics endpoints (§6.7)
GET /tracks/{id}/lyrics (get-or-fetch, caches found/not_found with a 7-day
miss TTL) and POST /tracks/{id}/lyrics/refetch (force). Hexagonal wiring:
LyricsProvider/LyricsRepository ports, LrclibHttpClient adapter (keyless,
degrades to not_found on error), SqlAlchemyLyricsRepository (upsert on the
existing lyrics table), LyricsService, LyricsOut schema, deps.py factory.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ from app.infrastructure.db.repositories.download_job_repository import (
|
||||
)
|
||||
from app.infrastructure.db.repositories.history_repository import SqlAlchemyHistoryRepository
|
||||
from app.infrastructure.db.repositories.like_repository import SqlAlchemyLikeRepository
|
||||
from app.infrastructure.db.repositories.lyrics_repository import SqlAlchemyLyricsRepository
|
||||
from app.infrastructure.db.repositories.playlist_repository import SqlAlchemyPlaylistRepository
|
||||
from app.infrastructure.db.repositories.refresh_token_repository import (
|
||||
SqlAlchemyRefreshTokenRepository,
|
||||
@@ -23,6 +24,7 @@ __all__ = [
|
||||
"SqlAlchemyDownloadJobRepository",
|
||||
"SqlAlchemyHistoryRepository",
|
||||
"SqlAlchemyLikeRepository",
|
||||
"SqlAlchemyLyricsRepository",
|
||||
"SqlAlchemyPlaylistRepository",
|
||||
"SqlAlchemyRefreshTokenRepository",
|
||||
"SqlAlchemyTrackRepository",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Lyrics repository — adapter over ``AsyncSession``.
|
||||
|
||||
One cached row per track (``track_id`` unique). ``upsert`` refreshes the row and
|
||||
bumps ``fetched_at`` so the service's TTL is measured from the last fetch.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.domain.entities.lyrics import Lyrics
|
||||
from app.infrastructure.db.models.lyrics import LyricsModel
|
||||
|
||||
|
||||
def _to_entity(row: LyricsModel) -> Lyrics:
|
||||
return Lyrics(
|
||||
track_id=row.track_id,
|
||||
synced=row.synced,
|
||||
plain=row.plain,
|
||||
source=row.source,
|
||||
status=row.status,
|
||||
fetched_at=row.fetched_at,
|
||||
)
|
||||
|
||||
|
||||
class SqlAlchemyLyricsRepository:
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def get(self, track_id: uuid.UUID) -> Lyrics | None:
|
||||
row = await self._session.scalar(
|
||||
select(LyricsModel).where(LyricsModel.track_id == track_id)
|
||||
)
|
||||
return _to_entity(row) if row is not None else None
|
||||
|
||||
async def upsert(
|
||||
self,
|
||||
*,
|
||||
track_id: uuid.UUID,
|
||||
synced: str | None,
|
||||
plain: str | None,
|
||||
source: str | None,
|
||||
status: str,
|
||||
) -> Lyrics:
|
||||
values = {
|
||||
"track_id": track_id,
|
||||
"synced": synced,
|
||||
"plain": plain,
|
||||
"source": source,
|
||||
"status": status,
|
||||
"fetched_at": func.now(),
|
||||
}
|
||||
stmt = (
|
||||
pg_insert(LyricsModel)
|
||||
.values(**values)
|
||||
.on_conflict_do_update(
|
||||
index_elements=[LyricsModel.track_id],
|
||||
set_={
|
||||
"synced": synced,
|
||||
"plain": plain,
|
||||
"source": source,
|
||||
"status": status,
|
||||
"fetched_at": func.now(),
|
||||
},
|
||||
)
|
||||
.returning(LyricsModel)
|
||||
)
|
||||
row = (await self._session.scalars(stmt)).one()
|
||||
await self._session.flush()
|
||||
return _to_entity(row)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""LrclibHttpClient — fetches lyrics from LRCLIB (plan §6.7).
|
||||
|
||||
LRCLIB is a free, keyless lyrics database. ``/api/get`` does an exact match on
|
||||
artist+track+album+duration; if that misses we fall back to ``/api/search`` and
|
||||
take the best-scoring hit. Graceful degradation: any network/parse error →
|
||||
``fetch`` returns ``None`` (the service then caches a ``not_found``), never
|
||||
raising. No API key is needed, so this provider is always "available".
|
||||
"""
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.domain.entities.lyrics import LyricsResult
|
||||
|
||||
log = get_logger(__name__)
|
||||
|
||||
_BASE_URL = "https://lrclib.net"
|
||||
_TIMEOUT_SECONDS = 10.0
|
||||
_SOURCE = "lrclib"
|
||||
|
||||
|
||||
class LrclibHttpClient:
|
||||
"""Implements :class:`app.domain.ports.LyricsProvider`."""
|
||||
|
||||
def __init__(self, *, user_agent: str, base_url: str = _BASE_URL) -> None:
|
||||
self._user_agent = user_agent
|
||||
self._base_url = base_url.rstrip("/")
|
||||
|
||||
async def fetch(
|
||||
self,
|
||||
*,
|
||||
artist: str,
|
||||
title: str,
|
||||
album: str | None,
|
||||
duration_seconds: int | None,
|
||||
) -> LyricsResult | None:
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=_TIMEOUT_SECONDS,
|
||||
headers={"User-Agent": self._user_agent},
|
||||
base_url=self._base_url,
|
||||
) as client:
|
||||
hit = await self._get(client, artist, title, album, duration_seconds)
|
||||
if hit is None:
|
||||
hit = await self._search(client, artist, title)
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
log.warning("lrclib.fetch_failed", error=str(exc))
|
||||
return None
|
||||
return hit
|
||||
|
||||
async def _get(
|
||||
self,
|
||||
client: httpx.AsyncClient,
|
||||
artist: str,
|
||||
title: str,
|
||||
album: str | None,
|
||||
duration_seconds: int | None,
|
||||
) -> LyricsResult | None:
|
||||
"""Exact match via ``/api/get`` (404 when nothing matches exactly)."""
|
||||
params = {"artist_name": artist, "track_name": title}
|
||||
if album:
|
||||
params["album_name"] = album
|
||||
if duration_seconds is not None:
|
||||
params["duration"] = str(duration_seconds)
|
||||
resp = await client.get("/api/get", params=params)
|
||||
if resp.status_code == httpx.codes.NOT_FOUND:
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
return _to_result(resp.json())
|
||||
|
||||
async def _search(
|
||||
self, client: httpx.AsyncClient, artist: str, title: str
|
||||
) -> LyricsResult | None:
|
||||
"""Fuzzy fallback via ``/api/search`` — take the first usable hit."""
|
||||
resp = await client.get(
|
||||
"/api/search", params={"artist_name": artist, "track_name": title}
|
||||
)
|
||||
resp.raise_for_status()
|
||||
results = resp.json()
|
||||
if not isinstance(results, list):
|
||||
return None
|
||||
for item in results:
|
||||
result = _to_result(item)
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
def _to_result(payload: object) -> LyricsResult | None:
|
||||
"""Map an LRCLIB record to a ``LyricsResult``. Instrumental tracks and empty
|
||||
records yield ``None`` (nothing worth caching as "found")."""
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
if payload.get("instrumental"):
|
||||
return None
|
||||
synced = payload.get("syncedLyrics") or None
|
||||
plain = payload.get("plainLyrics") or None
|
||||
if synced is None and plain is None:
|
||||
return None
|
||||
return LyricsResult(synced=synced, plain=plain, source=_SOURCE)
|
||||
Reference in New Issue
Block a user