Commit 12603c89 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Persist track_number on LibrarySong, add GET /library/album

identify_audio() (and the IdentifiedTrack cache) always computed a
track number, but LibrarySong had no column to store it in - so an
album's tracks had no real order to sort by anywhere they were shown.
Adds the column (+ migration), persists it in _identify_tag_and_store,
and adds GET /library/album?album=&artist= which returns one album's
songs sorted by it (numberless tracks last, then alphabetically) for
the frontend's new dedicated album detail page.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9c657b0a
Pipeline #1161 failed with stage
in 15 minutes and 55 seconds
"""add track_number to library_songs
Revision ID: 4e6ef348478e
Revises: 4551428f6b16
Create Date: 2026-09-01 21:49:29.106273
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '4e6ef348478e'
down_revision: Union[str, Sequence[str], None] = '4551428f6b16'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# Autogenerate also proposed a remix_jobs.user_id foreign key here - unrelated pre-existing
# model/DB drift, not something to fold into this migration blind. Left alone.
op.add_column('library_songs', sa.Column('track_number', sa.String(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('library_songs', 'track_number')
......@@ -18,6 +18,45 @@ async def get_library(db: Session = Depends(get_db), current_user: User = Depend
songs = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs}
def _track_sort_key(song: LibrarySong):
"""Real track order when we have it (parsed from track_number's "N/total" - only the
numerator matters for ordering), title A-Z as the tiebreak/fallback for songs identified
before this column existed or where identification found no track number at all. A large
sentinel (not raising/skipping) pushes those to the end rather than scattering them
unpredictably among the numbered ones."""
try:
num = int((song.track_number or '').split('/')[0])
except ValueError:
num = 10**9
return (num, (song.title or '').lower())
@router.get("/library/album")
async def get_album(
album: str,
artist: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""A single (album, artist) grouping's tracks, in real track order - the caller's own
library only, same scoping as everything else here. There's no separate Album entity (see
/library/search's own comment on this), so "the album" is just whichever of the caller's
songs currently share this exact (album, artist) pair."""
songs = db.query(LibrarySong).filter(
LibrarySong.user_id == current_user.id,
LibrarySong.album == album,
LibrarySong.artist == artist,
).all()
if not songs:
raise HTTPException(status_code=404, detail="Album not found")
songs.sort(key=_track_sort_key)
coverart = next((s.coverart for s in songs if s.coverart), None)
return {
"status": "success",
"album": {"album": album, "artist": artist, "coverart": coverart, "track_count": len(songs), "songs": songs},
}
@router.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
......
......@@ -173,6 +173,10 @@ async def _identify_tag_and_store(
coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''),
synced_lyrics=json.dumps(candidate['synced_lyrics']) if candidate.get('synced_lyrics') else None,
# "N/total" from identification (or the IdentifiedTrack cache, which already carries
# it through unchanged) - was computed all along but never made it onto this row
# until now, which is what let an album's tracks show in no particular order.
track_number=candidate.get('track_number'),
file_path=final_path,
fingerprint=fingerprint,
)
......
......@@ -99,6 +99,12 @@ class LibrarySong(Base):
genre = Column(String)
coverart = Column(String)
lyrics = Column(String)
# "N/total" from identification (Shazam, or MusicBrainz's release-list for AcoustID hits) -
# already computed and cached on IdentifiedTrack, but wasn't being copied onto the actual
# per-user row here, so an album's tracks had no real ordering to sort by. Nullable since
# older rows (identified before this column existed) and unmatched identifications won't
# have one.
track_number = Column(String, nullable=True)
# JSON-encoded [[seconds, text], ...], line-level LRC timing - null when no synced source
# was found (plain `lyrics` above still works as the static fallback either way).
synced_lyrics = Column(String, nullable=True)
......
......@@ -119,6 +119,89 @@ def test_library_search_ignores_songs_with_no_album(client, db_session, auth_as)
os.remove(path)
def test_get_album_requires_auth(client):
response = client.get("/library/album", params={"album": "X", "artist": "Y"})
assert response.status_code == 401
def test_get_album_orders_tracks_by_track_number(client, db_session, auth_as):
headers, user = auth_as()
paths = []
try:
# Deliberately created out of order, so a passing test can't be an accident of
# insertion/id order - only the real sort key.
_, p1 = _make_library_song(db_session, user.id, title="Third", artist="Ebi", album="Greatest Hits", track_number="3/5")
_, p2 = _make_library_song(db_session, user.id, title="First", artist="Ebi", album="Greatest Hits", track_number="1/5")
_, p3 = _make_library_song(db_session, user.id, title="Second", artist="Ebi", album="Greatest Hits", track_number="2/5")
paths = [p1, p2, p3]
response = client.get("/library/album", params={"album": "Greatest Hits", "artist": "Ebi"}, headers=headers)
assert response.status_code == 200
body = response.json()["album"]
assert body["album"] == "Greatest Hits"
assert body["artist"] == "Ebi"
assert body["track_count"] == 3
assert [s["title"] for s in body["songs"]] == ["First", "Second", "Third"]
finally:
for p in paths:
os.remove(p)
def test_get_album_puts_songs_with_no_track_number_last_then_sorts_by_title(client, db_session, auth_as):
headers, user = auth_as()
paths = []
try:
_, p1 = _make_library_song(db_session, user.id, title="Zeta (no number)", artist="Ebi", album="Mixed", track_number=None)
_, p2 = _make_library_song(db_session, user.id, title="Alpha (no number)", artist="Ebi", album="Mixed", track_number=None)
_, p3 = _make_library_song(db_session, user.id, title="Has Number", artist="Ebi", album="Mixed", track_number="1/2")
paths = [p1, p2, p3]
response = client.get("/library/album", params={"album": "Mixed", "artist": "Ebi"}, headers=headers)
titles = [s["title"] for s in response.json()["album"]["songs"]]
assert titles == ["Has Number", "Alpha (no number)", "Zeta (no number)"]
finally:
for p in paths:
os.remove(p)
def test_get_album_scoped_to_current_user(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
paths = []
try:
_, pa = _make_library_song(db_session, user_a.id, title="A's Song", artist="Ebi", album="Greatest Hits")
_, pb = _make_library_song(db_session, user_b.id, title="B's Song", artist="Ebi", album="Greatest Hits")
paths = [pa, pb]
response = client.get("/library/album", params={"album": "Greatest Hits", "artist": "Ebi"}, headers=headers_a)
titles = [s["title"] for s in response.json()["album"]["songs"]]
assert titles == ["A's Song"]
finally:
for p in paths:
os.remove(p)
def test_get_album_404_for_no_matching_songs(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/album", params={"album": "Nonexistent", "artist": "Nobody"}, headers=headers)
assert response.status_code == 404
def test_get_album_uses_first_available_coverart(client, db_session, auth_as):
headers, user = auth_as()
paths = []
try:
_, p1 = _make_library_song(db_session, user.id, title="No Art", artist="Ebi", album="Greatest Hits", track_number="1/2", coverart=None)
_, p2 = _make_library_song(db_session, user.id, title="Has Art", artist="Ebi", album="Greatest Hits", track_number="2/2", coverart="http://example.com/art.jpg")
paths = [p1, p2]
response = client.get("/library/album", params={"album": "Greatest Hits", "artist": "Ebi"}, headers=headers)
assert response.json()["album"]["coverart"] == "http://example.com/art.jpg"
finally:
for p in paths:
os.remove(p)
def test_library_stream_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
......
......@@ -102,6 +102,29 @@ def test_music_upload_success_creates_library_song(client, db_session, auth_as,
assert song.artist == "Test Artist"
def test_music_upload_persists_track_number(client, db_session, auth_as, mocker):
"""Regression: identify_audio (and the IdentifiedTrack cache) always computed a track_number,
but LibrarySong never had a column to store it in, so an album's tracks had no real order to
sort by. FAKE_CANDIDATE (used by _mock_pipeline) has no track_number at all - this test
supplies one explicitly to check it actually lands on the row."""
headers, user = auth_as()
_mock_pipeline(mocker)
mocker.patch(
"src.api.routers.music.identify_audio",
return_value=[{**FAKE_CANDIDATE, "track_number": "3/12"}],
)
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.track_number == "3/12"
def test_music_upload_persists_synced_lyrics(client, db_session, auth_as, mocker):
headers, user = auth_as()
candidate_without_lyrics = {**FAKE_CANDIDATE, "lyrics": None}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment