Commit cab57b31 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add shared-library search: /library/shared/search + /library/shared/claim

Every library query was scoped to the caller's own songs - there was no
way to search what other users have already tagged. New search endpoint
matches title/artist/genre across every user's library (same matching as
the existing owner-scoped search), deduped by (title, artist) so a song
several users separately uploaded doesn't show up once per owner, and
excludes anything the caller already has by that same identity - the
point is surfacing music that's new to them, not re-offering their own
library back at them.

Claiming a result reuses give_from_shared_library - the exact mechanism
already backing Discovery's "identified something someone else has, give
me a copy" flow - moved out of discovery.py into a new shared services
module so both routers call the same code instead of one importing the
other's private function. Picked up a drive-by fix in the move: it wasn't
copying track_number, so a claimed song silently lost its real album
order.

Also fixed two unrelated pre-existing test collisions surfaced while
adding these tests: the session-scoped test DB (no per-test rollback)
meant test_music.py, test_discovery.py, and this file's own new tests all
used identical "Shared Song"/"Shared Artist"-style literals, and a global
(no user_id) title/artist lookup could resolve to the wrong test's
leftover row depending on run order.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent d7dddc8e
Pipeline #1179 passed with stage
in 23 minutes and 12 seconds
import shutil import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status
from sqlalchemy import func
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
...@@ -8,6 +7,7 @@ from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, LibraryS ...@@ -8,6 +7,7 @@ from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, LibraryS
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
from src.services.shared_library import give_from_shared_library
router = APIRouter(prefix="/discovery", tags=["Music Discovery"]) router = APIRouter(prefix="/discovery", tags=["Music Discovery"])
...@@ -29,56 +29,6 @@ def _check_identify_rate_limit(db: Session, user_id: int): ...@@ -29,56 +29,6 @@ def _check_identify_rate_limit(db: Session, user_id: int):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later") raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later")
def _find_library_match(db: Session, title: str, artist: str, user_id: int | None = None) -> LibrarySong | None:
"""Case/whitespace-insensitive title+artist lookup - scoped to one user's library if
user_id is given, otherwise searched across every user's library (used to find something
to give a caller who doesn't have it themselves yet)."""
query = db.query(LibrarySong).filter(
func.lower(func.trim(LibrarySong.title)) == title.strip().lower(),
func.lower(func.trim(LibrarySong.artist)) == artist.strip().lower(),
)
if user_id is not None:
query = query.filter(LibrarySong.user_id == user_id)
return query.first()
def _give_from_shared_library(db: Session, current_user: User, title: str, artist: str) -> int | None:
"""The app's library is the collective pool of everything every user (including a super
admin seeding popular tracks) has uploaded and tagged - never anything auto-downloaded
from an external source. If a Discovery hit matches a song already sitting in *anyone's*
library and the caller doesn't have their own copy yet, give them one immediately: a new
LibrarySong row of their own (so it shows up in their Library, is playlist-able, etc.),
reusing the same file_path rather than duplicating the audio on disk. Returns the
resulting library_song_id, or None if nobody has this song at all yet."""
if not title or not artist or title == "Unknown" or artist == "Unknown":
return None
own = _find_library_match(db, title, artist, user_id=current_user.id)
if own:
return own.id
source_song = _find_library_match(db, title, artist)
if not source_song:
return None
given = LibrarySong(
user_id=current_user.id,
title=source_song.title,
artist=source_song.artist,
album=source_song.album,
genre=source_song.genre,
coverart=source_song.coverart,
lyrics=source_song.lyrics,
synced_lyrics=source_song.synced_lyrics,
file_path=source_song.file_path,
fingerprint=source_song.fingerprint,
)
db.add(given)
db.commit()
db.refresh(given)
return given.id
@router.post("/listen") @router.post("/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Accepts a short audio snippet from the microphone to identify what's playing.""" """Accepts a short audio snippet from the microphone to identify what's playing."""
...@@ -110,7 +60,7 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g ...@@ -110,7 +60,7 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g
db.commit() db.commit()
db.refresh(new_song) db.refresh(new_song)
library_song_id = _give_from_shared_library(db, current_user, candidate.get("title"), candidate.get("artist")) library_song_id = give_from_shared_library(db, current_user, candidate.get("title"), candidate.get("artist"))
return {"status": "success", "detected": candidate, "discovery_id": new_song.id, "library_song_id": library_song_id} return {"status": "success", "detected": candidate, "discovery_id": new_song.id, "library_song_id": library_song_id}
finally: finally:
......
...@@ -7,6 +7,7 @@ from sqlalchemy.orm import Session ...@@ -7,6 +7,7 @@ from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
from src.core.security import get_current_user, get_current_user_for_stream from src.core.security import get_current_user, get_current_user_for_stream
from src.services.shared_library import give_from_shared_library
router = APIRouter(tags=["Library & Playlists"]) router = APIRouter(tags=["Library & Playlists"])
...@@ -130,6 +131,68 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db), ...@@ -130,6 +131,68 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
return {"status": "success", "songs": songs, "albums": list(albums_by_key.values())} return {"status": "success", "songs": songs, "albums": list(albums_by_key.values())}
@router.post("/library/shared/search")
async def search_shared_library(query: str = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Same matching as /library/search (title/artist/genre), but across every user's library,
not just the caller's - the collective pool described in shared_library.py. Songs only, no
album groupings: an "album" here is a (album, artist) grouping *within one user's own
songs* (see /library/search's own comment), and there's no clean way to merge that across
owners - whose coverart wins, what happens when two owners have different subsets of the
same album's tracks - without a real Album entity this app doesn't have. Deliberately kept
to song-level results rather than taking on that complexity.
Deduped by (title, artist) - the same identity /library/shared/claim below matches on - so
a popular song several different users have all separately uploaded doesn't show up once
per owner. Also excludes anything the caller already owns a copy of (by that same identity,
not just literally their own row) - the point of this search is finding music not yet in
your library, and re-surfacing something you already have here would just be confusing: a
tap on it would silently resolve back to your existing copy instead of adding anything new
(see give_from_shared_library's own "own copy first" check). None of the returned songs can
be streamed directly - each still belongs to whoever owns that particular row, not the
searcher - the frontend calls /library/shared/claim first, same "get your own copy, then
play it" flow Discovery already uses when an identified song turns out to be something
someone else already has."""
q = f"%{query}%"
matches = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
own_keys = {
(s.title.strip().lower(), s.artist.strip().lower())
for s in db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id)
if s.title and s.artist
}
seen: dict[tuple[str, str], LibrarySong] = {}
for song in matches:
if not song.title or not song.artist:
continue
key = (song.title.strip().lower(), song.artist.strip().lower())
if key in own_keys:
continue
seen.setdefault(key, song)
return {"status": "success", "songs": list(seen.values())}
@router.post("/library/shared/claim")
async def claim_shared_song(
title: str = Form(...),
artist: str = Form(...),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Turns a /library/shared/search result into something the caller can actually play: a
real LibrarySong row of their own (or their existing one, if they already have this song),
reusing shared_library.py's give_from_shared_library - the exact mechanism Discovery already
uses for "identified something someone else already has". Never streams another owner's row
directly; every stream endpoint stays scoped to the caller's own library_songs, unchanged."""
library_song_id = give_from_shared_library(db, current_user, title, artist)
if library_song_id is None:
raise HTTPException(status_code=404, detail="That song isn't in the shared library")
return {"status": "success", "library_song_id": library_song_id}
@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)):
playlists = db.query(Playlist).filter(Playlist.user_id == current_user.id).order_by(Playlist.created_at.desc()).all() playlists = db.query(Playlist).filter(Playlist.user_id == current_user.id).order_by(Playlist.created_at.desc()).all()
......
from sqlalchemy import func
from sqlalchemy.orm import Session
from src.core.database import LibrarySong, User
def find_library_match(db: Session, title: str, artist: str, user_id: int | None = None) -> LibrarySong | None:
"""Case/whitespace-insensitive title+artist lookup - scoped to one user's library if
user_id is given, otherwise searched across every user's library."""
query = db.query(LibrarySong).filter(
func.lower(func.trim(LibrarySong.title)) == title.strip().lower(),
func.lower(func.trim(LibrarySong.artist)) == artist.strip().lower(),
)
if user_id is not None:
query = query.filter(LibrarySong.user_id == user_id)
return query.first()
def give_from_shared_library(db: Session, current_user: User, title: str, artist: str) -> int | None:
"""The app's library is the collective pool of everything every user (including a super
admin seeding popular tracks) has uploaded and tagged - never anything auto-downloaded
from an external source. If a match exists in *anyone's* library and the caller doesn't
have their own copy yet, give them one immediately: a new LibrarySong row of their own (so
it shows up in their Library, is playlist-able, etc.), reusing the same file_path rather
than duplicating the audio on disk. Returns the resulting library_song_id, or None if
nobody has this song at all yet.
Originally lived in discovery.py (Discovery's "identify, then give me a copy if someone
already has it" flow) - extracted here once /library/shared/search's "claim" step needed
the exact same behavior, rather than importing a router's private function from another
router or duplicating it."""
if not title or not artist or title == "Unknown" or artist == "Unknown":
return None
own = find_library_match(db, title, artist, user_id=current_user.id)
if own:
return own.id
source_song = find_library_match(db, title, artist)
if not source_song:
return None
given = LibrarySong(
user_id=current_user.id,
title=source_song.title,
artist=source_song.artist,
album=source_song.album,
genre=source_song.genre,
coverart=source_song.coverart,
lyrics=source_song.lyrics,
# Not copied by the original version of this function (before it moved here) - a real
# gap, since it meant a claimed song lost its real track order and sorted to the end of
# its album alongside genuinely unordered tracks (see library.py's _track_sort_key).
track_number=source_song.track_number,
synced_lyrics=source_song.synced_lyrics,
file_path=source_song.file_path,
fingerprint=source_song.fingerprint,
)
db.add(given)
db.commit()
db.refresh(given)
return given.id
...@@ -124,6 +124,119 @@ def test_get_album_requires_auth(client): ...@@ -124,6 +124,119 @@ def test_get_album_requires_auth(client):
assert response.status_code == 401 assert response.status_code == 401
def test_shared_search_requires_auth(client):
response = client.post("/library/shared/search", data={"query": "x"})
assert response.status_code == 401
def test_shared_search_finds_songs_from_other_users(client, db_session, auth_as):
headers, searcher = auth_as()
_, owner = auth_as()
_add_song(db_session, owner.id, title="Zyxarra Greatest Hits", artist="Zyxarra")
response = client.post("/library/shared/search", data={"query": "Zyxarra"}, headers=headers)
assert response.status_code == 200
titles = [s["title"] for s in response.json()["songs"]]
assert "Zyxarra Greatest Hits" in titles
def test_shared_search_dedupes_the_same_song_across_owners(client, db_session, auth_as):
# Title/artist chosen to be unlikely to collide with any other test's fixture data in this
# session-scoped (no per-test rollback) database - see the claim tests below for the same
# reasoning spelled out in more detail.
headers, searcher = auth_as()
_, owner_a = auth_as()
_, owner_b = auth_as()
_add_song(db_session, owner_a.id, title="Quezzlebix Anthem", artist="Quezzlebix")
_add_song(db_session, owner_b.id, title="quezzlebix anthem", artist="QUEZZLEBIX")
response = client.post("/library/shared/search", data={"query": "Quezzlebix"}, headers=headers)
matches = [s for s in response.json()["songs"] if s["title"].lower() == "quezzlebix anthem"]
assert len(matches) == 1
def test_shared_search_excludes_songs_the_searcher_already_owns(client, db_session, auth_as):
# The point of this search is finding music not yet in your own library - a song you
# already have (even a completely separate row someone else owns, matched by the same
# title/artist identity claim uses) shouldn't be re-offered as if it were new. Title/artist
# deliberately unique to this test (see the claim tests further down for why, in the
# session-scoped test DB) - a real collision here caused a false failure once already,
# matching an unrelated (different artist) "Already Mine" row from test_discovery.py.
headers, searcher = auth_as()
_, other_owner = auth_as()
_add_song(db_session, searcher.id, title="Wobblefinch Waltz", artist="Wobblefinch")
_add_song(db_session, other_owner.id, title="wobblefinch waltz", artist="WOBBLEFINCH")
response = client.post("/library/shared/search", data={"query": "Wobblefinch"}, headers=headers)
titles = [s["title"].lower() for s in response.json()["songs"]]
assert "wobblefinch waltz" not in titles
def test_shared_search_returns_no_albums_key_confusion(client, db_session, auth_as):
# Deliberately song-level only (see the endpoint's own docstring for why) - shouldn't
# accidentally echo back an "albums" list shaped like /library/search's.
headers, searcher = auth_as()
response = client.post("/library/shared/search", data={"query": "anything"}, headers=headers)
assert "albums" not in response.json()
def test_claim_shared_song_requires_auth(client):
response = client.post("/library/shared/claim", data={"title": "X", "artist": "Y"})
assert response.status_code == 401
def test_claim_shared_song_gives_own_copy_reusing_the_file(client, db_session, auth_as):
# Title/artist deliberately unique to this test, not the "Shared Song"/"Shared Artist"
# fixture literal test_discovery.py and test_music.py both already use - the test DB here
# is session-scoped with no per-test rollback (see conftest.py), so a reused literal risks
# this test's global (no user_id filter) lookup matching a leftover row from a completely
# different test instead of the one just inserted here.
headers, claimer = auth_as()
_, owner = auth_as()
db_session.add(LibrarySong(
user_id=owner.id, title="Claimable Song Alpha", artist="Claimable Artist Alpha", genre="Pop",
album="Claimable Album", track_number="3/10", file_path="/data/claimable-alpha.mp3", fingerprint="abc123",
))
db_session.commit()
response = client.post(
"/library/shared/claim", data={"title": "Claimable Song Alpha", "artist": "Claimable Artist Alpha"}, headers=headers
)
assert response.status_code == 200
library_song_id = response.json()["library_song_id"]
claimed = db_session.query(LibrarySong).filter(LibrarySong.id == library_song_id).first()
assert claimed.user_id == claimer.id
assert claimed.file_path == "/data/claimable-alpha.mp3" # reused, not duplicated on disk
assert claimed.track_number == "3/10"
def test_claim_shared_song_returns_existing_copy_not_a_duplicate(client, db_session, auth_as):
headers, claimer = auth_as()
_, owner = auth_as()
db_session.add(LibrarySong(user_id=owner.id, title="Claimable Song Beta", artist="Claimable Artist Beta", file_path="/data/x.mp3"))
db_session.commit()
first = client.post(
"/library/shared/claim", data={"title": "Claimable Song Beta", "artist": "Claimable Artist Beta"}, headers=headers
)
second = client.post(
"/library/shared/claim", data={"title": "Claimable Song Beta", "artist": "Claimable Artist Beta"}, headers=headers
)
assert first.json()["library_song_id"] == second.json()["library_song_id"]
owned_count = db_session.query(LibrarySong).filter(
LibrarySong.user_id == claimer.id, LibrarySong.title == "Claimable Song Beta"
).count()
assert owned_count == 1
def test_claim_shared_song_404s_when_nobody_has_it(client, auth_as):
headers, _ = auth_as()
response = client.post("/library/shared/claim", data={"title": "Nobody Has This", "artist": "Nobody"}, headers=headers)
assert response.status_code == 404
def test_get_album_orders_tracks_by_track_number(client, db_session, auth_as): def test_get_album_orders_tracks_by_track_number(client, db_session, auth_as):
headers, user = auth_as() headers, user = auth_as()
paths = [] paths = []
......
...@@ -321,8 +321,14 @@ def test_music_upload_same_fingerprint_different_users_both_get_their_own_song(c ...@@ -321,8 +321,14 @@ def test_music_upload_same_fingerprint_different_users_both_get_their_own_song(c
headers_b, user_b = auth_as() headers_b, user_b = auth_as()
fingerprint = "fp-shared-recording" fingerprint = "fp-shared-recording"
# Title/artist here just needs to exist - this test's own dedup mechanism is fingerprint-
# based, not title/artist matching - but "Shared Song"/"Shared Artist" collided with the
# identical literal test_discovery.py's shared-library test uses, and the session-scoped
# test DB (see conftest.py) keeps rows around across files with no per-test rollback: with
# tests running in the other file order, that test's own global (no user_id) title/artist
# lookup could resolve to this row instead of the one it just inserted.
db_session.add(LibrarySong( db_session.add(LibrarySong(
user_id=user_a.id, title="Shared Song", artist="Shared Artist", album="", genre="", user_id=user_a.id, title="Fingerprinted Song", artist="Fingerprinted Artist", album="", genre="",
coverart=None, lyrics=None, file_path="./var/storage/downloads/a/shared.mp3", fingerprint=fingerprint, coverart=None, lyrics=None, file_path="./var/storage/downloads/a/shared.mp3", fingerprint=fingerprint,
)) ))
db_session.commit() db_session.commit()
......
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