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
......@@ -5,59 +5,88 @@ from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, User
from src.core.security import get_current_user
from src.services.favorites import liked_song_ids
router = APIRouter(prefix="/home", tags=["Home"])
LATEST_SONGS_LIMIT = 8
NEW_ALBUMS_LIMIT = 8
SUGGESTIONS_LIMIT = 8
# How many of the most-recent rows to scan before dedup/grouping - wider than the display caps
# above since the same song or album is commonly uploaded by more than one user, and those
# duplicates need to collapse to one entry *before* capping, not after (otherwise a popular
# song could eat several of the 8 display slots on its own).
POOL_SIZE = 500
def _serialize_global_song(song: LibrarySong, db: Session) -> dict:
"""Global-feed songs belong to whichever user actually uploaded them, not the viewer - no
`is_liked` here (see library.py's own _serialize_song docstring: a viewer can't have liked
a song they don't own yet), but the real owner's username is attached so the frontend can
tell "mine, play directly" from "someone else's, claim first" the same way it already does
for shared-library search results."""
author = db.query(User).filter(User.id == song.user_id).first()
def _identity_key(title: str | None, artist: str | None) -> tuple[str, str] | None:
"""Case/whitespace-insensitive (title, artist) identity - the same notion of "this is the
same song" used throughout the shared-library/claim flow (see shared_library.py's
find_library_match). None for a row missing either field, which can't be meaningfully
deduped or claimed anyway."""
if not title or not artist:
return None
return (title.strip().lower(), artist.strip().lower())
def _serialize_global_song(song: LibrarySong, liked_ids: set[int]) -> dict:
"""Global-feed songs belong to whichever user actually uploaded them, not necessarily the
viewer - deliberately no uploader identity (name/username) in this response, the feed is
presented as one shared pool of music, not attributed to whoever happened to add it first.
`is_liked` is only ever true for a song the caller already owns (liked_ids comes from their
own Liked Songs playlist) - a song still owned by someone else naturally isn't in that set,
so it reads as not-liked until claimed, same as everywhere else `is_liked` appears."""
return {
"id": song.id,
"user_id": song.user_id,
"username": author.username if author else None,
"title": song.title,
"artist": song.artist,
"album": song.album,
"genre": song.genre,
"coverart": song.coverart,
"added_at": song.added_at,
"is_liked": song.id in liked_ids,
}
@router.get("/feed")
async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""The Home page's feed - everything here is global (every user's uploads), unlike the
per-user Library page. `suggestions` is explicitly a placeholder (see its own comment
below), not a real recommendation algorithm yet."""
latest_songs = (
db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).limit(LATEST_SONGS_LIMIT).all()
)
per-user Library page. Every section is deduped by (title, artist) identity so the same
song/album tagged by multiple users shows once, not once per uploader - which uploader's
copy ends up representing it is an implementation detail (preferring the caller's own copy,
so tapping it plays/navigates directly rather than needing a claim first), not shown to the
viewer. `suggestions` is explicitly a placeholder (see its own comment below), not a real
recommendation algorithm yet."""
liked_ids = liked_song_ids(db, current_user.id)
# Grouped by (album, artist, user_id) - deliberately NOT merged across different
# uploaders of the same album. /library/shared/search's own docstring already ruled this
# out for the shared-search feature (no real Album entity exists, so there's no clean way
# to decide whose coverart wins or how to reconcile different track subsets) - the same
# reasoning applies here, so each uploader's copy of an album gets its own card.
latest_pool = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).limit(POOL_SIZE).all()
seen_identities: set[tuple[str, str]] = set()
latest_songs: list[LibrarySong] = []
for song in latest_pool:
key = _identity_key(song.title, song.artist)
if key is None or key in seen_identities:
continue
seen_identities.add(key)
latest_songs.append(song)
if len(latest_songs) >= LATEST_SONGS_LIMIT:
break
# First pass: group by (album, artist, user_id) exactly as before - each uploader's full,
# untouched set of tracks for that album, never mixed with another uploader's files (there's
# no real Album entity to reconcile mismatched track subsets/coverart against, so a shown
# album is always one real person's actual upload, start to finish).
albums_pool = (
db.query(LibrarySong)
.filter(LibrarySong.album.isnot(None), LibrarySong.album != "")
.order_by(LibrarySong.added_at.desc())
.limit(500)
.limit(POOL_SIZE)
.all()
)
albums_by_key: dict[tuple[str, str, int], dict] = {}
per_uploader_albums: dict[tuple[str, str, int], dict] = {}
for song in albums_pool:
key = (song.album, song.artist, song.user_id)
entry = albums_by_key.setdefault(key, {
entry = per_uploader_albums.setdefault(key, {
"album": song.album,
"artist": song.artist,
"user_id": song.user_id,
......@@ -73,33 +102,62 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
if song.added_at and (not entry["latest_added_at"] or song.added_at > entry["latest_added_at"]):
entry["latest_added_at"] = song.added_at
new_albums = sorted(albums_by_key.values(), key=lambda a: a["latest_added_at"] or "", reverse=True)[:NEW_ALBUMS_LIMIT]
# Second pass: collapse those per-uploader groups down to one representative per
# (album, artist) - picking which uploader's copy to show, not merging their track data
# together. The caller's own copy wins whenever they have one (so the card can navigate
# straight to their real album page instead of the claim-then-expand flow); otherwise the
# most recently added copy wins.
albums_by_identity: dict[tuple[str, str], dict] = {}
for entry in per_uploader_albums.values():
key = _identity_key(entry["album"], entry["artist"])
if key is None:
continue
existing = albums_by_identity.get(key)
if existing is None:
albums_by_identity[key] = entry
continue
existing_is_mine = existing["user_id"] == current_user.id
entry_is_mine = entry["user_id"] == current_user.id
if entry_is_mine and not existing_is_mine:
albums_by_identity[key] = entry
elif entry_is_mine == existing_is_mine and entry["latest_added_at"] > existing["latest_added_at"]:
albums_by_identity[key] = entry
new_albums = sorted(albums_by_identity.values(), key=lambda a: a["latest_added_at"] or "", reverse=True)[:NEW_ALBUMS_LIMIT]
# Computed before the serialization loop below mutates each shown album's "songs" from raw
# ORM rows into plain dicts - only what's actually displayed (the capped `new_albums`, not
# every group that happened to exist) should be excluded from suggestions.
already_shown_ids = {s.id for s in latest_songs} | {s.id for album in new_albums for s in album["songs"]}
already_shown_identities = seen_identities | {
key for album in new_albums for key in [_identity_key(album["album"], album["artist"])] if key
}
for album in new_albums:
album["songs"] = [_serialize_global_song(s, db) for s in album["songs"]]
album["songs"] = [_serialize_global_song(s, liked_ids) for s in album["songs"]]
del album["latest_added_at"]
# Placeholder, not a real algorithm yet (per the explicit product direction: a future pass
# will build this from search/listening habits instead). For now: a lightweight,
# non-personalized pick from songs the caller doesn't already own, with a soft bias toward
# genres already present in the caller's own library when they have any - otherwise plain
# random. Excludes anything already surfaced above so the page doesn't show the same song
# twice.
# random. Excludes anything already surfaced above (by id and by identity, so a different
# uploader's copy of a song already shown in New Songs/New Albums doesn't show again here
# under a different row) and deduped against itself the same way, so two other users' copies
# of the same song don't both appear.
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
key for s in db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id)
if (key := _identity_key(s.title, s.artist))
}
candidates = [
s for s in db.query(LibrarySong).filter(LibrarySong.user_id != current_user.id).all()
if s.id not in already_shown_ids
and s.title and s.artist
and (s.title.strip().lower(), s.artist.strip().lower()) not in own_keys
]
candidates = []
seen_suggestion_identities: set[tuple[str, str]] = set()
for s in db.query(LibrarySong).filter(LibrarySong.user_id != current_user.id).all():
if s.id in already_shown_ids:
continue
key = _identity_key(s.title, s.artist)
if key is None or key in own_keys or key in already_shown_identities or key in seen_suggestion_identities:
continue
seen_suggestion_identities.add(key)
candidates.append(s)
own_genres = {
g for (g,) in db.query(LibrarySong.genre).filter(LibrarySong.user_id == current_user.id, LibrarySong.genre.isnot(None))
......@@ -117,7 +175,7 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
return {
"status": "success",
"latest_songs": [_serialize_global_song(s, db) for s in latest_songs],
"latest_songs": [_serialize_global_song(s, liked_ids) for s in latest_songs],
"new_albums": new_albums,
"suggestions": [_serialize_global_song(s, db) for s in suggestions],
"suggestions": [_serialize_global_song(s, liked_ids) for s in suggestions],
}
......@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
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.services.shared_library import give_from_shared_library
from src.services.favorites import liked_song_ids
router = APIRouter(tags=["Library & Playlists"])
......@@ -95,23 +96,6 @@ def _fuzzy_match_songs(candidates: list[LibrarySong], query: str, threshold: flo
class PlaylistCreate(BaseModel):
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:
"""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
......@@ -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
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
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."""
playlist = (
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:
@router.get("/library")
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()
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]}
......@@ -225,7 +209,7 @@ async def get_album(
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)
liked_ids = _liked_song_ids(db, current_user.id)
liked_ids = liked_song_ids(db, current_user.id)
return {
"status": "success",
"album": {
......@@ -335,7 +319,7 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
if not entry["coverart"] and 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 = []
for entry in albums_by_key.values():
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_
.order_by(PlaylistTrack.order)
.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]}
@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
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()
_, 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)
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
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):
headers, viewer = auth_as()
_, owner = 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
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()
_, owner_a = 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_b.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 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)
matching = [a for a in response.json()["new_albums"] if a["album"] == "Shared Album Name" and a["artist"] == "Shared Artist"]
# Two distinct uploaders, each gets their own card - never merged into one.
assert len(matching) == 2
assert {a["user_id"] for a in matching} == {owner_a.id, owner_b.id}
matching = [a for a in response.json()["new_albums"] if a["album"].lower() == "pref album unique"]
assert len(matching) == 1
assert matching[0]["user_id"] == viewer.id
assert matching[0]["songs"][0]["id"] == mine.id
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
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):
headers, viewer = 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