Commit fc4b4352 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add guest browsing, onboarding profile fields, and a background job pipeline for uploads

Home and Discovery now serve anonymous callers (get_current_user_optional)
so unauthenticated visitors can browse and identify songs - Discovery's
rate limiter keys off IP instead of user_id for guests, and the
save/claim step is skipped entirely since there's no account to attach it
to. UserProfile gains display_name/preferred_genres for the new 4-page
onboarding (replacing the old 6-step tour), plus PATCH /auth/profile and
POST /auth/profile/avatar to save them.

POST /music/upload no longer blocks on the full identify/tag pipeline -
it saves the file, creates an UploadJob, and hands identify/tag off to a
BackgroundTasks job (mirroring RemixJob/ChatScanJob), returning
{job_id, status} immediately. This is what lets the frontend upload
several files concurrently instead of queuing each one behind the last,
and what lets tagging keep running after the uploading tab closes - GET
/music/upload/jobs is how the client finds out the result, including
reconciling after a reload.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 77eff0b8
Pipeline #1296 failed with stage
"""guest discovery rate limiting, user profile fields, upload jobs
Revision ID: 499ebec0825d
Revises: 20a199643cc2
Create Date: 2026-11-24 08:53:20.645240
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '499ebec0825d'
down_revision: Union[str, Sequence[str], None] = '20a199643cc2'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.create_table('upload_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('original_filename', sa.String(), nullable=True),
sa.Column('status', sa.String(), nullable=True),
sa.Column('result_song_id', sa.Integer(), nullable=True),
sa.Column('error', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['result_song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_upload_jobs_id'), 'upload_jobs', ['id'], unique=False)
op.create_index(op.f('ix_upload_jobs_user_id'), 'upload_jobs', ['user_id'], unique=False)
# Discovery is now guest-accessible (see get_current_user_optional) - an anonymous
# caller's attempt row has no user_id, only ip_address, so user_id must become nullable.
# batch_alter_table for SQLite-safety (plain ALTER COLUMN isn't supported there), works
# unchanged on Postgres too.
with op.batch_alter_table('discovery_attempts') as batch_op:
batch_op.alter_column('user_id', existing_type=sa.Integer(), nullable=True)
op.add_column('discovery_attempts', sa.Column('ip_address', sa.String(), nullable=True))
op.create_index(op.f('ix_discovery_attempts_ip_address'), 'discovery_attempts', ['ip_address'], unique=False)
op.add_column('user_profiles', sa.Column('display_name', sa.String(), nullable=True))
op.add_column('user_profiles', sa.Column('preferred_genres', sa.String(), nullable=True))
# Autogenerate also proposed creating FKs on auth_attempts.room_id/user_id and
# remix_jobs.user_id - pre-existing SQLite-reflection drift unrelated to this change
# (those columns already exist with no real FK in SQLite's own schema), not something
# this migration should touch. Stripped, same as every prior migration's autogenerate
# output in this repo.
def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('user_profiles', 'preferred_genres')
op.drop_column('user_profiles', 'display_name')
op.drop_index(op.f('ix_discovery_attempts_ip_address'), table_name='discovery_attempts')
op.drop_column('discovery_attempts', 'ip_address')
with op.batch_alter_table('discovery_attempts') as batch_op:
batch_op.alter_column('user_id', existing_type=sa.Integer(), nullable=False)
op.drop_index(op.f('ix_upload_jobs_user_id'), table_name='upload_jobs')
op.drop_index(op.f('ix_upload_jobs_id'), table_name='upload_jobs')
op.drop_table('upload_jobs')
import json
import uuid
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
......@@ -95,6 +96,14 @@ class PrivacyUpdateReq(BaseModel):
allow_direct_messages: bool | None = None
class ProfileUpdateReq(BaseModel):
"""Partial update, same idiom as PrivacyUpdateReq - set by the new 4-page onboarding
(OnboardingOverlay.tsx), but not exclusive to it; both fields stay editable later too.
Both skippable - onboarding is not a gate, a user can finish it having set neither."""
display_name: str | None = None
preferred_genres: list[str] | None = None
class TokenResponse(BaseModel):
access_token: str
refresh_token: str
......@@ -329,6 +338,11 @@ async def auth_me(db: Session = Depends(get_db), current_user: User = Depends(ge
"share_location_enabled": profile.share_location_enabled,
"allow_direct_messages": profile.allow_direct_messages,
},
"profile": {
"display_name": profile.display_name,
"avatar_url": profile.avatar_url,
"preferred_genres": json.loads(profile.preferred_genres) if profile.preferred_genres else [],
},
},
}
......@@ -367,6 +381,42 @@ async def update_privacy(
}
@router.patch("/profile")
async def update_profile(
req: ProfileUpdateReq, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
profile = _get_or_create_profile(db, current_user.id)
if req.display_name is not None:
profile.display_name = req.display_name.strip() or None
if req.preferred_genres is not None:
profile.preferred_genres = json.dumps(req.preferred_genres) if req.preferred_genres else None
db.commit()
db.refresh(profile)
return {
"status": "success",
"profile": {
"display_name": profile.display_name,
"avatar_url": profile.avatar_url,
"preferred_genres": json.loads(profile.preferred_genres) if profile.preferred_genres else [],
},
}
@router.post("/profile/avatar")
async def upload_avatar(
file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
if file.content_type not in storage.ALLOWED_IMAGE_TYPES:
raise HTTPException(status_code=422, detail=f"Avatar must be one of {sorted(storage.ALLOWED_IMAGE_TYPES)}")
data = await file.read()
if len(data) > storage.MAX_IMAGE_BYTES:
raise HTTPException(status_code=422, detail=f"Avatar must be under {storage.MAX_IMAGE_BYTES} bytes")
profile = _get_or_create_profile(db, current_user.id)
profile.avatar_url = storage.store_image(current_user.id, data, storage.ALLOWED_IMAGE_TYPES[file.content_type])
db.commit()
return {"status": "success", "avatar_url": profile.avatar_url}
@router.get("/telegram/chats")
async def get_chats(current_user: User = Depends(get_current_user)):
if not current_user.telegram_session_string:
......
import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File, Form, status
from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone
from src.core.database import get_db, DiscoveredSong, DiscoveryAttempt, LibrarySong, User
from src.core.security import get_current_user
from src.core.security import get_current_user, get_current_user_optional
from src.services import storage
from src.services.music_identification import identify_audio
from src.services.shared_library import give_from_shared_library
......@@ -13,12 +13,15 @@ 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.
# abuse) into real API costs/quota exhaustion. Anonymous callers (guest browsing, see
# get_current_user_optional) get the same ceiling keyed by IP instead of user_id - no reason
# to let unauthenticated traffic have a *more* generous budget just because it's anonymous.
MAX_IDENTIFY_ATTEMPTS_PER_USER = 20
MAX_IDENTIFY_ATTEMPTS_PER_IP = 20
IDENTIFY_WINDOW = timedelta(minutes=10)
def _check_identify_rate_limit(db: Session, user_id: int):
def _check_identify_rate_limit_user(db: Session, user_id: int):
now = datetime.now(timezone.utc).replace(tzinfo=None)
count = (
db.query(DiscoveryAttempt)
......@@ -29,11 +32,37 @@ def _check_identify_rate_limit(db: Session, user_id: int):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later")
def _check_identify_rate_limit_ip(db: Session, ip: str):
now = datetime.now(timezone.utc).replace(tzinfo=None)
count = (
db.query(DiscoveryAttempt)
.filter(DiscoveryAttempt.ip_address == ip, DiscoveryAttempt.created_at >= now - IDENTIFY_WINDOW)
.count()
)
if count >= MAX_IDENTIFY_ATTEMPTS_PER_IP:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many identify requests, try again later")
@router.post("/listen")
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."""
_check_identify_rate_limit(db, current_user.id)
async def discovery_listen(
request: Request,
file: UploadFile = File(...),
db: Session = Depends(get_db),
current_user: User | None = Depends(get_current_user_optional),
):
"""Accepts a short audio snippet from the microphone to identify what's playing. Discovery
is one of the two guest-accessible pages (see get_current_user_optional) - the expensive
identify step itself runs identically for a guest, only the persistence/claim step
afterwards (saving a DiscoveredSong, giving the caller a library copy) requires an account
to attach it to, so that part is skipped entirely for an anonymous caller rather than
erroring."""
if current_user:
_check_identify_rate_limit_user(db, current_user.id)
db.add(DiscoveryAttempt(user_id=current_user.id))
else:
client_ip = request.client.host if request.client else "unknown"
_check_identify_rate_limit_ip(db, client_ip)
db.add(DiscoveryAttempt(ip_address=client_ip))
db.commit()
temp_path = storage.new_temp_path(file.filename)
......@@ -47,6 +76,9 @@ async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(g
candidate = candidates[0]
if not current_user:
return {"status": "success", "detected": candidate, "discovery_id": None, "library_song_id": None}
new_song = DiscoveredSong(
user_id=current_user.id,
title=candidate.get("title"),
......
......@@ -4,7 +4,7 @@ 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
from src.core.security import get_current_user_optional
from src.services.favorites import liked_song_ids
router = APIRouter(prefix="/home", tags=["Home"])
......@@ -50,15 +50,20 @@ def _serialize_global_song(song: LibrarySong, liked_ids: set[int]) -> dict:
@router.get("/feed")
async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
async def get_home_feed(db: Session = Depends(get_db), current_user: User | None = Depends(get_current_user_optional)):
"""The Home page's feed - everything here is global (every user's uploads), unlike the
per-user Library page. Every section is deduped by (title, artist) identity so the same
song/album tagged by multiple users shows once, not once per uploader - which uploader's
copy ends up representing it is an implementation detail (preferring the caller's own copy,
so tapping it plays/navigates directly rather than needing a claim first), not shown to the
viewer. `suggestions` is explicitly a placeholder (see its own comment below), not a real
recommendation algorithm yet."""
liked_ids = liked_song_ids(db, current_user.id)
recommendation algorithm yet.
current_user is None for an anonymous guest (Home is one of the two guest-accessible pages,
see get_current_user_optional) - every "is this mine" personalization below degrades to its
existing non-personalized fallback in that case rather than needing a separate guest branch:
no liked songs, no "my copy wins" album tie-break, no genre-biased suggestions."""
liked_ids = liked_song_ids(db, current_user.id) if current_user else set()
# 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
......@@ -130,8 +135,8 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
if existing is None:
albums_by_identity[key] = entry
continue
existing_is_mine = existing["user_id"] == current_user.id
entry_is_mine = entry["user_id"] == current_user.id
existing_is_mine = current_user is not None and existing["user_id"] == current_user.id
entry_is_mine = current_user is not None and entry["user_id"] == current_user.id
if entry_is_mine and not existing_is_mine:
albums_by_identity[key] = entry
elif entry_is_mine == existing_is_mine and entry["latest_added_at"] > existing["latest_added_at"]:
......@@ -160,13 +165,15 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
own_keys = {
key for s in db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id)
if (key := _identity_key(s.title, s.artist))
}
} if current_user else set()
candidates_query = db.query(LibrarySong).filter(LibrarySong.review_status == "approved")
if current_user:
candidates_query = candidates_query.filter(LibrarySong.user_id != current_user.id)
candidates = []
seen_suggestion_identities: set[tuple[str, str]] = set()
for s in db.query(LibrarySong).filter(
LibrarySong.user_id != current_user.id, LibrarySong.review_status == "approved"
).all():
for s in candidates_query.all():
if s.id in already_shown_ids:
continue
key = _identity_key(s.title, s.artist)
......@@ -177,7 +184,7 @@ async def get_home_feed(db: Session = Depends(get_db), current_user: User = Depe
own_genres = {
g for (g,) in db.query(LibrarySong.genre).filter(LibrarySong.user_id == current_user.id, LibrarySong.genre.isnot(None))
}
} if current_user else set()
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]
......
import asyncio
import json
import shutil
from datetime import datetime, timedelta, timezone
from typing import List
import google.generativeai as genai
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, UploadFile, File
from pydantic import BaseModel
from sqlalchemy.orm import Session
import src.telegram_worker.telegram_sync as telegram_sync
from src.core.config import AI_IDENTIFICATION_ENABLED, logger
from src.core.database import IdentifiedTrack, LibrarySong, User, get_db
from src.core.database import IdentifiedTrack, LibrarySong, SessionLocal, UploadJob, User, get_db
from src.core.security import get_current_user
from src.services import storage
from src.services.audio_processing import AudioDecodeError, probe_duration_seconds, tag_and_convert_audio
......@@ -270,22 +271,108 @@ async def batch_remix_status(job_id: str, current_user: User = Depends(get_curre
raise HTTPException(status_code=501, detail="AI remix isn't implemented yet")
@router.post("/upload", response_model=TagResponse)
async def _run_upload_job(job_id: int, user_id: int, temp_path: str):
"""Runs after POST /upload has already returned - identify/tag genuinely continues even
if the uploading tab has since been closed, which is the whole point of dispatching this
via BackgroundTasks instead of awaiting it inline. Opens its own session since the
request-scoped one is long gone by the time this runs, same pattern as
telegram_scan.py's _run_chat_scan and remix_engine.py's render_remix_sync."""
db = SessionLocal()
try:
job = db.query(UploadJob).filter(UploadJob.id == job_id).first()
if not job:
return
job.status = "processing"
db.commit()
user = db.query(User).filter(User.id == user_id).first()
try:
result = await _identify_tag_and_store(db, user, temp_path)
job.status = "done"
job.result_song_id = result["metadata"]["library_song_id"]
except AudioDecodeError:
job.status = "error"
job.error = "Couldn't process this audio file - it may be corrupted or in an unsupported format."
except Exception as e:
logger.exception(f"Upload job {job_id} failed")
job.status = "error"
job.error = str(e)[:500]
db.commit()
finally:
db.close()
@router.post("/upload")
async def upload_direct(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Saves the uploaded bytes, then hands identify/tag off to a background task and returns
immediately - letting the frontend upload several files concurrently (see
UploadQueueContext.tsx) instead of waiting out each one's full Shazam/AcoustID/lyrics/
artwork pipeline before starting the next, and letting that pipeline keep running after
the client disconnects. See GET /upload/jobs for how the frontend finds out the result."""
temp_path = storage.new_temp_path(file.filename)
with open(temp_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
result = await _identify_tag_and_store(db, current_user, temp_path)
except AudioDecodeError as e:
logger.error(f"Audio decode failed for user {current_user.id}'s upload: {e}")
raise HTTPException(status_code=422, detail="Couldn't process this audio file - it may be corrupted or in an unsupported format.")
except Exception:
logger.exception(f"Unexpected error tagging upload for user {current_user.id}")
raise HTTPException(status_code=500, detail="Something went wrong processing this file. Please try again.")
return result
job = UploadJob(user_id=current_user.id, original_filename=file.filename, status="queued")
db.add(job)
db.commit()
db.refresh(job)
background_tasks.add_task(_run_upload_job, job.id, current_user.id, temp_path)
return {"job_id": job.id, "status": job.status}
UPLOAD_JOBS_LOOKBACK_HOURS = 24
@router.get("/upload/jobs")
async def list_upload_jobs(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Lets the client reconcile "what's still going / what finished while I was away" after
a reload or a reopened tab - this list, not the background task by itself, is what makes
upload state actually survive a closed tab from the frontend's point of view (see
UploadQueueContext.tsx's mount-time reconciliation). A finished job's result is joined
against LibrarySong and returned in the same shape TagMetadata already uses, so the
frontend can materialize a finished UploadItem directly with no second round-trip."""
cutoff = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=UPLOAD_JOBS_LOOKBACK_HOURS)
jobs = (
db.query(UploadJob)
.filter(UploadJob.user_id == current_user.id, UploadJob.created_at >= cutoff)
.order_by(UploadJob.created_at.desc())
.all()
)
song_ids = [j.result_song_id for j in jobs if j.result_song_id]
songs_by_id = {s.id: s for s in db.query(LibrarySong).filter(LibrarySong.id.in_(song_ids)).all()} if song_ids else {}
def _serialize(j: UploadJob) -> dict:
song = songs_by_id.get(j.result_song_id)
metadata = None
if song:
metadata = {
"library_song_id": song.id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"genre": song.genre,
"year": "",
"has_lyrics": bool(song.lyrics),
"lyrics": song.lyrics,
"synced_lyrics": json.loads(song.synced_lyrics) if song.synced_lyrics else None,
"cover_art": song.coverart,
"confidence": song.confidence,
"review_status": song.review_status,
}
return {
"job_id": j.id,
"original_filename": j.original_filename,
"status": j.status,
"error": j.error,
"metadata": metadata,
}
return {"status": "success", "jobs": [_serialize(j) for j in jobs]}
......@@ -26,8 +26,9 @@ TUNING_LOCK_EPSILON = 0.3
# this gap, a listener's dial could land in a position where it's ambiguous which of two
# stations they've "tuned" to.
FREQUENCY_COLLISION_EPSILON = 0.6
MAX_ARTWORK_BYTES = 5 * 1024 * 1024
ALLOWED_ARTWORK_TYPES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
# Hoisted into storage.py so auth.py's avatar upload shares the same definitions.
MAX_ARTWORK_BYTES = storage.MAX_IMAGE_BYTES
ALLOWED_ARTWORK_TYPES = storage.ALLOWED_IMAGE_TYPES
# A duration that genuinely can't be probed (corrupted file, exotic codec) shouldn't wedge the
# now-playing math - fall back to a plausible average rather than dividing by zero or crashing.
FALLBACK_DURATION_SECONDS = 180.0
......
......@@ -101,7 +101,11 @@ class DiscoveryAttempt(Base):
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)
# Nullable since Discovery is guest-accessible (see get_current_user_optional) - an
# anonymous caller has no user_id to log, only ip_address below, and vice versa for a
# logged-in caller. Exactly one of the two is ever set on a given row.
user_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=True)
ip_address = Column(String, index=True, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveredSong(Base):
......@@ -209,6 +213,15 @@ class UserProfile(Base):
# handling.
share_location_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
allow_direct_messages = Column(Boolean, default=False, nullable=False, server_default="0")
# Set during onboarding (see OnboardingOverlay.tsx) - a human-readable name shown instead
# of the bare username wherever one's wanted. Nullable: onboarding's profile step is
# skippable, same as preferred_genres below.
display_name = Column(String, nullable=True)
# JSON-encoded list of strings from the fixed GENRES list (src/lib/genres.ts, webapp) -
# same "small JSON-encoded list in a String column" idiom as RemixJob.input_paths below,
# chosen over a join table since this is a short, infrequently-queried list with no
# per-genre relational queries needed yet. Nullable/empty both mean "no preference set."
preferred_genres = Column(String, nullable=True)
class Follow(Base):
__tablename__ = "follows"
......@@ -435,6 +448,24 @@ class RemixJob(Base):
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class UploadJob(Base):
"""Mirrors RemixJob's shape: a status column polled by GET /music/upload/jobs rather than
returned synchronously from POST /music/upload. Exists specifically so the identify+tag
pipeline (network calls to Shazam/AcoustID, lyrics, cover art - see
_identify_tag_and_store) keeps running via BackgroundTasks after the response is sent,
independent of whether the uploading tab is still open - that response delay is what makes
"upload several files as a stream, not one by one" and "tagging continues after closing
the tab" both actually true."""
__tablename__ = "upload_jobs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
original_filename = Column(String, nullable=True)
status = Column(String, default="queued") # queued, processing, done, error
result_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
error = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class ApprovedChat(Base):
"""A Telegram chat a user has explicitly opted into bulk scanning for - distinct from
just being able to browse a chat's music one song at a time (GET
......
......@@ -102,6 +102,25 @@ def get_current_user(
return user
def get_current_user_optional(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: Session = Depends(get_db),
) -> Optional[User]:
"""Same identity check as get_current_user, but returns None instead of raising when no
credentials were sent at all - lets an endpoint serve both logged-in and anonymous callers
(guest browsing on Home/Discovery) from one code path. A credential that IS present but
invalid/expired/for a deactivated account still raises exactly like get_current_user - this
only ever treats "no token" as anonymous, never "bad token" as anonymous."""
if not credentials:
return None
payload = decode_token(credentials.credentials, expected_type="access")
user = db.query(User).filter(User.id == int(payload["sub"])).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
check_account_usable(user)
return user
def get_current_user_for_stream(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
token: Optional[str] = None,
......
......@@ -13,6 +13,11 @@ DOWNLOADS_DIR = os.path.join(LOCAL_STORAGE_ROOT, "downloads")
# per-user subdirectory or ownership check needed on the read side.
IMAGES_DIR = os.path.join(LOCAL_STORAGE_ROOT, "images")
# Shared by every endpoint that accepts a small user-supplied image (radio station artwork,
# profile avatars) - one definition instead of duplicating the same dict/int per router.
MAX_IMAGE_BYTES = 5 * 1024 * 1024
ALLOWED_IMAGE_TYPES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
def _ensure_dirs():
os.makedirs(TEMP_DIR, exist_ok=True)
......
......@@ -484,3 +484,86 @@ def test_chat_music_preview_decode_failure_still_cleans_up_the_raw_download(clie
finally:
if os.path.exists(raw_path):
os.remove(raw_path)
def test_auth_me_includes_an_empty_profile_block_by_default(client, auth_as):
"""Most users have no UserProfile row at all yet - GET /auth/me must still return a
well-formed (empty) profile block rather than erroring, same as the existing privacy
block already does for a missing row (see _get_or_create_profile)."""
headers, _ = auth_as()
body = client.get("/auth/me", headers=headers).json()
assert body["user"]["profile"] == {"display_name": None, "avatar_url": None, "preferred_genres": []}
def test_update_profile_requires_auth(client):
response = client.patch("/auth/profile", json={"display_name": "Nope"})
assert response.status_code == 401
def test_update_profile_sets_display_name_and_genres(client, auth_as):
headers, _ = auth_as()
response = client.patch(
"/auth/profile", json={"display_name": "DJ Test", "preferred_genres": ["Pop", "Jazz"]}, headers=headers
)
assert response.status_code == 200
assert response.json()["profile"] == {"display_name": "DJ Test", "avatar_url": None, "preferred_genres": ["Pop", "Jazz"]}
me = client.get("/auth/me", headers=headers).json()
assert me["user"]["profile"]["display_name"] == "DJ Test"
assert me["user"]["profile"]["preferred_genres"] == ["Pop", "Jazz"]
def test_update_profile_is_a_partial_update(client, auth_as):
"""Omitting a field leaves it untouched, same idiom as PATCH /auth/privacy - a client
setting just the genre step shouldn't have to already know/resend the display name."""
headers, _ = auth_as()
client.patch("/auth/profile", json={"display_name": "Keep Me"}, headers=headers)
response = client.patch("/auth/profile", json={"preferred_genres": ["Rock"]}, headers=headers)
assert response.json()["profile"]["display_name"] == "Keep Me"
assert response.json()["profile"]["preferred_genres"] == ["Rock"]
def test_update_profile_empty_genre_list_clears_preference(client, auth_as):
headers, _ = auth_as()
client.patch("/auth/profile", json={"preferred_genres": ["Rock"]}, headers=headers)
response = client.patch("/auth/profile", json={"preferred_genres": []}, headers=headers)
assert response.json()["profile"]["preferred_genres"] == []
def test_upload_avatar_requires_auth(client):
response = client.post("/auth/profile/avatar", files={"file": ("a.png", b"fake", "image/png")})
assert response.status_code == 401
def test_upload_avatar_rejects_disallowed_content_type(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/auth/profile/avatar", headers=headers, files={"file": ("a.gif", b"fake", "image/gif")}
)
assert response.status_code == 422
def test_upload_avatar_rejects_oversized_file(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch("src.api.routers.auth.storage.MAX_IMAGE_BYTES", 10)
response = client.post(
"/auth/profile/avatar", headers=headers, files={"file": ("a.png", b"way more than ten bytes", "image/png")}
)
assert response.status_code == 422
def test_upload_avatar_stores_image_and_sets_profile_avatar_url(client, auth_as, mocker):
headers, _ = auth_as()
store_image = mocker.patch("src.api.routers.auth.storage.store_image", return_value="/images/1/avatar.png")
response = client.post(
"/auth/profile/avatar", headers=headers, files={"file": ("a.png", b"fake png bytes", "image/png")}
)
assert response.status_code == 200
assert response.json()["avatar_url"] == "/images/1/avatar.png"
store_image.assert_called_once()
me = client.get("/auth/me", headers=headers).json()
assert me["user"]["profile"]["avatar_url"] == "/images/1/avatar.png"
......@@ -62,6 +62,52 @@ def test_discovery_listen_no_file(client, auth_as):
assert response.status_code == 422
def test_discovery_listen_works_for_an_anonymous_guest(client, monkeypatch):
"""Discovery is one of the two guest-accessible pages (see get_current_user_optional) -
the real identify step runs for an anonymous caller too, just without anything to attach
a DiscoveredSong/library copy to."""
async def _fake_identify_hit(path):
return [{"title": "Dummy Song", "artist": "Dummy Artist", "genre": "Pop", "coverart": None}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["detected"]["title"] == "Dummy Song"
# No account to attach a DiscoveredSong row or a library copy to.
assert body["discovery_id"] is None
assert body["library_song_id"] is None
def test_discovery_listen_anonymous_rate_limit_is_per_ip(monkeypatch):
"""Own TestClient with a dedicated fake client address (not the shared `client` fixture's
default) - DiscoveryAttempt rows persist for the whole test session (see conftest.py), so
every anonymous test sharing the default address would otherwise accumulate into the same
rate-limit bucket and make this flaky depending on test order."""
from fastapi.testclient import TestClient
from src.api.main import app
async def _fake_identify_miss(path):
return []
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_miss)
monkeypatch.setattr(discovery_router, "MAX_IDENTIFY_ATTEMPTS_PER_IP", 2)
with TestClient(app, client=("203.0.113.77", 51234)) as isolated_client:
for _ in range(2):
response = isolated_client.post("/discovery/listen", files={"file": _dummy_audio_file()})
assert response.status_code == 200
limited = isolated_client.post("/discovery/listen", files={"file": _dummy_audio_file()})
assert limited.status_code == 429
def test_discovery_history_still_requires_auth_for_guests(client):
"""History/swipe are both inherently about a signed-in caller's own saved
history/preferences - unlike /listen, these stay auth-required for an anonymous guest."""
response = client.get("/discovery/history")
assert response.status_code == 401
def test_discovery_swipe_invalid_song(client, auth_as):
headers, _ = auth_as()
response = client.post("/discovery/99999/swipe", data={"liked": True}, headers=headers)
......
......@@ -20,9 +20,18 @@ def _add_song(db_session, user_id, **overrides):
return song
def test_home_feed_requires_auth(client):
def test_home_feed_works_for_an_anonymous_guest(client, db_session, auth_as):
"""Home is one of the two guest-accessible pages (see get_current_user_optional) - an
anonymous caller gets 200 with a non-personalized feed, not a 401."""
_, owner = auth_as()
_add_song(db_session, owner.id, title="Guest Visible Song", artist="Someone")
response = client.get("/home/feed")
assert response.status_code == 401
assert response.status_code == 200
body = response.json()
assert any(s["title"] == "Guest Visible Song" for s in body["latest_songs"])
# No account to have liked anything from.
assert all(s["is_liked"] is False for s in body["latest_songs"])
def test_latest_songs_is_global_not_scoped_to_the_caller(client, db_session, auth_as):
......
from src.core.database import IdentifiedTrack, LibrarySong
from src.services.audio_processing import AudioDecodeError
from src.services.music_identification import fingerprint_hash
FAKE_CANDIDATE = {
......@@ -12,6 +13,19 @@ FAKE_CANDIDATE = {
}
def _upload(client, headers, filename="test.mp3", content=b"fake mp3 bytes"):
"""POSTs to /music/upload (job-based, see music.py's upload_direct) and returns the
resulting job dict from GET /music/upload/jobs. Starlette's TestClient runs
BackgroundTasks synchronously as part of the same call before the response comes back, so
the job is already done/errored by the time this helper's second request runs - tests
don't need to poll."""
response = client.post("/music/upload", headers=headers, files={"file": (filename, content, "audio/mpeg")})
assert response.status_code == 200
job_id = response.json()["job_id"]
jobs = client.get("/music/upload/jobs", headers=headers).json()["jobs"]
return next(j for j in jobs if j["job_id"] == job_id)
def _mock_pipeline(mocker, final_path="/tmp/does-not-need-to-exist.mp3", url_path="/downloads/1/x.mp3", fingerprint=None):
mocker.patch("src.api.routers.music.compute_fingerprint", return_value=fingerprint)
# A fresh copy every call, not the shared FAKE_CANDIDATE object itself -
......@@ -86,8 +100,12 @@ def test_music_upload_no_file(client, auth_as):
assert response.status_code == 422
def test_music_upload_success_creates_library_song(client, db_session, auth_as, mocker):
headers, user = auth_as()
def test_music_upload_returns_a_job_id_immediately(client, auth_as, mocker):
"""The response itself is now just an accepted-job acknowledgement, not the full tagged
result - that's the whole point of the background-job rework (see upload_direct's own
docstring): it lets the client move on to the next file in a batch immediately instead of
waiting out the full identify/tag pipeline per file."""
headers, _ = auth_as()
_mock_pipeline(mocker)
response = client.post(
......@@ -96,7 +114,17 @@ def test_music_upload_success_creates_library_song(client, db_session, auth_as,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
body = response.json()
assert isinstance(body["job_id"], int)
assert body["status"] in ("queued", "processing", "done")
def test_music_upload_success_creates_library_song(client, db_session, auth_as, mocker):
headers, user = auth_as()
_mock_pipeline(mocker)
job = _upload(client, headers)
assert job["status"] == "done"
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song is not None
......@@ -136,13 +164,8 @@ def test_music_upload_persists_synced_lyrics(client, db_session, auth_as, mocker
return_value={"lyrics": "la\nla la", "synced_lyrics": [[0.0, "la"], [1.5, "la la"]]},
)
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
assert response.json()["metadata"]["synced_lyrics"] == [[0.0, "la"], [1.5, "la la"]]
job = _upload(client, headers)
assert job["metadata"]["synced_lyrics"] == [[0.0, "la"], [1.5, "la la"]]
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics == '[[0.0, "la"], [1.5, "la la"]]'
......@@ -159,15 +182,10 @@ def test_music_upload_synced_lyrics_override_candidates_own_plain_lyrics(client,
return_value={"lyrics": "real\nsynced lyrics", "synced_lyrics": [[0.0, "real"], [2.0, "synced lyrics"]]},
)
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
job = _upload(client, headers)
fetch_lyrics.assert_called_once()
assert response.json()["metadata"]["synced_lyrics"] == [[0.0, "real"], [2.0, "synced lyrics"]]
assert response.json()["metadata"]["lyrics"] == "real\nsynced lyrics"
assert job["metadata"]["synced_lyrics"] == [[0.0, "real"], [2.0, "synced lyrics"]]
assert job["metadata"]["lyrics"] == "real\nsynced lyrics"
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics == '[[0.0, "real"], [2.0, "synced lyrics"]]'
......@@ -183,12 +201,8 @@ def test_music_upload_no_synced_lyrics_stays_null(client, db_session, auth_as, m
mocker.patch("src.api.routers.music.identify_audio", return_value=[candidate_without_lyrics])
mocker.patch("src.api.routers.music.fetch_lyrics", return_value={"lyrics": None, "synced_lyrics": None})
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.json()["metadata"]["synced_lyrics"] is None
job = _upload(client, headers)
assert job["metadata"]["synced_lyrics"] is None
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics is None
......@@ -202,13 +216,9 @@ def test_music_upload_keeps_candidates_own_lyrics_when_no_synced_source_found(cl
_mock_pipeline(mocker) # FAKE_CANDIDATE's lyrics is "la la la"
mocker.patch("src.api.routers.music.fetch_lyrics", return_value={"lyrics": None, "synced_lyrics": None})
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.json()["metadata"]["synced_lyrics"] is None
assert response.json()["metadata"]["lyrics"] == "la la la"
job = _upload(client, headers)
assert job["metadata"]["synced_lyrics"] is None
assert job["metadata"]["lyrics"] == "la la la"
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.synced_lyrics is None
......@@ -256,15 +266,9 @@ def test_music_upload_cached_fingerprint_skips_identification(client, db_session
_mock_pipeline(mocker, fingerprint=fingerprint)
identify_audio = mocker.patch("src.api.routers.music.identify_audio")
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
body = response.json()
assert body["metadata"]["title"] == "Cached Title"
assert body["metadata"]["artist"] == "Cached Artist"
job = _upload(client, headers)
assert job["metadata"]["title"] == "Cached Title"
assert job["metadata"]["artist"] == "Cached Artist"
identify_audio.assert_not_called()
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
......@@ -297,16 +301,9 @@ def test_music_upload_already_in_library_reuses_existing_song(client, db_session
tag_and_convert_audio = mocker.patch("src.api.routers.music.tag_and_convert_audio")
store_final = mocker.patch("src.api.routers.music.storage.store_final")
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
body = response.json()
assert body["metadata"]["library_song_id"] == existing.id
assert body["metadata"]["title"] == "Already Tagged"
assert "download_url" not in body
job = _upload(client, headers)
assert job["metadata"]["library_song_id"] == existing.id
assert job["metadata"]["title"] == "Already Tagged"
identify_audio.assert_not_called()
tag_and_convert_audio.assert_not_called()
......@@ -363,11 +360,36 @@ def test_music_upload_skips_gemini_fallback_when_ai_identification_disabled(clie
mocker.patch("src.api.routers.music.storage.store_final", return_value=("/tmp/does-not-need-to-exist.mp3", "/downloads/1/x.mp3"))
mocker.patch("src.api.routers.music.fetch_lyrics", return_value={"lyrics": None, "synced_lyrics": None})
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
assert response.json()["metadata"]["title"] == "Unknown"
job = _upload(client, headers)
assert job["metadata"]["title"] == "Unknown"
identify_with_gemini.assert_not_called()
def test_music_upload_job_marks_error_on_audio_decode_failure(client, auth_as, mocker):
"""A corrupted/undecodable file must land the job in 'error' with a readable message, not
leave it stuck 'processing' forever or bubble a raw 500 up through the (already-returned)
POST /upload response."""
headers, _ = auth_as()
mocker.patch("src.api.routers.music.compute_fingerprint", side_effect=AudioDecodeError("bad data"))
job = _upload(client, headers)
assert job["status"] == "error"
assert "corrupted" in job["error"] or "unsupported" in job["error"]
assert job["metadata"] is None
def test_music_upload_jobs_scoped_to_owner(client, auth_as, mocker):
"""GET /music/upload/jobs must never show another user's upload jobs."""
headers_a, _ = auth_as()
headers_b, _ = auth_as()
_mock_pipeline(mocker)
client.post("/music/upload", headers=headers_a, files={"file": ("a.mp3", b"a", "audio/mpeg")})
jobs_b = client.get("/music/upload/jobs", headers=headers_b).json()["jobs"]
assert jobs_b == []
def test_music_upload_jobs_requires_auth(client):
response = client.get("/music/upload/jobs")
assert response.status_code == 401
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