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],
}
import difflib
import json
import os
from fastapi import APIRouter, Depends, HTTPException, Form
from fastapi.responses import FileResponse
from pydantic import BaseModel
from sqlalchemy import or_
from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
......@@ -11,13 +13,183 @@ from src.services.shared_library import give_from_shared_library
router = APIRouter(tags=["Library & Playlists"])
# "How search worked before embeddings": a recency keyword plus a curated mood/vibe-to-genre
# vocabulary (think early iTunes smart playlists, or Pandora's hand-tagged Music Genome
# Project), not a model. Neither is a *replacement* for the plain substring match in
# search_library/search_shared_library below - both are purely additive (extra OR'd candidates,
# or an ordering bias), so a song literally titled e.g. "New Rock Anthem" is still found by the
# existing substring pass regardless of what gets recognized here. Easy to extend with more
# entries later; not meant to be exhaustive.
_RECENCY_WORDS = {"new", "newest", "latest", "recent", "recently"}
_MOOD_GENRE_SYNONYMS: dict[str, list[str]] = {
"party": ["Dance", "Pop", "Hip Hop", "EDM"],
"dance": ["Dance", "EDM", "Pop"],
"chill": ["Lo-fi", "Acoustic", "Jazz", "Chill"],
"relax": ["Lo-fi", "Acoustic", "Jazz"],
"relaxing": ["Lo-fi", "Acoustic", "Jazz"],
"sad": ["Blues", "R&B", "Soul"],
"happy": ["Pop", "Dance"],
"upbeat": ["Pop", "Dance", "EDM"],
"energetic": ["EDM", "Rock", "Hip Hop"],
"workout": ["EDM", "Hip Hop", "Rock"],
"gym": ["EDM", "Hip Hop", "Rock"],
"romantic": ["R&B", "Soul", "Pop"],
"love": ["R&B", "Soul", "Pop"],
"angry": ["Rock", "Metal", "Punk"],
"study": ["Lo-fi", "Classical", "Jazz"],
"focus": ["Lo-fi", "Classical", "Jazz"],
"sleep": ["Lo-fi", "Acoustic", "Classical"],
}
FUZZY_MATCH_THRESHOLD = 0.6
def _parse_search_modifiers(query: str) -> tuple[bool, set[str], str]:
"""Returns (recency_bias, mood_genres, literal_query). Recognized words (a recency keyword,
or a mood word that mapped to real genres) are stripped out of `literal_query` - without
this, "new rock" would only ever be checked as the literal 7-character substring "new
rock" against each field, which obviously never matches a genre value that's just "Rock".
Once stripped, "rock" alone is a real substring of "Rock" via the normal genre match,
while "new" separately drives the recency ordering below. A query that's entirely
recognized words (e.g. just "party") ends up with an empty literal_query - callers must
treat that as "no literal filter at all", not an unbounded `ILIKE '%%'` that would match
every row."""
words = query.lower().split()
recency = False
genres: set[str] = set()
literal_words = []
for w in words:
is_modifier = False
if w in _RECENCY_WORDS:
recency = True
is_modifier = True
mapped = _MOOD_GENRE_SYNONYMS.get(w)
if mapped:
genres.update(mapped)
is_modifier = True
if not is_modifier:
literal_words.append(w)
return recency, genres, " ".join(literal_words)
def _fuzzy_match_songs(candidates: list[LibrarySong], query: str, threshold: float = FUZZY_MATCH_THRESHOLD) -> list[LibrarySong]:
"""Typo tolerance for when the literal+mood pipeline above finds nothing - classic
edit-distance-style spell correction (the same family as 2000s-era "did you mean"), not
ML. Only ever called on that empty-result path, so a normal search never pays this extra
pass. `candidates` is whatever pool the caller already has in hand (own library, or the
shared pool) - this doesn't run its own query."""
query_lower = query.strip().lower()
if not query_lower:
return []
scored = []
for song in candidates:
title_ratio = difflib.SequenceMatcher(None, query_lower, (song.title or "").lower()).ratio()
artist_ratio = difflib.SequenceMatcher(None, query_lower, (song.artist or "").lower()).ratio()
best = max(title_ratio, artist_ratio)
if best >= threshold:
scored.append((best, song))
scored.sort(key=lambda pair: pair[0], reverse=True)
return [song for _, song in scored]
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
every one of these endpoints used to return directly) can't carry it. Not used for other
users' songs (shared search, the home feed) - a viewer can't have liked a song they don't
own yet."""
return {
"id": song.id,
"user_id": song.user_id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"genre": song.genre,
"coverart": song.coverart,
"lyrics": song.lyrics,
"track_number": song.track_number,
"file_path": song.file_path,
"added_at": song.added_at,
"is_liked": song.id in liked_song_ids,
}
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
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()
)
if not playlist:
playlist = Playlist(user_id=user_id, name="Liked Songs", is_liked_playlist=True)
db.add(playlist)
db.commit()
db.refresh(playlist)
return 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()
return {"status": "success", "library": songs}
liked_ids = _liked_song_ids(db, current_user.id)
return {"status": "success", "library": [_serialize_song(s, liked_ids) for s in songs]}
@router.put("/library/{file_id}/favorite")
async def favorite_song(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
liked_playlist = _get_or_create_liked_playlist(db, current_user.id)
existing = db.query(PlaylistTrack).filter(
PlaylistTrack.playlist_id == liked_playlist.id, PlaylistTrack.song_id == file_id
).first()
if not existing:
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == liked_playlist.id).count()
db.add(PlaylistTrack(playlist_id=liked_playlist.id, song_id=file_id, order=max_order))
db.commit()
return {"status": "success", "is_liked": True}
@router.delete("/library/{file_id}/favorite")
async def unfavorite_song(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
# No-op (not a 404) if never liked, or if the liked playlist doesn't exist yet at all -
# "already unliked" is the same end state either way, not an error.
liked_playlist = (
db.query(Playlist).filter(Playlist.user_id == current_user.id, Playlist.is_liked_playlist.is_(True)).first()
)
if liked_playlist:
db.query(PlaylistTrack).filter(
PlaylistTrack.playlist_id == liked_playlist.id, PlaylistTrack.song_id == file_id
).delete()
db.commit()
return {"status": "success", "is_liked": False}
def _track_sort_key(song: LibrarySong):
......@@ -53,9 +225,16 @@ 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)
return {
"status": "success",
"album": {"album": album, "artist": artist, "coverart": coverart, "track_count": len(songs), "songs": songs},
"album": {
"album": album,
"artist": artist,
"coverart": coverart,
"track_count": len(songs),
"songs": [_serialize_song(s, liked_ids) for s in songs],
},
}
@router.get("/library/stream/{file_id}")
......@@ -95,24 +274,51 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
"""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}%"
songs = db.query(LibrarySong).filter(
LibrarySong.user_id == current_user.id,
(LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q))
).all()
matching song.
Beyond a plain title/artist/album/genre substring match, this also recognizes a recency
modifier ("new", "latest", ...) and a curated mood/vibe vocabulary ("party", "chill", ...)
expanding into real genre values - see _parse_search_modifiers's own comment for why this
is a deliberately non-ML, rules-based approach. If that whole pipeline still comes up empty,
falls back to typo-tolerant fuzzy matching (_fuzzy_match_songs) over the caller's own
library. Were this ever to need real relevance ranking or run at a much larger scale than a
single user's library, SQLite's built-in FTS5 virtual table (available here - SQLite 3.45)
would be the natural next step; not needed yet at this scale, so not built."""
recency, mood_genres, literal_query = _parse_search_modifiers(query)
q = f"%{literal_query}%" if literal_query else None
song_filters = []
if q:
song_filters += [
LibrarySong.title.ilike(q),
LibrarySong.artist.ilike(q),
LibrarySong.album.ilike(q),
LibrarySong.genre.ilike(q),
]
if mood_genres:
song_filters.append(LibrarySong.genre.in_(mood_genres))
if song_filters:
songs_query = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id, or_(*song_filters))
songs = (songs_query.order_by(LibrarySong.added_at.desc()) if recency else songs_query).all()
else:
songs = []
if not songs:
own_library = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id).all()
songs = _fuzzy_match_songs(own_library, query)
# 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).
# apps: each section matches on its own identifying field). Uses the same stripped
# literal_query as the songs match above - a query of just "new" (no literal remainder at
# all) has nothing meaningful to match an album name/artist against either.
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()
).all() if q else []
albums_by_key: dict[tuple[str, str], dict] = {}
for song in album_songs:
......@@ -129,7 +335,17 @@ async def search_library(query: str = Form(...), db: Session = Depends(get_db),
if not entry["coverart"] and song.coverart:
entry["coverart"] = song.coverart
return {"status": "success", "songs": songs, "albums": list(albums_by_key.values())}
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"]]
albums_out.append(entry)
return {
"status": "success",
"songs": [_serialize_song(s, liked_ids) for s in songs],
"albums": albums_out,
}
@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)):
......@@ -151,13 +367,32 @@ async def search_shared_library(query: str = Form(...), db: Session = Depends(ge
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()
someone else already has.
Gets the same album-field addition, mood/genre vocabulary, and typo-tolerance fallback as
/library/search - see that endpoint's own docstring and _parse_search_modifiers for why."""
recency, mood_genres, literal_query = _parse_search_modifiers(query)
q = f"%{literal_query}%" if literal_query else None
match_filters = []
if q:
match_filters += [
LibrarySong.title.ilike(q),
LibrarySong.artist.ilike(q),
LibrarySong.album.ilike(q),
LibrarySong.genre.ilike(q),
]
if mood_genres:
match_filters.append(LibrarySong.genre.in_(mood_genres))
if match_filters:
matches_query = db.query(LibrarySong).filter(or_(*match_filters))
matches = (matches_query.order_by(LibrarySong.added_at.desc()) if recency else matches_query).all()
else:
matches = []
if not matches:
matches = _fuzzy_match_songs(db.query(LibrarySong).all(), query)
own_keys = {
(s.title.strip().lower(), s.artist.strip().lower())
......@@ -195,7 +430,14 @@ async def claim_shared_song(
@router.get("/playlists")
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()
# Liked Songs (if it exists for this user yet - it's lazy-created, see
# _get_or_create_liked_playlist) always sorts first, everything else by recency after that.
playlists = (
db.query(Playlist)
.filter(Playlist.user_id == current_user.id)
.order_by(Playlist.is_liked_playlist.desc(), Playlist.created_at.desc())
.all()
)
return {"status": "success", "playlists": playlists}
@router.get("/playlists/{playlist_id}")
......@@ -210,7 +452,8 @@ async def get_playlist(playlist_id: int, db: Session = Depends(get_db), current_
.order_by(PlaylistTrack.order)
.all()
)
return {"status": "success", "playlist": pl, "tracks": tracks}
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")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
......@@ -225,6 +468,8 @@ async def delete_playlist(playlist_id: int, db: Session = Depends(get_db), curre
pl = db.query(Playlist).filter(Playlist.id == playlist_id, Playlist.user_id == current_user.id).first()
if not pl:
raise HTTPException(status_code=404, detail="Playlist not found")
if pl.is_liked_playlist:
raise HTTPException(status_code=400, detail="Can't delete your Liked Songs playlist")
db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).delete()
db.delete(pl)
db.commit()
......
......@@ -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