Commit 1bf26cb9 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add favorites/Liked Songs, a global home feed, and rules-based search upgrades

Playlist gains a structurally-flagged is_liked_playlist column, lazily created
per user on first favorite; is_liked is computed (not stored) and threaded
through every endpoint that returns the caller's own songs. New GET
/home/feed powers a global landing feed (latest songs, new albums, lightweight
non-personalized suggestions) distinct from the per-user Library page.
Library search gains album matching, a recency modifier, a curated mood/genre
synonym table, and a difflib-based typo-tolerance fallback - deliberately
rules-based rather than an LLM call, per direction to build it the way search
worked before AI.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 50bcb35e
Pipeline #1211 failed with stage
in 5 minutes and 34 seconds
"""add is_liked_playlist to playlists
Revision ID: a6f66b340a16
Revises: 83f2d110f07c
Create Date: 2026-10-06 06:32:58.649733
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'a6f66b340a16'
down_revision: Union[str, Sequence[str], None] = '83f2d110f07c'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('playlists', sa.Column('is_liked_playlist', sa.Boolean(), server_default='0', nullable=False))
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('playlists', 'is_liked_playlist')
# ### end Alembic commands ###
......@@ -10,7 +10,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, channels, discovery, dm, library, music, remix, social, soundmarks, telegram_scan
from src.api.routers import auth, channels, discovery, dm, home, library, music, remix, social, soundmarks, telegram_scan
from src.core.config import CORS_ORIGINS, DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR
......@@ -86,6 +86,7 @@ app.mount("/downloads", StaticFiles(directory=DOWNLOADS_DIR), name="downloads")
app.include_router(auth.router)
app.include_router(discovery.router)
app.include_router(home.router)
app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
......
import random
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, User
from src.core.security import get_current_user
router = APIRouter(prefix="/home", tags=["Home"])
LATEST_SONGS_LIMIT = 8
NEW_ALBUMS_LIMIT = 8
SUGGESTIONS_LIMIT = 8
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()
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,
}
@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()
)
# 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.
albums_pool = (
db.query(LibrarySong)
.filter(LibrarySong.album.isnot(None), LibrarySong.album != "")
.order_by(LibrarySong.added_at.desc())
.limit(500)
.all()
)
albums_by_key: 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, {
"album": song.album,
"artist": song.artist,
"user_id": song.user_id,
"coverart": None,
"track_count": 0,
"latest_added_at": song.added_at,
"songs": [],
})
entry["track_count"] += 1
entry["songs"].append(song)
if not entry["coverart"] and song.coverart:
entry["coverart"] = song.coverart
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]
# 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"]}
for album in new_albums:
album["songs"] = [_serialize_global_song(s, db) 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.
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
}
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
]
own_genres = {
g for (g,) in db.query(LibrarySong.genre).filter(LibrarySong.user_id == current_user.id, LibrarySong.genre.isnot(None))
}
if own_genres:
preferred = [s for s in candidates if s.genre in own_genres]
rest = [s for s in candidates if s.genre not in own_genres]
random.shuffle(preferred)
random.shuffle(rest)
candidates = preferred + rest
else:
random.shuffle(candidates)
suggestions = candidates[:SUGGESTIONS_LIMIT]
return {
"status": "success",
"latest_songs": [_serialize_global_song(s, db) for s in latest_songs],
"new_albums": new_albums,
"suggestions": [_serialize_global_song(s, db) for s in suggestions],
}
This diff is collapsed.
......@@ -120,6 +120,11 @@ class Playlist(Base):
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String)
# True only for the one auto-created-per-user "Liked Songs" playlist (see
# _get_or_create_liked_playlist in library.py) - identifies it structurally so it's never
# matched by name (a user could rename/duplicate a playlist called "Liked Songs"), and so
# it can be protected from deletion. Default False for every normal, user-created playlist.
is_liked_playlist = Column(Boolean, default=False, nullable=False, server_default="0")
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class PlaylistTrack(Base):
......
from datetime import datetime, timezone
from src.core.database import LibrarySong
# Session-scoped test DB with no per-test rollback (see conftest.py) means every song any
# earlier test in the whole suite has ever inserted is still present when these run - an
# explicit, deliberately far-future added_at is what guarantees a given test's own song
# deterministically sorts to the top of a global "latest" feed regardless of what else exists.
_FAR_FUTURE = datetime(2099, 1, 1, tzinfo=timezone.utc)
def _add_song(db_session, user_id, **overrides):
defaults = dict(user_id=user_id, title="Test Song", artist="Test Artist", genre="Pop", added_at=_FAR_FUTURE)
defaults.update(overrides)
song = LibrarySong(**defaults)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
return song
def test_home_feed_requires_auth(client):
response = client.get("/home/feed")
assert response.status_code == 401
def test_latest_songs_is_global_not_scoped_to_the_caller(client, db_session, auth_as):
headers, viewer = auth_as()
_, other_owner = auth_as()
song = _add_song(db_session, other_owner.id, title="Someone Else's Fresh Upload", artist="Nobody")
response = client.get("/home/feed", headers=headers)
assert response.status_code == 200
latest = response.json()["latest_songs"]
assert any(s["id"] == song.id for s in latest)
def test_latest_songs_attaches_the_real_uploader_username(client, db_session, auth_as):
headers, viewer = auth_as()
_, other_owner = auth_as()
song = _add_song(db_session, other_owner.id, title="Attributed 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 entry["user_id"] == other_owner.id
def test_latest_songs_is_capped_at_eight(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner = auth_as()
for i in range(10):
_add_song(db_session, owner.id, title=f"Capped Upload {i}", artist="Nobody")
response = client.get("/home/feed", headers=headers)
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):
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")
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}
def test_new_albums_excludes_songs_with_no_album(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner = auth_as()
_add_song(db_session, owner.id, title="Loose Track", artist="Nobody", album=None)
response = client.get("/home/feed", headers=headers)
assert all(a["album"] for a in response.json()["new_albums"])
def test_suggestions_excludes_songs_the_caller_already_owns(client, db_session, auth_as):
headers, viewer = auth_as()
mine = _add_song(db_session, viewer.id, title="My Own Upload Unique Zyx", artist="Me")
response = client.get("/home/feed", headers=headers)
suggestion_ids = {s["id"] for s in response.json()["suggestions"]}
assert mine.id not in suggestion_ids
def test_suggestions_excludes_a_song_the_caller_owns_an_identical_copy_of(client, db_session, auth_as):
# Same (title, artist) identity as a song the caller already has a copy of (just a
# different row, a different owner) - shouldn't be "suggested" as if it were new to them,
# mirroring /library/shared/search's own "own copy first" exclusion.
headers, viewer = auth_as()
_add_song(db_session, viewer.id, title="Identity Match Quirble", artist="Quirble Band")
_, other_owner = auth_as()
other_copy = _add_song(db_session, other_owner.id, title="identity match quirble", artist="QUIRBLE BAND")
response = client.get("/home/feed", headers=headers)
suggestion_ids = {s["id"] for s in response.json()["suggestions"]}
assert other_copy.id not in suggestion_ids
def test_suggestions_does_not_duplicate_songs_already_in_latest_or_albums(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner = auth_as()
# Only a handful of total candidates exist for this owner, all deliberately far-future so
# they'd otherwise dominate both latest_songs and the suggestions candidate pool - proving
# no overlap here isn't just a coincidence of a large, naturally-non-colliding pool.
for i in range(3):
_add_song(db_session, owner.id, title=f"Overlap Check {i}", artist="Nobody", album="Overlap Album")
response = client.get("/home/feed", headers=headers)
body = response.json()
latest_ids = {s["id"] for s in body["latest_songs"]}
album_song_ids = {s["id"] for album in body["new_albums"] for s in album["songs"]}
suggestion_ids = {s["id"] for s in body["suggestions"]}
assert suggestion_ids.isdisjoint(latest_ids)
assert suggestion_ids.isdisjoint(album_song_ids)
def test_suggestions_is_capped_at_eight(client, db_session, auth_as):
headers, viewer = auth_as()
_, owner = auth_as()
for i in range(12):
_add_song(db_session, owner.id, title=f"Suggestion Pool {i}", artist=f"Artist {i}")
response = client.get("/home/feed", headers=headers)
assert len(response.json()["suggestions"]) <= 8
......@@ -119,6 +119,93 @@ def test_library_search_ignores_songs_with_no_album(client, db_session, auth_as)
os.remove(path)
def test_library_search_matches_album_field_directly(client, db_session, auth_as):
# Not an album-name or artist match that surfaces an "Albums" grouping (see the test above
# for that) - this is the plain Songs-section match gaining the album field itself, which
# it didn't check before.
headers, user = auth_as()
_, path = _make_library_song(db_session, user.id, title="Deep Cut", artist="Nobody Famous", album="Zorquil Sessions")
try:
response = client.post("/library/search", data={"query": "Zorquil"}, headers=headers)
songs = response.json()["songs"]
assert any(s["title"] == "Deep Cut" for s in songs)
finally:
os.remove(path)
def test_library_search_abstract_mood_query_matches_mapped_genres(client, db_session, auth_as):
headers, user = auth_as()
_, dance_path = _make_library_song(db_session, user.id, title="Floorfiller", artist="DJ Nobody", genre="Dance")
_, classical_path = _make_library_song(db_session, user.id, title="Nocturne", artist="Composer Nobody", genre="Classical")
try:
response = client.post("/library/search", data={"query": "party"}, headers=headers)
titles = {s["title"] for s in response.json()["songs"]}
assert "Floorfiller" in titles
assert "Nocturne" not in titles
finally:
os.remove(dance_path)
os.remove(classical_path)
def test_library_search_recency_modifier_orders_newest_first(client, db_session, auth_as):
headers, user = auth_as()
_, old_path = _make_library_song(db_session, user.id, title="Old Rock Jam", artist="Nobody", genre="Rock")
old_song = db_session.query(LibrarySong).filter(LibrarySong.title == "Old Rock Jam").one()
from datetime import datetime, timedelta, timezone
old_song.added_at = datetime.now(timezone.utc) - timedelta(days=30)
db_session.commit()
_, new_path = _make_library_song(db_session, user.id, title="Fresh Rock Jam", artist="Nobody", genre="Rock")
try:
response = client.post("/library/search", data={"query": "new rock"}, headers=headers)
titles = [s["title"] for s in response.json()["songs"] if "Rock Jam" in s["title"]]
assert titles == ["Fresh Rock Jam", "Old Rock Jam"]
finally:
os.remove(old_path)
os.remove(new_path)
def test_library_search_typo_tolerance_fallback(client, db_session, auth_as):
headers, user = auth_as()
_, path = _make_library_song(db_session, user.id, title="Invisible", artist="Someone")
try:
# No literal/mood/genre match exists for this misspelling, so the fuzzy fallback is
# what's actually being exercised here.
response = client.post("/library/search", data={"query": "invisble"}, headers=headers)
titles = {s["title"] for s in response.json()["songs"]}
assert "Invisible" in titles
finally:
os.remove(path)
def test_library_search_typo_tolerance_does_not_fire_when_literal_match_exists(client, db_session, auth_as):
# The fuzzy fallback only runs on an empty literal+mood result - confirmed indirectly here
# by making sure an unrelated, poorly-matching song doesn't get pulled in by it when a
# perfectly good literal match already exists.
headers, user = auth_as()
_, path1 = _make_library_song(db_session, user.id, title="Exact Match Title", artist="Someone")
_, path2 = _make_library_song(db_session, user.id, title="Zzzznoise", artist="Nobody Related")
try:
response = client.post("/library/search", data={"query": "Exact Match Title"}, headers=headers)
titles = {s["title"] for s in response.json()["songs"]}
assert titles == {"Exact Match Title"}
finally:
os.remove(path1)
os.remove(path2)
def test_shared_search_matches_album_field(client, db_session, auth_as):
headers, searcher = auth_as()
_, owner = auth_as()
_add_song(db_session, owner.id, title="Shared Deep Cut", artist="Shared Nobody")
song = db_session.query(LibrarySong).filter(LibrarySong.title == "Shared Deep Cut").one()
song.album = "Vorblatt Sessions"
db_session.commit()
response = client.post("/library/shared/search", data={"query": "Vorblatt"}, headers=headers)
titles = [s["title"] for s in response.json()["songs"]]
assert "Shared Deep Cut" in titles
def test_get_album_requires_auth(client):
response = client.get("/library/album", params={"album": "X", "artist": "Y"})
assert response.status_code == 401
......@@ -626,3 +713,101 @@ def test_remove_track_from_another_users_playlist_404s(client, db_session, auth_
headers_b, _ = auth_as()
response = client.delete(f"/playlists/{playlist_id}/tracks/{song.id}", headers=headers_b)
assert response.status_code == 404
def test_favorite_song_creates_liked_playlist_and_marks_it_liked(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Favorite Me")
response = client.put(f"/library/{song.id}/favorite", headers=headers)
assert response.status_code == 200
assert response.json()["is_liked"] is True
library = client.get("/library", headers=headers).json()["library"]
assert next(s for s in library if s["id"] == song.id)["is_liked"] is True
playlists = client.get("/playlists", headers=headers).json()["playlists"]
liked = next(p for p in playlists if p["is_liked_playlist"])
assert liked["name"] == "Liked Songs"
def test_favorite_song_is_idempotent(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Double Like")
client.put(f"/library/{song.id}/favorite", headers=headers)
client.put(f"/library/{song.id}/favorite", headers=headers)
playlists = client.get("/playlists", headers=headers).json()["playlists"]
liked_id = next(p["id"] for p in playlists if p["is_liked_playlist"])
tracks = client.get(f"/playlists/{liked_id}", headers=headers).json()["tracks"]
assert [t["id"] for t in tracks].count(song.id) == 1
def test_unfavorite_song_removes_it_and_is_idempotent(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Unlike Me")
client.put(f"/library/{song.id}/favorite", headers=headers)
response = client.delete(f"/library/{song.id}/favorite", headers=headers)
assert response.status_code == 200
assert response.json()["is_liked"] is False
library = client.get("/library", headers=headers).json()["library"]
assert next(s for s in library if s["id"] == song.id)["is_liked"] is False
# No-op the second time, and no-op entirely when the liked playlist was never created.
response_again = client.delete(f"/library/{song.id}/favorite", headers=headers)
assert response_again.status_code == 200
def test_unfavorite_with_no_liked_playlist_yet_is_a_no_op(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Never Liked")
response = client.delete(f"/library/{song.id}/favorite", headers=headers)
assert response.status_code == 200
assert response.json()["is_liked"] is False
def test_favorite_song_requires_ownership(client, db_session, auth_as):
headers_a, user_a = auth_as()
song = _add_song(db_session, user_a.id, title="Not Yours")
headers_b, _ = auth_as()
response = client.put(f"/library/{song.id}/favorite", headers=headers_b)
assert response.status_code == 404
def test_favorite_song_404_for_unknown_song(client, auth_as):
headers, _ = auth_as()
response = client.put("/library/999999/favorite", headers=headers)
assert response.status_code == 404
def test_liked_playlist_cannot_be_deleted(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Protects Playlist")
client.put(f"/library/{song.id}/favorite", headers=headers)
liked_id = next(p["id"] for p in client.get("/playlists", headers=headers).json()["playlists"] if p["is_liked_playlist"])
response = client.delete(f"/playlists/{liked_id}", headers=headers)
assert response.status_code == 400
def test_liked_playlist_sorts_first(client, db_session, auth_as):
headers, user = auth_as()
client.post("/playlists", json={"name": "Z Playlist"}, headers=headers)
song = _add_song(db_session, user.id, title="Sorts First")
client.put(f"/library/{song.id}/favorite", headers=headers)
playlists = client.get("/playlists", headers=headers).json()["playlists"]
assert playlists[0]["is_liked_playlist"] is True
def test_is_liked_false_by_default_for_an_unfavorited_song(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Untouched")
library = client.get("/library", headers=headers).json()["library"]
assert next(s for s in library if s["id"] == song.id)["is_liked"] is False
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