Commit b36805a8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add confidence scores and community-review gating for identified songs

Identified songs now carry a 0-100 confidence score. Accepting the
system's identification needs no action; editing title/artist/album/
genre instead flips the song to review_status "pending" ("community
noted") - it stays fully visible and playable in the uploader's own
library immediately, but is withheld from the shared library/Home feed
for everyone else until a super admin approves or rejects it via the
new review-queue endpoints. Also stops hitting Gemini when Shazam/
AcoustID already found a real match, bounds Gemini's own request
timeout, and fixes a dead lyrics-fetch guard that was wasting calls on
blank queries.
parent 4b5c72cd
Pipeline #1281 failed with stage
...@@ -10,6 +10,8 @@ venv/ ...@@ -10,6 +10,8 @@ venv/
# Runtime data # Runtime data
*.db *.db
*.db-shm
*.db-wal
*.log *.log
var/ var/
......
"""add confidence and review_status to library_songs
Revision ID: 0323f5b7b4a9
Revises: 0c9ff986c2e6
Create Date: 2026-11-22 13:33:39.054831
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '0323f5b7b4a9'
down_revision: Union[str, Sequence[str], None] = '0c9ff986c2e6'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.add_column('library_songs', sa.Column('confidence', sa.Float(), nullable=True))
# server_default so existing rows backfill to "approved" (the model's default= is ORM-side
# only, for new inserts - this column is NOT NULL, so the add itself needs a real default to
# satisfy every row that already exists).
op.add_column('library_songs', sa.Column('review_status', sa.String(), nullable=False, server_default='approved'))
op.create_index(op.f('ix_library_songs_review_status'), 'library_songs', ['review_status'], unique=False)
op.add_column('identified_tracks', sa.Column('confidence', sa.Float(), nullable=True))
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('identified_tracks', 'confidence')
op.drop_index(op.f('ix_library_songs_review_status'), table_name='library_songs')
op.drop_column('library_songs', 'review_status')
op.drop_column('library_songs', 'confidence')
...@@ -43,7 +43,7 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g ...@@ -43,7 +43,7 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g
try: try:
candidates = await identify_audio(temp_path) candidates = await identify_audio(temp_path)
if not candidates: if not candidates:
return {"status": "error", "message": "No music detected"} return {"status": "error", "message": "We could not detect this song"}
candidate = candidates[0] candidate = candidates[0]
......
...@@ -60,7 +60,17 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe ...@@ -60,7 +60,17 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
recommendation algorithm yet.""" recommendation algorithm yet."""
liked_ids = liked_song_ids(db, current_user.id) liked_ids = liked_song_ids(db, current_user.id)
latest_pool = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).limit(POOL_SIZE).all() # review_status == "approved" excludes anything a user edited away from the system's own
# identification (see LibrarySong.review_status) - Home is the shared/public view, so a
# community-noted song stays out of it for everyone (including its own uploader browsing
# Home) until a super admin reviews it, even though it's fully visible in their own Library.
latest_pool = (
db.query(LibrarySong)
.filter(LibrarySong.review_status == "approved")
.order_by(LibrarySong.added_at.desc())
.limit(POOL_SIZE)
.all()
)
seen_identities: set[tuple[str, str]] = set() seen_identities: set[tuple[str, str]] = set()
latest_songs: list[LibrarySong] = [] latest_songs: list[LibrarySong] = []
for song in latest_pool: for song in latest_pool:
...@@ -78,7 +88,11 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe ...@@ -78,7 +88,11 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
# album is always one real person's actual upload, start to finish). # album is always one real person's actual upload, start to finish).
albums_pool = ( albums_pool = (
db.query(LibrarySong) db.query(LibrarySong)
.filter(LibrarySong.album.isnot(None), LibrarySong.album != "") .filter(
LibrarySong.album.isnot(None),
LibrarySong.album != "",
LibrarySong.review_status == "approved",
)
.order_by(LibrarySong.added_at.desc()) .order_by(LibrarySong.added_at.desc())
.limit(POOL_SIZE) .limit(POOL_SIZE)
.all() .all()
...@@ -150,7 +164,9 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe ...@@ -150,7 +164,9 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
candidates = [] candidates = []
seen_suggestion_identities: set[tuple[str, str]] = set() seen_suggestion_identities: set[tuple[str, str]] = set()
for s in db.query(LibrarySong).filter(LibrarySong.user_id != current_user.id).all(): for s in db.query(LibrarySong).filter(
LibrarySong.user_id != current_user.id, LibrarySong.review_status == "approved"
).all():
if s.id in already_shown_ids: if s.id in already_shown_ids:
continue continue
key = _identity_key(s.title, s.artist) key = _identity_key(s.title, s.artist)
......
import difflib import difflib
import json import json
import os import os
from datetime import datetime, timezone
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Form, Request from fastapi import APIRouter, Depends, HTTPException, Form, Request
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy import or_ from sqlalchemy import or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
from src.core.security import get_current_user, get_current_user_for_stream from src.core.security import get_current_super_admin, get_current_user, get_current_user_for_stream
from src.services.shared_library import give_from_shared_library from src.services.shared_library import give_from_shared_library
from src.services.favorites import liked_song_ids from src.services.favorites import liked_song_ids
from src.services.media_stream import stream_audio_file from src.services.media_stream import stream_audio_file
...@@ -115,6 +117,8 @@ def _serialize_song(song: LibrarySong, liked_song_ids: set[int]) -> dict: ...@@ -115,6 +117,8 @@ def _serialize_song(song: LibrarySong, liked_song_ids: set[int]) -> dict:
"file_path": song.file_path, "file_path": song.file_path,
"added_at": song.added_at, "added_at": song.added_at,
"is_liked": song.id in liked_song_ids, "is_liked": song.id in liked_song_ids,
"confidence": song.confidence,
"review_status": song.review_status,
} }
...@@ -242,6 +246,109 @@ async def delete_library_song(file_id: int, db: Session = Depends(get_db), curre ...@@ -242,6 +246,109 @@ async def delete_library_song(file_id: int, db: Session = Depends(get_db), curre
db.commit() db.commit()
return {"status": "success"} return {"status": "success"}
class LibrarySongEditRequest(BaseModel):
title: Optional[str] = None
artist: Optional[str] = None
album: Optional[str] = None
genre: Optional[str] = None
coverart: Optional[str] = None
@router.patch("/library/{file_id}")
async def edit_library_song(
file_id: int,
body: LibrarySongEditRequest,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Lets the uploader correct what the identification pipeline found - only ever called when
they're diverging from the system's own guess (accepting it as-is needs no call at all, see
Upload.tsx). Any edit here means the song is no longer "what the system identified": it
flips to review_status="pending" ("community noted" in product terms) immediately, taking it
out of the shared library pool (search_shared_library, shared_library.find_library_match,
Home's feed queries) for everyone else until a super admin reviews it in the admin panel's
queue below - but it stays fully visible and playable in the uploader's *own* library right
away regardless, since every one of those gating queries scopes to other users' rows, never
the owner's own via get_library/get_album/etc."""
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")
for field in ("title", "artist", "album", "genre", "coverart"):
value = getattr(body, field)
if value is not None:
setattr(song, field, value)
song.review_status = "pending"
db.commit()
db.refresh(song)
liked_ids = liked_song_ids(db, current_user.id)
return {"status": "success", "song": _serialize_song(song, liked_ids)}
def _serialize_review_item(song: LibrarySong) -> dict:
return {
"id": song.id,
"user_id": song.user_id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"genre": song.genre,
"coverart": song.coverart,
"confidence": song.confidence,
"review_status": song.review_status,
"added_at": song.added_at,
}
@router.get("/library/admin/review-queue")
async def get_library_review_queue(
status: str = "pending",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
"""Songs a user edited away from the system's own identification - see edit_library_song's
docstring for why that flips review_status. Global, not per-business (unlike soundmarks'
own suggestion queue) - a community-noted song isn't tied to any particular business owner,
it's the shared library as a whole that's affected."""
songs = (
db.query(LibrarySong)
.filter(LibrarySong.review_status == status)
.order_by(LibrarySong.added_at.desc())
.all()
)
return {"status": "success", "songs": [_serialize_review_item(s) for s in songs]}
@router.post("/library/admin/review-queue/{song_id}/approve")
async def approve_library_review(
song_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
if song.review_status != "pending":
raise HTTPException(status_code=400, detail="This song has already been reviewed")
song.review_status = "approved"
db.commit()
db.refresh(song)
return {"status": "success", "song": _serialize_review_item(song)}
@router.post("/library/admin/review-queue/{song_id}/reject")
async def reject_library_review(
song_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
if song.review_status != "pending":
raise HTTPException(status_code=400, detail="This song has already been reviewed")
song.review_status = "rejected"
db.commit()
db.refresh(song)
return {"status": "success", "song": _serialize_review_item(song)}
@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()
...@@ -369,14 +476,19 @@ async def search_shared_library(query: str = Form(...), db: Session = Depends(ge ...@@ -369,14 +476,19 @@ async def search_shared_library(query: str = Form(...), db: Session = Depends(ge
if mood_genres: if mood_genres:
match_filters.append(LibrarySong.genre.in_(mood_genres)) match_filters.append(LibrarySong.genre.in_(mood_genres))
# Excludes anything not yet approved (see LibrarySong.review_status) - a song someone
# community-noted away from the system's identification shouldn't surface to a stranger as
# a confirmed match, same reasoning as find_library_match's own user_id=None branch.
if match_filters: if match_filters:
matches_query = db.query(LibrarySong).filter(or_(*match_filters)) matches_query = db.query(LibrarySong).filter(LibrarySong.review_status == "approved", or_(*match_filters))
matches = (matches_query.order_by(LibrarySong.added_at.desc()) if recency else matches_query).all() matches = (matches_query.order_by(LibrarySong.added_at.desc()) if recency else matches_query).all()
else: else:
matches = [] matches = []
if not matches: if not matches:
matches = _fuzzy_match_songs(db.query(LibrarySong).all(), query) matches = _fuzzy_match_songs(
db.query(LibrarySong).filter(LibrarySong.review_status == "approved").all(), query
)
own_keys = { own_keys = {
(s.title.strip().lower(), s.artist.strip().lower()) (s.title.strip().lower(), s.artist.strip().lower())
......
...@@ -86,6 +86,8 @@ async def _identify_tag_and_store( ...@@ -86,6 +86,8 @@ async def _identify_tag_and_store(
"lyrics": existing_song.lyrics, "lyrics": existing_song.lyrics,
"synced_lyrics": json.loads(existing_song.synced_lyrics) if existing_song.synced_lyrics else None, "synced_lyrics": json.loads(existing_song.synced_lyrics) if existing_song.synced_lyrics else None,
"cover_art": existing_song.coverart, "cover_art": existing_song.coverart,
"confidence": existing_song.confidence,
"review_status": existing_song.review_status,
}, },
} }
...@@ -100,6 +102,7 @@ async def _identify_tag_and_store( ...@@ -100,6 +102,7 @@ async def _identify_tag_and_store(
'year': cached.year, 'genre': cached.genre, 'track_number': cached.track_number, 'year': cached.year, 'genre': cached.genre, 'track_number': cached.track_number,
'source': cached.source, 'coverart': cached.coverart, 'lyrics': cached.lyrics, 'source': cached.source, 'coverart': cached.coverart, 'lyrics': cached.lyrics,
'synced_lyrics': json.loads(cached.synced_lyrics) if cached.synced_lyrics else None, 'synced_lyrics': json.loads(cached.synced_lyrics) if cached.synced_lyrics else None,
'confidence': cached.confidence,
} }
else: else:
candidates = await identify_audio(raw_file_path) candidates = await identify_audio(raw_file_path)
...@@ -124,13 +127,23 @@ async def _identify_tag_and_store( ...@@ -124,13 +127,23 @@ async def _identify_tag_and_store(
candidate["lyrics"] = lyrics_result["lyrics"] candidate["lyrics"] = lyrics_result["lyrics"]
candidate["synced_lyrics"] = None candidate["synced_lyrics"] = None
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre": # Gemini is an absolute last resort - reserved for identifying the song itself when
# Shazam/AcoustID both come up empty (see the `if not candidate` branch above). A
# confident Shazam/AcoustID match that merely lacks genre metadata must NOT also spend
# a Gemini call just to backfill that one field - it shares the same per-minute quota
# as real identification, and a found song's genre is a nice-to-have, not worth
# starving the fallback path that's actually needed for songs nothing else can match.
source = candidate.get("source")
genre_missing = not candidate.get("genre") or candidate.get("genre") == "Unknown Genre"
if genre_missing and source not in ("Shazam", "AcoustID"):
title, artist = candidate.get("title", ""), candidate.get("artist", "") title, artist = candidate.get("title", ""), candidate.get("artist", "")
if title and artist and title != "Unknown" and artist != "Unknown": if title and artist and title != "Unknown" and artist != "Unknown":
try: try:
model = genai.GenerativeModel('gemini-3.7-flash') model = genai.GenerativeModel('gemini-3.7-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text." prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
response = await asyncio.to_thread(model.generate_content, prompt) response = await asyncio.to_thread(
model.generate_content, prompt, request_options={"timeout": 15}
)
raw_text = response.text.strip() raw_text = response.text.strip()
if "\n" in raw_text: if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1] candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
...@@ -152,6 +165,7 @@ async def _identify_tag_and_store( ...@@ -152,6 +165,7 @@ async def _identify_tag_and_store(
coverart=candidate.get('coverart', ''), coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''), lyrics=candidate.get('lyrics', ''),
synced_lyrics=json.dumps(candidate['synced_lyrics']) if candidate.get('synced_lyrics') else None, synced_lyrics=json.dumps(candidate['synced_lyrics']) if candidate.get('synced_lyrics') else None,
confidence=candidate.get('confidence'),
)) ))
try: try:
db.commit() db.commit()
...@@ -180,6 +194,7 @@ async def _identify_tag_and_store( ...@@ -180,6 +194,7 @@ async def _identify_tag_and_store(
file_path=final_path, file_path=final_path,
fingerprint=fingerprint, fingerprint=fingerprint,
duration_seconds=probe_duration_seconds(final_path), duration_seconds=probe_duration_seconds(final_path),
confidence=candidate.get('confidence'),
) )
db.add(library_song) db.add(library_song)
db.commit() db.commit()
...@@ -199,6 +214,8 @@ async def _identify_tag_and_store( ...@@ -199,6 +214,8 @@ async def _identify_tag_and_store(
"lyrics": library_song.lyrics, "lyrics": library_song.lyrics,
"synced_lyrics": json.loads(library_song.synced_lyrics) if library_song.synced_lyrics else None, "synced_lyrics": json.loads(library_song.synced_lyrics) if library_song.synced_lyrics else None,
"cover_art": library_song.coverart, "cover_art": library_song.coverart,
"confidence": library_song.confidence,
"review_status": library_song.review_status,
}, },
} }
finally: finally:
......
...@@ -150,6 +150,20 @@ class LibrarySong(Base): ...@@ -150,6 +150,20 @@ class LibrarySong(Base):
# rows are lazily backfilled on first read by Radio's own now-playing computation, the # rows are lazily backfilled on first read by Radio's own now-playing computation, the
# closest honest analog to a server_default backfill for a value that can't have one. # closest honest analog to a server_default backfill for a value that can't have one.
duration_seconds = Column(Float, nullable=True) duration_seconds = Column(Float, nullable=True)
# 0-100, how confident the identification pipeline was (Shazam: fixed 95, since a hit is a
# real fingerprint match not a fuzzy guess; AcoustID: the match's own score*100; Gemini: null,
# a transcription-based guess has no comparable score - see identify_audio/
# identify_with_gemini in music_identification.py). Null for manually-entered/claimed/remixed
# rows with no identification step of their own.
confidence = Column(Float, nullable=True)
# "approved" (default - the system's own identification, shown in the shared library/Home
# feed to everyone) vs "pending" (the uploader edited the identified title/artist/album/
# genre/cover themselves, diverging from what the system found - stays visible in *their own*
# library immediately, per product direction, but withheld from the shared pool until a
# super admin reviews it in AdminPanel) vs "rejected" (reviewed and declined - stays private
# to the uploader only, same as "pending" from everyone else's point of view). A row never
# starts "rejected"; only an admin review can set it.
review_status = Column(String, default="approved", index=True, nullable=False)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base): class Playlist(Base):
...@@ -374,6 +388,10 @@ class IdentifiedTrack(Base): ...@@ -374,6 +388,10 @@ class IdentifiedTrack(Base):
coverart = Column(String) coverart = Column(String)
lyrics = Column(String) lyrics = Column(String)
synced_lyrics = Column(String, nullable=True) # same JSON-encoded [[seconds, text], ...] shape as LibrarySong synced_lyrics = Column(String, nullable=True) # same JSON-encoded [[seconds, text], ...] shape as LibrarySong
# Same 0-100 meaning as LibrarySong.confidence - cached here too so a second upload of the
# same recording (identified by someone else first) carries forward the same score instead
# of silently losing it just because this particular upload skipped re-running identification.
confidence = Column(Float, nullable=True)
identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Correction(Base): class Correction(Base):
......
...@@ -135,7 +135,15 @@ async def identify_with_gemini(file_path: str, lang_pref: str) -> dict: ...@@ -135,7 +135,15 @@ async def identify_with_gemini(file_path: str, lang_pref: str) -> dict:
"data": audio_data "data": audio_data
} }
response = await asyncio.to_thread(model.generate_content, [audio_part, prompt]) # The SDK's default retry policy backs off repeatedly on a 429 (rate limit) before
# finally raising - observed taking 40+ seconds on this free-tier key (5 req/min) for a
# single failed call. This is the last-resort identification path precisely because
# Shazam/AcoustID already failed, so the user is already waiting on it - fail fast
# instead of silently burning most of a minute retrying a quota that won't recover
# within the request's lifetime anyway.
response = await asyncio.to_thread(
model.generate_content, [audio_part, prompt], request_options={"timeout": 15}
)
data = json.loads(response.text) data = json.loads(response.text)
...@@ -193,7 +201,13 @@ async def fetch_lyrics(title: str, artist: str) -> dict: ...@@ -193,7 +201,13 @@ async def fetch_lyrics(title: str, artist: str) -> dict:
falls back to whatever plain lyrics exist if no synced version is available anywhere. falls back to whatever plain lyrics exist if no synced version is available anywhere.
Returns {"lyrics": str | None, "synced_lyrics": [[seconds, text], ...] | None} - lyrics is Returns {"lyrics": str | None, "synced_lyrics": [[seconds, text], ...] | None} - lyrics is
derived from the parsed synced text when synced data was found, so the two never disagree.""" derived from the parsed synced text when synced data was found, so the two never disagree."""
if title == 'Unknown Title': # 'Unknown Title' is telegram_sync.py's own sentinel for an untitled Telegram audio message -
# a real case this guard must still catch. But music.py's upload/tag path instead calls this
# with candidate.get("title", "") (empty string, not that literal sentinel) whenever Shazam/
# AcoustID/Gemini all failed to identify anything - the old check missed that case entirely,
# letting a blank/near-blank query waste two full syncedlyrics.search round trips searching
# for a result that was already known to be unfindable.
if not title or title in ('Unknown Title', 'Unknown'):
return {"lyrics": None, "synced_lyrics": None} return {"lyrics": None, "synced_lyrics": None}
search_term = f"{title} {artist}" search_term = f"{title} {artist}"
......
...@@ -6,13 +6,19 @@ from src.core.database import LibrarySong, User ...@@ -6,13 +6,19 @@ from src.core.database import LibrarySong, User
def find_library_match(db: Session, title: str, artist: str, user_id: int | None = None) -> LibrarySong | None: def find_library_match(db: Session, title: str, artist: str, user_id: int | None = None) -> LibrarySong | None:
"""Case/whitespace-insensitive title+artist lookup - scoped to one user's library if """Case/whitespace-insensitive title+artist lookup - scoped to one user's library if
user_id is given, otherwise searched across every user's library.""" user_id is given, otherwise searched across every user's library. The global search
(user_id=None) excludes anything not yet approved (see LibrarySong.review_status) - a song
someone community-noted away from the system's identification shouldn't be handed to a
stranger as if it were a confirmed match. Scoped lookups (a real user_id) never filter by
this - the owner always has full access to their own rows regardless of review state."""
query = db.query(LibrarySong).filter( query = db.query(LibrarySong).filter(
func.lower(func.trim(LibrarySong.title)) == title.strip().lower(), func.lower(func.trim(LibrarySong.title)) == title.strip().lower(),
func.lower(func.trim(LibrarySong.artist)) == artist.strip().lower(), func.lower(func.trim(LibrarySong.artist)) == artist.strip().lower(),
) )
if user_id is not None: if user_id is not None:
query = query.filter(LibrarySong.user_id == user_id) query = query.filter(LibrarySong.user_id == user_id)
else:
query = query.filter(LibrarySong.review_status == "approved")
return query.first() return query.first()
......
...@@ -194,3 +194,22 @@ def test_suggestions_is_capped_at_eight(client, db_session, auth_as): ...@@ -194,3 +194,22 @@ def test_suggestions_is_capped_at_eight(client, db_session, auth_as):
response = client.get("/home/feed", headers=headers) response = client.get("/home/feed", headers=headers)
assert len(response.json()["suggestions"]) <= 8 assert len(response.json()["suggestions"]) <= 8
def test_pending_review_songs_excluded_from_every_feed_section(client, db_session, auth_as):
# Home is the shared/public view - a song its own uploader community-noted away from the
# system's identification should stay out of it for everyone, including that uploader
# themselves browsing Home, until a super admin reviews it (see LibrarySong.review_status).
headers, viewer = auth_as()
_, owner = auth_as()
song = _add_song(
db_session, owner.id, title="Community Noted Unique Pqr", artist="Noted Band", album="Noted Album Unique"
)
song.review_status = "pending"
db_session.commit()
response = client.get("/home/feed", headers=headers)
body = response.json()
assert not any(s["title"] == "Community Noted Unique Pqr" for s in body["latest_songs"])
assert not any(a["album"] == "Noted Album Unique" for a in body["new_albums"])
assert not any(s["title"] == "Community Noted Unique Pqr" for s in body["suggestions"])
...@@ -811,3 +811,144 @@ def test_is_liked_false_by_default_for_an_unfavorited_song(client, db_session, a ...@@ -811,3 +811,144 @@ def test_is_liked_false_by_default_for_an_unfavorited_song(client, db_session, a
library = client.get("/library", headers=headers).json()["library"] library = client.get("/library", headers=headers).json()["library"]
assert next(s for s in library if s["id"] == song.id)["is_liked"] is False assert next(s for s in library if s["id"] == song.id)["is_liked"] is False
def test_new_song_defaults_to_approved_review_status(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Fresh Tag")
library = client.get("/library", headers=headers).json()["library"]
row = next(s for s in library if s["id"] == song.id)
assert row["review_status"] == "approved"
assert row["confidence"] is None
def test_edit_library_song_requires_auth(client, db_session, auth_as):
_, user = auth_as()
song = _add_song(db_session, user.id)
response = client.patch(f"/library/{song.id}", json={"title": "New Title"})
assert response.status_code == 401
def test_edit_library_song_updates_fields_and_flips_to_pending(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Correctable Song", artist="Original Artist")
response = client.patch(
f"/library/{song.id}", json={"title": "Corrected Title", "artist": "Corrected Artist"}, headers=headers
)
assert response.status_code == 200
body = response.json()["song"]
assert body["title"] == "Corrected Title"
assert body["artist"] == "Corrected Artist"
assert body["review_status"] == "pending"
def test_edit_library_song_partial_update_leaves_other_fields_alone(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id, title="Keep My Artist", artist="Stays The Same")
response = client.patch(f"/library/{song.id}", json={"album": "New Album"}, headers=headers)
body = response.json()["song"]
assert body["title"] == "Keep My Artist"
assert body["artist"] == "Stays The Same"
assert body["album"] == "New Album"
def test_edit_library_song_404_for_another_users_song(client, db_session, auth_as):
headers, _ = auth_as()
_, owner = auth_as()
song = _add_song(db_session, owner.id)
response = client.patch(f"/library/{song.id}", json={"title": "Hijacked"}, headers=headers)
assert response.status_code == 404
def test_shared_search_excludes_pending_community_noted_songs(client, db_session, auth_as):
headers, searcher = auth_as()
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="Communitynoted Melody", artist="Communitynoted")
song.review_status = "pending"
db_session.commit()
response = client.post("/library/shared/search", data={"query": "Communitynoted"}, headers=headers)
titles = [s["title"] for s in response.json()["songs"]]
assert "Communitynoted Melody" not in titles
def test_claim_shared_song_does_not_hand_out_a_pending_song(client, db_session, auth_as):
headers, searcher = auth_as()
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="Notyetreviewed Track", artist="Notyetreviewed")
song.review_status = "pending"
db_session.commit()
response = client.post(
"/library/shared/claim", data={"title": "Notyetreviewed Track", "artist": "Notyetreviewed"}, headers=headers
)
assert response.status_code == 404
def test_review_queue_requires_super_admin(client, db_session, auth_as):
headers, user = auth_as()
song = _add_song(db_session, user.id)
song.review_status = "pending"
db_session.commit()
response = client.get("/library/admin/review-queue", headers=headers)
assert response.status_code == 403
def test_review_queue_lists_pending_songs(client, db_session, auth_as):
admin_headers, _ = auth_as(role="super_admin")
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="Queued For Review")
song.review_status = "pending"
db_session.commit()
response = client.get("/library/admin/review-queue", headers=admin_headers)
assert response.status_code == 200
titles = [s["title"] for s in response.json()["songs"]]
assert "Queued For Review" in titles
def test_approve_review_sets_approved_and_is_idempotent_guarded(client, db_session, auth_as):
admin_headers, _ = auth_as(role="super_admin")
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="To Be Approved")
song.review_status = "pending"
db_session.commit()
response = client.post(f"/library/admin/review-queue/{song.id}/approve", headers=admin_headers)
assert response.status_code == 200
assert response.json()["song"]["review_status"] == "approved"
again = client.post(f"/library/admin/review-queue/{song.id}/approve", headers=admin_headers)
assert again.status_code == 400
def test_reject_review_sets_rejected(client, db_session, auth_as):
admin_headers, _ = auth_as(role="super_admin")
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="To Be Rejected")
song.review_status = "pending"
db_session.commit()
response = client.post(f"/library/admin/review-queue/{song.id}/reject", headers=admin_headers)
assert response.status_code == 200
assert response.json()["song"]["review_status"] == "rejected"
def test_approved_song_after_review_reappears_in_shared_search(client, db_session, auth_as):
admin_headers, _ = auth_as(role="super_admin")
headers, searcher = auth_as()
_, owner = auth_as()
song = _add_song(db_session, owner.id, title="Reinstated Anthem", artist="Reinstated")
song.review_status = "pending"
db_session.commit()
client.post(f"/library/admin/review-queue/{song.id}/approve", headers=admin_headers)
response = client.post("/library/shared/search", data={"query": "Reinstated"}, headers=headers)
titles = [s["title"] for s in response.json()["songs"]]
assert "Reinstated Anthem" in titles
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