Commit 575d3a59 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add delete endpoints (library/playlists/tracks) + rate limit Discovery's identify endpoint

DELETE /library/{id} - removes a song, its file on disk, and any
PlaylistTrack rows pointing at it (owner-scoped).
DELETE /playlists/{id} - removes a playlist and its tracks (owner-scoped).
DELETE /playlists/{id}/tracks/{song_id} - removes one track from a
playlist without deleting the song itself (owner-scoped).

Also adds rate limiting to POST /discovery/listen (20 identify calls per
user per 10 minutes, new DiscoveryAttempt table + migration 9f6585c71f80)
- each call is a real, billable Shazam + AcoustID request and was
previously uncapped. Counts every attempt, not just successful ones (a
failed identification still costs the same external API call, and only
successful ones create a DiscoveredSong row).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 28e9ac64
Pipeline #1099 passed with stage
in 8 minutes and 21 seconds
"""add discovery_attempts table
Revision ID: 9f6585c71f80
Revises: d22ca64d291e
Create Date: 2026-08-18 07:00:15.368326
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '9f6585c71f80'
down_revision: Union[str, Sequence[str], None] = 'd22ca64d291e'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.create_table(
"discovery_attempts",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_discovery_attempts_id"), "discovery_attempts", ["id"])
op.create_index(op.f("ix_discovery_attempts_user_id"), "discovery_attempts", ["user_id"])
def downgrade() -> None:
"""Downgrade schema."""
op.drop_index(op.f("ix_discovery_attempts_user_id"), table_name="discovery_attempts")
op.drop_index(op.f("ix_discovery_attempts_id"), table_name="discovery_attempts")
op.drop_table("discovery_attempts")
import shutil import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from src.core.database import get_db, DiscoveredSong, User from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, User
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services import storage from src.services import storage
from src.services.music_identification import identify_audio from src.services.music_identification import identify_audio
router = APIRouter(prefix="/discovery", tags=["Music Discovery"]) router = APIRouter(prefix="/discovery", tags=["Music Discovery"])
# Each /discovery/listen call is a real Shazam + AcoustID request - cheap DB-backed limit,
# same pattern as auth.py's rate limiters, so this doesn't get hammered (by accident or
# abuse) into real API costs/quota exhaustion.
MAX_IDENTIFY_ATTEMPTS_PER_USER = 20
IDENTIFY_WINDOW = timedelta(minutes=10)
def _check_identify_rate_limit(db: Session, user_id: int):
now = datetime.now(timezone.utc).replace(tzinfo=None)
count = (
db.query(DiscoveryAttempt)
.filter(DiscoveryAttempt.user_id == user_id, DiscoveryAttempt.created_at >= now - IDENTIFY_WINDOW)
.count()
)
if count >= MAX_IDENTIFY_ATTEMPTS_PER_USER:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later")
@router.post("/listen") @router.post("/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Accepts a short audio snippet from the microphone to identify what's playing.""" """Accepts a short audio snippet from the microphone to identify what's playing."""
_check_identify_rate_limit(db, current_user.id)
db.add(DiscoveryAttempt(user_id=current_user.id))
db.commit()
temp_path = storage.new_temp_path(file.filename) temp_path = storage.new_temp_path(file.filename)
with open(temp_path, "wb") as buffer: with open(temp_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer) shutil.copyfileobj(file.file, buffer)
......
...@@ -24,6 +24,20 @@ async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user ...@@ -24,6 +24,20 @@ async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user
raise HTTPException(status_code=404, detail="Audio file not found") raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg") return FileResponse(song.file_path, media_type="audio/mpeg")
@router.delete("/library/{file_id}")
async def delete_library_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")
# Clean up playlist entries pointing at this song too - otherwise a playlist would keep a
# PlaylistTrack row referencing a song_id that no longer resolves to anything.
db.query(PlaylistTrack).filter(PlaylistTrack.song_id == file_id).delete()
if song.file_path and os.path.exists(song.file_path):
os.remove(song.file_path)
db.delete(song)
db.commit()
return {"status": "success"}
@router.get("/library/lyrics/{file_id}") @router.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def get_lyrics(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() song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
...@@ -69,6 +83,16 @@ async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db), c ...@@ -69,6 +83,16 @@ async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db), c
db.refresh(new_pl) db.refresh(new_pl)
return {"status": "success", "playlist": new_pl} return {"status": "success", "playlist": new_pl}
@router.delete("/playlists/{playlist_id}")
async def delete_playlist(playlist_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
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")
db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).delete()
db.delete(pl)
db.commit()
return {"status": "success"}
@router.post("/playlists/{playlist_id}/add") @router.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id, Playlist.user_id == current_user.id).first() pl = db.query(Playlist).filter(Playlist.id == playlist_id, Playlist.user_id == current_user.id).first()
...@@ -85,3 +109,15 @@ async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Sessio ...@@ -85,3 +109,15 @@ async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Sessio
db.add(pt) db.add(pt)
db.commit() db.commit()
return {"status": "success", "message": "Added to playlist"} return {"status": "success", "message": "Added to playlist"}
@router.delete("/playlists/{playlist_id}/tracks/{song_id}")
async def remove_from_playlist(playlist_id: int, song_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
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")
track = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id, PlaylistTrack.song_id == song_id).first()
if not track:
raise HTTPException(status_code=404, detail="That song isn't in this playlist")
db.delete(track)
db.commit()
return {"status": "success"}
...@@ -62,6 +62,16 @@ class AuthAttempt(Base): ...@@ -62,6 +62,16 @@ class AuthAttempt(Base):
ip_address = Column(String, index=True) ip_address = Column(String, index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveryAttempt(Base):
"""Logged on every /discovery/listen call, success or not - each one is a real Shazam +
AcoustID request, so this rate-limits the expensive external calls themselves, not just
successful identifications (a DiscoveredSong row only gets created on success, which
would miss failed/abusive traffic entirely)."""
__tablename__ = "discovery_attempts"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveredSong(Base): class DiscoveredSong(Base):
__tablename__ = "discovered_songs" __tablename__ = "discovered_songs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
......
...@@ -84,6 +84,60 @@ def test_discovery_listen_no_match(client, auth_as, monkeypatch): ...@@ -84,6 +84,60 @@ def test_discovery_listen_no_match(client, auth_as, monkeypatch):
assert "message" in body assert "message" in body
def test_discovery_listen_counts_toward_rate_limit_even_on_a_miss(client, db_session, auth_as, monkeypatch):
# A failed identification is still a real, billable Shazam + AcoustID call - it must
# count toward the limit exactly like a hit does, not just successful DiscoveredSong rows.
from src.core.database import DiscoveryAttempt
headers, user = auth_as()
async def _fake_identify_miss(path):
return []
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_miss)
client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
count = db_session.query(DiscoveryAttempt).filter(DiscoveryAttempt.user_id == user.id).count()
assert count == 1
def test_discovery_listen_rate_limited_after_too_many_attempts(client, auth_as, monkeypatch):
headers, _ = auth_as()
monkeypatch.setattr(discovery_router, "MAX_IDENTIFY_ATTEMPTS_PER_USER", 3)
async def _fake_identify_hit(path):
return [{"title": "Song", "artist": "Artist", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
for _ in range(3):
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 200
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 429
def test_discovery_listen_rate_limit_is_per_user(client, auth_as, monkeypatch):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
monkeypatch.setattr(discovery_router, "MAX_IDENTIFY_ATTEMPTS_PER_USER", 2)
async def _fake_identify_hit(path):
return [{"title": "Song", "artist": "Artist", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
for _ in range(2):
client.post("/discovery/listen", headers=headers_a, files={"file": _dummy_audio_file()})
limited = client.post("/discovery/listen", headers=headers_a, files={"file": _dummy_audio_file()})
assert limited.status_code == 429
# A different user hitting their own limit for the first time isn't affected by user A's.
response = client.post("/discovery/listen", headers=headers_b, files={"file": _dummy_audio_file()})
assert response.status_code == 200
def test_discovery_swipe_success_updates_liked(client, db_session, auth_as): def test_discovery_swipe_success_updates_liked(client, db_session, auth_as):
headers, user = auth_as() headers, user = auth_as()
song = DiscoveredSong(user_id=user.id, title="Swipe Me", artist="Someone", genre="Rock") song = DiscoveredSong(user_id=user.id, title="Swipe Me", artist="Someone", genre="Rock")
......
...@@ -250,3 +250,112 @@ def test_playlist_add_song_not_found(client, auth_as): ...@@ -250,3 +250,112 @@ def test_playlist_add_song_not_found(client, auth_as):
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": 99999}, headers=headers) response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404 assert response.status_code == 404
# --- delete endpoints ---
def test_delete_library_song_removes_the_row_and_file(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
response = client.delete(f"/library/{song.id}", headers=headers)
assert response.status_code == 200
assert response.json()["status"] == "success"
assert db_session.query(LibrarySong).filter(LibrarySong.id == song.id).first() is None
assert not os.path.exists(path)
def test_delete_library_song_also_removes_it_from_any_playlists(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
playlist_id = client.post("/playlists", json={"name": "Has The Song"}, headers=headers).json()["playlist"]["id"]
client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers)
response = client.delete(f"/library/{song.id}", headers=headers)
assert response.status_code == 200
assert db_session.query(PlaylistTrack).filter(PlaylistTrack.song_id == song.id).first() is None
finally:
if os.path.exists(path):
os.remove(path)
def test_delete_library_song_404_for_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.delete("/library/999999", headers=headers)
assert response.status_code == 404
def test_delete_library_song_404_for_another_users_song(client, db_session, auth_as):
_, owner = auth_as()
song, path = _make_library_song(db_session, owner.id)
try:
headers, _ = auth_as()
response = client.delete(f"/library/{song.id}", headers=headers)
assert response.status_code == 404
assert os.path.exists(path) # never touched - the delete never ran
finally:
os.remove(path)
def test_delete_playlist_removes_it_and_its_tracks(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id)
playlist_id = client.post("/playlists", json={"name": "Temporary"}, headers=headers).json()["playlist"]["id"]
client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers)
response = client.delete(f"/playlists/{playlist_id}", headers=headers)
assert response.status_code == 200
assert db_session.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).first() is None
get_response = client.get(f"/playlists/{playlist_id}", headers=headers)
assert get_response.status_code == 404
def test_delete_playlist_404_for_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.delete("/playlists/999999", headers=headers)
assert response.status_code == 404
def test_delete_playlist_404_for_another_users_playlist(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
playlist_id = client.post("/playlists", json={"name": "Not Yours"}, headers=headers_a).json()["playlist"]["id"]
response = client.delete(f"/playlists/{playlist_id}", headers=headers_b)
assert response.status_code == 404
def test_remove_track_from_playlist(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id)
playlist_id = client.post("/playlists", json={"name": "Trim Me"}, headers=headers).json()["playlist"]["id"]
client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers)
response = client.delete(f"/playlists/{playlist_id}/tracks/{song.id}", headers=headers)
assert response.status_code == 200
detail = client.get(f"/playlists/{playlist_id}", headers=headers).json()
assert detail["tracks"] == []
def test_remove_track_not_in_playlist_404s(client, auth_as):
headers, _ = auth_as()
playlist_id = client.post("/playlists", json={"name": "Empty"}, headers=headers).json()["playlist"]["id"]
response = client.delete(f"/playlists/{playlist_id}/tracks/999999", headers=headers)
assert response.status_code == 404
def test_remove_track_from_another_users_playlist_404s(client, db_session, auth_as):
headers_a, user_a = auth_as()
song = _add_song(db_session, user_a.id)
playlist_id = client.post("/playlists", json={"name": "Owner Only"}, headers=headers_a).json()["playlist"]["id"]
client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers_a)
headers_b, _ = auth_as()
response = client.delete(f"/playlists/{playlist_id}/tracks/{song.id}", headers=headers_b)
assert response.status_code == 404
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