Commit 1049dc75 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Link Discovery matches to the library, add universal song+album search

GET /discovery/history now matches each hit against the caller's own
library (title+artist, case-insensitive) and includes library_song_id
when found - computed live on every read rather than persisted, so it
stays correct if the library changes later (a song added after the
hit, or later deleted) instead of going stale like a stored link would.

POST /library/search is now a real universal search: songs (existing
title/artist/genre match) plus albums, a derived (album, artist)
grouping of the caller's own songs - there's no separate Album table,
so an album only appears when it has a name and at least one matching
song. Albums match on album name or artist, not song title, so
searching one track doesn't surface an unrelated album.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent f1ac2f8e
Pipeline #1122 passed with stage
in 5 minutes and 20 seconds
...@@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, s ...@@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, s
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, User from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, LibrarySong, User
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services import storage from src.services import storage
from src.services.music_identification import identify_audio from src.services.music_identification import identify_audio
...@@ -61,6 +61,19 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g ...@@ -61,6 +61,19 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g
finally: finally:
storage.cleanup_temp(temp_path) storage.cleanup_temp(temp_path)
def _library_match_index(db: Session, user_id: int) -> dict[tuple[str, str], int]:
"""(title, artist) -> library_song_id, case/whitespace-insensitive, scoped to one user's
own library. Computed fresh on every call rather than persisted on DiscoveredSong - a
Discovery hit should become playable the moment a matching song exists (even if it was
added to the library after the hit was recorded), and stop being playable if that song is
later deleted, neither of which a stored link would track correctly."""
index: dict[tuple[str, str], int] = {}
for song in db.query(LibrarySong).filter(LibrarySong.user_id == user_id):
if song.title and song.artist:
index[(song.title.strip().lower(), song.artist.strip().lower())] = song.id
return index
@router.get("/history") @router.get("/history")
async def discovery_history(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def discovery_history(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Returns the current user's background listening history for the past 24 hours.""" """Returns the current user's background listening history for the past 24 hours."""
...@@ -71,7 +84,23 @@ async def discovery_history(db: Session = Depends(get_db), current_user: User = ...@@ -71,7 +84,23 @@ async def discovery_history(db: Session = Depends(get_db), current_user: User =
.order_by(DiscoveredSong.detected_at.desc()) .order_by(DiscoveredSong.detected_at.desc())
.all() .all()
) )
return {"status": "success", "history": songs}
library_index = _library_match_index(db, current_user.id)
history = [
{
"id": song.id,
"user_id": song.user_id,
"title": song.title,
"artist": song.artist,
"genre": song.genre,
"coverart": song.coverart,
"detected_at": song.detected_at,
"liked": song.liked,
"library_song_id": library_index.get(((song.title or "").strip().lower(), (song.artist or "").strip().lower())),
}
for song in songs
]
return {"status": "success", "history": history}
@router.post("/{song_id}/swipe") @router.post("/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......
...@@ -47,6 +47,10 @@ async def get_lyrics(file_id: int, db: Session = Depends(get_db), current_user: ...@@ -47,6 +47,10 @@ async def get_lyrics(file_id: int, db: Session = Depends(get_db), current_user:
@router.post("/library/search") @router.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def search_library(query: str = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Universal search across the caller's own library: matching songs, plus matching albums -
there's no separate Album table, an "album" is just a (album, artist) grouping derived from
the songs that share it, so an album only shows up here if it has a name and at least one
matching song."""
q = f"%{query}%" q = f"%{query}%"
songs = db.query(LibrarySong).filter( songs = db.query(LibrarySong).filter(
LibrarySong.user_id == current_user.id, LibrarySong.user_id == current_user.id,
...@@ -54,7 +58,33 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db), ...@@ -54,7 +58,33 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
(LibrarySong.artist.ilike(q)) | (LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q)) (LibrarySong.genre.ilike(q))
).all() ).all()
return {"status": "success", "results": songs}
# Matched by album name or artist - not song title, so searching one song's title doesn't
# surface its whole album (mirrors how Songs/Albums results are separated in most music
# apps: each section matches on its own identifying field).
album_songs = db.query(LibrarySong).filter(
LibrarySong.user_id == current_user.id,
LibrarySong.album.isnot(None),
LibrarySong.album != "",
(LibrarySong.album.ilike(q)) | (LibrarySong.artist.ilike(q)),
).all()
albums_by_key: dict[tuple[str, str], dict] = {}
for song in album_songs:
key = (song.album, song.artist)
entry = albums_by_key.setdefault(key, {
"album": song.album,
"artist": song.artist,
"coverart": None,
"track_count": 0,
"songs": [],
})
entry["track_count"] += 1
entry["songs"].append(song)
if not entry["coverart"] and song.coverart:
entry["coverart"] = song.coverart
return {"status": "success", "songs": songs, "albums": list(albums_by_key.values())}
@router.get("/playlists") @router.get("/playlists")
async def get_playlists(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def get_playlists(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......
import io import io
from src.api.routers import discovery as discovery_router from src.api.routers import discovery as discovery_router
from src.core.database import DiscoveredSong from src.core.database import DiscoveredSong, LibrarySong
def test_discovery_history_requires_auth(client): def test_discovery_history_requires_auth(client):
...@@ -22,6 +22,40 @@ def test_discovery_history_scoped_to_current_user(client, db_session, auth_as): ...@@ -22,6 +22,40 @@ def test_discovery_history_scoped_to_current_user(client, db_session, auth_as):
assert titles == ["Song A"] assert titles == ["Song A"]
def test_discovery_history_links_a_match_already_in_the_library(client, db_session, auth_as):
headers, user = auth_as()
db_session.add(DiscoveredSong(user_id=user.id, title="Song A", artist="Artist A"))
db_session.add(LibrarySong(user_id=user.id, title=" Song A ", artist="ARTIST a", genre="Pop", file_path="/tmp/x.mp3"))
db_session.commit()
response = client.get("/discovery/history", headers=headers)
assert response.status_code == 200
entry = response.json()["history"][0]
assert entry["library_song_id"] is not None
def test_discovery_history_leaves_unmatched_songs_unlinked(client, db_session, auth_as):
headers, user = auth_as()
db_session.add(DiscoveredSong(user_id=user.id, title="Song A", artist="Artist A"))
db_session.commit()
response = client.get("/discovery/history", headers=headers)
assert response.status_code == 200
entry = response.json()["history"][0]
assert entry["library_song_id"] is None
def test_discovery_history_does_not_match_another_users_library(client, db_session, auth_as):
headers_a, user_a = auth_as()
_, user_b = auth_as()
db_session.add(DiscoveredSong(user_id=user_a.id, title="Song A", artist="Artist A"))
db_session.add(LibrarySong(user_id=user_b.id, title="Song A", artist="Artist A", genre="Pop", file_path="/tmp/x.mp3"))
db_session.commit()
response = client.get("/discovery/history", headers=headers_a)
assert response.json()["history"][0]["library_song_id"] is None
def test_discovery_listen_no_file(client, auth_as): def test_discovery_listen_no_file(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.post("/discovery/listen", headers=headers) response = client.post("/discovery/listen", headers=headers)
......
...@@ -56,7 +56,7 @@ def test_library_search_scoped(client, db_session, auth_as): ...@@ -56,7 +56,7 @@ def test_library_search_scoped(client, db_session, auth_as):
response = client.post("/library/search", data={"query": "Ebi"}, headers=headers_a) response = client.post("/library/search", data={"query": "Ebi"}, headers=headers_a)
assert response.status_code == 200 assert response.status_code == 200
assert len(response.json()["results"]) == 1 assert len(response.json()["songs"]) == 1
def test_library_search_finds_match(client, db_session, auth_as): def test_library_search_finds_match(client, db_session, auth_as):
...@@ -65,8 +65,56 @@ def test_library_search_finds_match(client, db_session, auth_as): ...@@ -65,8 +65,56 @@ def test_library_search_finds_match(client, db_session, auth_as):
try: try:
response = client.post("/library/search", data={"query": "Xyzzy"}, headers=headers) response = client.post("/library/search", data={"query": "Xyzzy"}, headers=headers)
assert response.status_code == 200 assert response.status_code == 200
results = response.json()["results"] songs = response.json()["songs"]
assert any(r["id"] == song.id for r in results) assert any(r["id"] == song.id for r in songs)
finally:
os.remove(path)
def test_library_search_groups_matching_songs_into_albums(client, db_session, auth_as):
headers, user = auth_as()
_, path1 = _make_library_song(db_session, user.id, title="Track One", artist="Ebi", album="Greatest Hits", coverart=None)
_, path2 = _make_library_song(db_session, user.id, title="Track Two", artist="Ebi", album="Greatest Hits", coverart="http://example.com/art.jpg")
try:
response = client.post("/library/search", data={"query": "Greatest Hits"}, headers=headers)
assert response.status_code == 200
albums = response.json()["albums"]
assert len(albums) == 1
assert albums[0]["album"] == "Greatest Hits"
assert albums[0]["artist"] == "Ebi"
assert albums[0]["track_count"] == 2
assert albums[0]["coverart"] == "http://example.com/art.jpg"
assert {s["id"] for s in albums[0]["songs"]} == {
s.id for s in db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id)
}
finally:
os.remove(path1)
os.remove(path2)
def test_library_search_album_match_by_artist_not_by_song_title(client, db_session, auth_as):
headers, user = auth_as()
_, path = _make_library_song(db_session, user.id, title="Some Song", artist="Ebi", album="Greatest Hits")
try:
# Searching the artist should surface the album even though the query never appears
# in the album name or the song title.
response = client.post("/library/search", data={"query": "Ebi"}, headers=headers)
albums = response.json()["albums"]
assert any(a["album"] == "Greatest Hits" for a in albums)
# Searching a song title shouldn't surface an unrelated album match.
response = client.post("/library/search", data={"query": "Some Song"}, headers=headers)
assert response.json()["albums"] == []
finally:
os.remove(path)
def test_library_search_ignores_songs_with_no_album(client, db_session, auth_as):
headers, user = auth_as()
_, path = _make_library_song(db_session, user.id, title="Loose Track", artist="Solo Artist", album=None)
try:
response = client.post("/library/search", data={"query": "Solo Artist"}, headers=headers)
assert response.json()["albums"] == []
finally: finally:
os.remove(path) os.remove(path)
......
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