Commit 44617a06 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Home feed: dedupe songs/albums across uploaders, drop uploader attribution

Every section (New Songs, New Albums, Suggestions) is now deduped by
(title, artist)/(album, artist) identity - the same song or album tagged by
several different users used to eat one display slot per uploader, now
shows once. Albums merge across uploaders by picking a single
representative copy (the caller's own if they have one, so the card still
navigates directly instead of needing a claim; otherwise the most recent) -
never literally merging different people's track data together.

No uploader identity (username) is attached to any global-feed entry
anymore - the feed reads as one shared pool of music. New `is_liked` field
lets the frontend show a real favorite heart on Home rows; the helper that
computes it (liked_song_ids) moved out of library.py into
services/favorites.py so home.py can reuse it without importing another
router's private function, same reasoning give_from_shared_library was
already split out for.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 1bf26cb9
Pipeline #1212 failed with stage
in 15 minutes and 1 second
This diff is collapsed.
...@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session ...@@ -10,6 +10,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 from src.services.shared_library import give_from_shared_library
from src.services.favorites import liked_song_ids
router = APIRouter(tags=["Library & Playlists"]) router = APIRouter(tags=["Library & Playlists"])
...@@ -95,23 +96,6 @@ def _fuzzy_match_songs(candidates: list[LibrarySong], query: str, threshold: flo ...@@ -95,23 +96,6 @@ def _fuzzy_match_songs(candidates: list[LibrarySong], query: str, threshold: flo
class PlaylistCreate(BaseModel): class PlaylistCreate(BaseModel):
name: str name: str
def _liked_song_ids(db: Session, user_id: int) -> set[int]:
"""The caller's liked-song ids, derived from PlaylistTrack membership in their (possibly
not-yet-created) Liked Songs playlist - "liked" isn't a column on LibrarySong, it's purely
membership in that one playlist. Returns an empty set rather than creating the playlist on
a read path (see _get_or_create_liked_playlist's own note on why reads must stay
side-effect-free)."""
liked_playlist = (
db.query(Playlist).filter(Playlist.user_id == user_id, Playlist.is_liked_playlist.is_(True)).first()
)
if not liked_playlist:
return set()
return {
row.song_id
for row in db.query(PlaylistTrack.song_id).filter(PlaylistTrack.playlist_id == liked_playlist.id)
}
def _serialize_song(song: LibrarySong, liked_song_ids: set[int]) -> dict: def _serialize_song(song: LibrarySong, liked_song_ids: set[int]) -> dict:
"""Every response that returns the caller's own songs goes through this so `is_liked` is """Every response that returns the caller's own songs goes through this so `is_liked` is
computed consistently - it's not a LibrarySong column, so the raw ORM object alone (what computed consistently - it's not a LibrarySong column, so the raw ORM object alone (what
...@@ -138,7 +122,7 @@ def _get_or_create_liked_playlist(db: Session, user_id: int) -> Playlist: ...@@ -138,7 +122,7 @@ def _get_or_create_liked_playlist(db: Session, user_id: int) -> Playlist:
"""Lazy-created on first favorite, not hooked into registration - this covers every signup """Lazy-created on first favorite, not hooked into registration - this covers every signup
path (username/password, Telegram link) for free, matching the same reasoning path (username/password, Telegram link) for free, matching the same reasoning
_get_or_create_profile (auth.py) already established for UserProfile. Never call this from _get_or_create_profile (auth.py) already established for UserProfile. Never call this from
a read path (see _liked_song_ids) - only from the favorite-add endpoint, which is the one a read path (see liked_song_ids in services/favorites.py) - only from the favorite-add endpoint, which is the one
place a playlist should actually get created as a side effect.""" place a playlist should actually get created as a side effect."""
playlist = ( playlist = (
db.query(Playlist).filter(Playlist.user_id == user_id, Playlist.is_liked_playlist.is_(True)).first() db.query(Playlist).filter(Playlist.user_id == user_id, Playlist.is_liked_playlist.is_(True)).first()
...@@ -154,7 +138,7 @@ def _get_or_create_liked_playlist(db: Session, user_id: int) -> Playlist: ...@@ -154,7 +138,7 @@ def _get_or_create_liked_playlist(db: Session, user_id: int) -> Playlist:
@router.get("/library") @router.get("/library")
async def get_library(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def get_library(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
songs = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id).order_by(LibrarySong.added_at.desc()).all() songs = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id).order_by(LibrarySong.added_at.desc()).all()
liked_ids = _liked_song_ids(db, current_user.id) liked_ids = liked_song_ids(db, current_user.id)
return {"status": "success", "library": [_serialize_song(s, liked_ids) for s in songs]} return {"status": "success", "library": [_serialize_song(s, liked_ids) for s in songs]}
...@@ -225,7 +209,7 @@ async def get_album( ...@@ -225,7 +209,7 @@ async def get_album(
raise HTTPException(status_code=404, detail="Album not found") raise HTTPException(status_code=404, detail="Album not found")
songs.sort(key=_track_sort_key) songs.sort(key=_track_sort_key)
coverart = next((s.coverart for s in songs if s.coverart), None) coverart = next((s.coverart for s in songs if s.coverart), None)
liked_ids = _liked_song_ids(db, current_user.id) liked_ids = liked_song_ids(db, current_user.id)
return { return {
"status": "success", "status": "success",
"album": { "album": {
...@@ -335,7 +319,7 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db), ...@@ -335,7 +319,7 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
if not entry["coverart"] and song.coverart: if not entry["coverart"] and song.coverart:
entry["coverart"] = song.coverart entry["coverart"] = song.coverart
liked_ids = _liked_song_ids(db, current_user.id) liked_ids = liked_song_ids(db, current_user.id)
albums_out = [] albums_out = []
for entry in albums_by_key.values(): for entry in albums_by_key.values():
entry["songs"] = [_serialize_song(s, liked_ids) for s in entry["songs"]] entry["songs"] = [_serialize_song(s, liked_ids) for s in entry["songs"]]
...@@ -452,7 +436,7 @@ async def get_playlist(playlist_id: int, db: Session = Depends(get_db), current_ ...@@ -452,7 +436,7 @@ async def get_playlist(playlist_id: int, db: Session = Depends(get_db), current_
.order_by(PlaylistTrack.order) .order_by(PlaylistTrack.order)
.all() .all()
) )
liked_ids = _liked_song_ids(db, current_user.id) liked_ids = liked_song_ids(db, current_user.id)
return {"status": "success", "playlist": pl, "tracks": [_serialize_song(s, liked_ids) for s in tracks]} return {"status": "success", "playlist": pl, "tracks": [_serialize_song(s, liked_ids) for s in tracks]}
@router.post("/playlists") @router.post("/playlists")
......
from sqlalchemy.orm import Session
from src.core.database import Playlist, PlaylistTrack
def liked_song_ids(db: Session, user_id: int) -> set[int]:
"""The caller's liked-song ids, derived from PlaylistTrack membership in their (possibly
not-yet-created) Liked Songs playlist - "liked" isn't a column on LibrarySong, it's purely
membership in that one playlist. Returns an empty set rather than creating the playlist on
a read path (see library.py's _get_or_create_liked_playlist for why reads must stay
side-effect-free).
Lives here (not library.py) so the home feed can compute is_liked for the caller's own
songs without importing a router's private function from another router - same reasoning
give_from_shared_library was already moved to its own service module for."""
liked_playlist = (
db.query(Playlist).filter(Playlist.user_id == user_id, Playlist.is_liked_playlist.is_(True)).first()
)
if not liked_playlist:
return set()
return {
row.song_id
for row in db.query(PlaylistTrack.song_id).filter(PlaylistTrack.playlist_id == liked_playlist.id)
}
...@@ -36,17 +36,52 @@ def test_latest_songs_is_global_not_scoped_to_the_caller(client, db_session, aut ...@@ -36,17 +36,52 @@ def test_latest_songs_is_global_not_scoped_to_the_caller(client, db_session, aut
assert any(s["id"] == song.id for s in latest) assert any(s["id"] == song.id for s in latest)
def test_latest_songs_attaches_the_real_uploader_username(client, db_session, auth_as): def test_global_songs_do_not_attach_uploader_identity(client, db_session, auth_as):
# The feed is presented as one shared pool of music, not attributed to whoever added it -
# user_id stays (needed client-side to tell "mine" from "someone else's"), but no username
# or other identifying field should ever appear on a global-feed song.
headers, viewer = auth_as() headers, viewer = auth_as()
_, other_owner = auth_as() _, other_owner = auth_as()
song = _add_song(db_session, other_owner.id, title="Attributed Upload", artist="Nobody") song = _add_song(db_session, other_owner.id, title="Unattributed Upload", artist="Nobody")
response = client.get("/home/feed", headers=headers) response = client.get("/home/feed", headers=headers)
entry = next(s for s in response.json()["latest_songs"] if s["id"] == song.id) entry = next(s for s in response.json()["latest_songs"] if s["id"] == song.id)
assert entry["username"] == other_owner.username assert "username" not in entry
assert entry["user_id"] == other_owner.id assert entry["user_id"] == other_owner.id
def test_latest_songs_deduplicates_the_same_song_uploaded_by_multiple_users(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner_a = auth_as()
_, owner_b = auth_as()
_add_song(db_session, owner_a.id, title="Duplicate Hit Unique Zql", artist="Shared Band")
_add_song(db_session, owner_b.id, title="duplicate hit unique zql", artist="SHARED BAND")
response = client.get("/home/feed", headers=headers)
matching = [s for s in response.json()["latest_songs"] if s["title"].lower() == "duplicate hit unique zql"]
assert len(matching) == 1
def test_latest_songs_is_liked_reflects_the_callers_own_liked_playlist(client, db_session, auth_as):
headers, viewer = auth_as()
mine = _add_song(db_session, viewer.id, title="My Liked Upload Unique Vbn", artist="Me")
client.put(f"/library/{mine.id}/favorite", headers=headers)
response = client.get("/home/feed", headers=headers)
entry = next(s for s in response.json()["latest_songs"] if s["id"] == mine.id)
assert entry["is_liked"] is True
def test_latest_songs_is_liked_false_for_a_song_the_caller_does_not_own(client, db_session, auth_as):
headers, viewer = auth_as()
_, other_owner = auth_as()
song = _add_song(db_session, other_owner.id, title="Not Mine Unique Qrs", artist="Nobody")
response = client.get("/home/feed", headers=headers)
entry = next(s for s in response.json()["latest_songs"] if s["id"] == song.id)
assert entry["is_liked"] is False
def test_latest_songs_is_capped_at_eight(client, db_session, auth_as): def test_latest_songs_is_capped_at_eight(client, db_session, auth_as):
headers, viewer = auth_as() headers, viewer = auth_as()
_, owner = auth_as() _, owner = auth_as()
...@@ -57,18 +92,36 @@ def test_latest_songs_is_capped_at_eight(client, db_session, auth_as): ...@@ -57,18 +92,36 @@ def test_latest_songs_is_capped_at_eight(client, db_session, auth_as):
assert len(response.json()["latest_songs"]) <= 8 assert len(response.json()["latest_songs"]) <= 8
def test_new_albums_groups_separately_per_uploader_even_for_the_same_album_name(client, db_session, auth_as): def test_new_albums_deduplicates_the_same_album_uploaded_by_multiple_users(client, db_session, auth_as):
headers, viewer = auth_as() headers, viewer = auth_as()
_, owner_a = auth_as() _, owner_a = auth_as()
_, owner_b = auth_as() _, owner_b = auth_as()
_add_song(db_session, owner_a.id, title="Track One", artist="Shared Artist", album="Shared Album Name") _add_song(db_session, owner_a.id, title="Track One", artist="Shared Artist", album="Shared Album Name Unique")
_add_song(db_session, owner_b.id, title="Track One", artist="Shared Artist", album="Shared Album Name") _add_song(db_session, owner_b.id, title="Track One", artist="Shared Artist", album="shared album name unique")
response = client.get("/home/feed", headers=headers)
matching = [
a for a in response.json()["new_albums"]
if a["album"].lower() == "shared album name unique" and a["artist"] == "Shared Artist"
]
# Same album identity uploaded by two different users - one card, not one per uploader.
assert len(matching) == 1
def test_new_albums_prefers_the_callers_own_copy_when_merging_duplicates(client, db_session, auth_as):
headers, viewer = auth_as()
_, other_owner = auth_as()
# Caller's own copy added first (older) - the other uploader's copy is more recent, but the
# caller's own should still win as the representative so the card can navigate straight to
# their real album page instead of falling back to the claim-then-expand flow.
mine = _add_song(db_session, viewer.id, title="Mine Preferred", artist="Pref Artist", album="Pref Album Unique")
_add_song(db_session, other_owner.id, title="Mine Preferred", artist="Pref Artist", album="pref album unique")
response = client.get("/home/feed", headers=headers) response = client.get("/home/feed", headers=headers)
matching = [a for a in response.json()["new_albums"] if a["album"] == "Shared Album Name" and a["artist"] == "Shared Artist"] matching = [a for a in response.json()["new_albums"] if a["album"].lower() == "pref album unique"]
# Two distinct uploaders, each gets their own card - never merged into one. assert len(matching) == 1
assert len(matching) == 2 assert matching[0]["user_id"] == viewer.id
assert {a["user_id"] for a in matching} == {owner_a.id, owner_b.id} assert matching[0]["songs"][0]["id"] == mine.id
def test_new_albums_excludes_songs_with_no_album(client, db_session, auth_as): def test_new_albums_excludes_songs_with_no_album(client, db_session, auth_as):
...@@ -121,6 +174,18 @@ def test_suggestions_does_not_duplicate_songs_already_in_latest_or_albums(client ...@@ -121,6 +174,18 @@ def test_suggestions_does_not_duplicate_songs_already_in_latest_or_albums(client
assert suggestion_ids.isdisjoint(album_song_ids) assert suggestion_ids.isdisjoint(album_song_ids)
def test_suggestions_deduplicates_the_same_song_uploaded_by_multiple_other_users(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner_a = auth_as()
_, owner_b = auth_as()
_add_song(db_session, owner_a.id, title="Dupe Suggestion Unique Wxy", artist="Dupe Band")
_add_song(db_session, owner_b.id, title="dupe suggestion unique wxy", artist="DUPE BAND")
response = client.get("/home/feed", headers=headers)
matching = [s for s in response.json()["suggestions"] if s["title"].lower() == "dupe suggestion unique wxy"]
assert len(matching) <= 1
def test_suggestions_is_capped_at_eight(client, db_session, auth_as): def test_suggestions_is_capped_at_eight(client, db_session, auth_as):
headers, viewer = auth_as() headers, viewer = auth_as()
_, owner = auth_as() _, owner = auth_as()
......
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