Commit 9c657b0a authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Remove download_url from /music/tag and /music/upload

Frontend no longer needs it (Upload's result card now offers add-to-
playlist/play instead of a download link), and it was pointing at the
unauthenticated /downloads static mount - anyone who saw or guessed a
path could pull another user's file. Same access-control class as the
remix download_url fixed earlier. Playback goes through the already
auth-scoped /library/stream/{id} instead.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9a65fa5a
Pipeline #1156 failed with stage
in 20 minutes and 58 seconds
import asyncio
import json
import shutil
import urllib.parse
from typing import List
import google.generativeai as genai
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from pydantic import BaseModel
from sqlalchemy.orm import Session
......@@ -33,7 +32,6 @@ class TagRequest(BaseModel):
class TagResponse(BaseModel):
status: str
download_url: str
metadata: dict
......@@ -51,18 +49,16 @@ async def _identify_tag_and_store(
db: Session,
current_user: User,
raw_file_path: str,
request: Request = None,
language_preference: str = "native",
) -> dict:
"""Shared by /music/upload, /music/tag, and the bulk chat-scan background job: identify ->
lyrics -> genre -> tag -> durable storage -> LibrarySong row. This is what makes /library
non-empty - nothing wrote to it before this existed.
request is optional because the background scan job (telegram_scan.py) has no live
request to build an absolute download_url from - same reasoning as RemixJob storing a bare
result_filename and letting GET /remix/{job_id} build the URL later from *its own* request.
When request is None, download_url comes back None too; callers that need it always pass
one (both /music/tag and /music/upload do)."""
Doesn't hand back a raw file URL - the stored file lives under the unauthenticated
/downloads static mount, so anyone who saw or guessed the path could pull another user's
song. Playback goes through the auth-scoped /library/stream/{id} instead, keyed off
metadata.library_song_id (same fix already applied to remix's result files)."""
try:
fingerprint = await compute_fingerprint(raw_file_path)
......@@ -76,14 +72,9 @@ async def _identify_tag_and_store(
# Same user, same recording (by content fingerprint, not just title/artist text) -
# they already have this tagged and stored. Hand back the existing entry instead of
# re-running identification, re-tagging, and writing a second copy of the file.
download_url = (
str(request.base_url).rstrip('/') + urllib.parse.quote(storage.url_path_for(existing_song.file_path))
if request else None
)
return {
"status": "success",
"deduped": True, # already had this exact recording - filtered out by response_model on the HTTP endpoints, read directly by the chat-scan background job
"download_url": download_url,
"metadata": {
"library_song_id": existing_song.id,
"title": existing_song.title,
......@@ -171,7 +162,7 @@ async def _identify_tag_and_store(
logger.error(f"IdentifiedTrack cache write failed: {e}")
tagged_path = await tag_and_convert_audio(raw_file_path, candidate)
final_path, url_path = storage.store_final(current_user.id, tagged_path)
final_path, _ = storage.store_final(current_user.id, tagged_path)
library_song = LibrarySong(
user_id=current_user.id,
......@@ -189,12 +180,9 @@ async def _identify_tag_and_store(
db.commit()
db.refresh(library_song)
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(url_path) if request else None
return {
"status": "success",
"deduped": False,
"download_url": download_url,
"metadata": {
"library_song_id": library_song.id,
"title": library_song.title,
......@@ -215,7 +203,6 @@ async def _identify_tag_and_store(
@router.post("/tag", response_model=TagResponse)
async def tag_music(
req: TagRequest,
request: Request,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
......@@ -233,7 +220,7 @@ async def tag_music(
raise HTTPException(status_code=404, detail=f"Could not download audio from chat: {e}")
try:
result = await _identify_tag_and_store(db, current_user, raw_file_path, request, req.language_preference)
result = await _identify_tag_and_store(db, current_user, raw_file_path, req.language_preference)
except AudioDecodeError as e:
logger.error(f"Audio decode failed for user {current_user.id}'s chat tag request: {e}")
raise HTTPException(status_code=422, detail="Couldn't process this audio file - it may be corrupted or in an unsupported format.")
......@@ -257,7 +244,6 @@ async def batch_remix_status(job_id: str, current_user: User = Depends(get_curre
@router.post("/upload", response_model=TagResponse)
async def upload_direct(
request: Request,
file: UploadFile = File(...),
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
......@@ -267,7 +253,7 @@ async def upload_direct(
shutil.copyfileobj(file.file, buffer)
try:
result = await _identify_tag_and_store(db, current_user, temp_path, request)
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.")
......
......@@ -124,7 +124,7 @@ async def _run_chat_scan(job_id: int, user_id: int, chat_id: int, session_string
try:
dest = storage.new_temp_path(f"scan_{chat_id}_{m['message_id']}")
raw_path = await telegram_sync.download_chat_audio(session_string, chat_id, m["message_id"], dest)
result = await _identify_tag_and_store(db, user, raw_path, None, language_preference)
result = await _identify_tag_and_store(db, user, raw_path, language_preference)
outcome = "skipped_duplicate" if result.get("deduped") else "saved"
title = result["metadata"]["title"]
artist = result["metadata"]["artist"]
......
......@@ -40,14 +40,6 @@ def store_final(user_id: int, local_path: str) -> tuple[str, str]:
return dest, url_path
def url_path_for(local_path: str) -> str:
"""Reverse of store_final's second return value - reconstructs the servable /downloads
URL for a path that was persisted earlier (e.g. LibrarySong.file_path), so callers don't
need to know the on-disk layout themselves."""
rel = os.path.relpath(local_path, DOWNLOADS_DIR)
return f"/downloads/{rel.replace(os.sep, '/')}"
def cleanup_temp(path: str):
if path and os.path.exists(path):
os.remove(path)
......@@ -280,7 +280,7 @@ def test_music_upload_already_in_library_reuses_existing_song(client, db_session
body = response.json()
assert body["metadata"]["library_song_id"] == existing.id
assert body["metadata"]["title"] == "Already Tagged"
assert body["download_url"].endswith("/downloads/1/existing.mp3")
assert "download_url" not in body
identify_audio.assert_not_called()
tag_and_convert_audio.assert_not_called()
......
......@@ -171,8 +171,8 @@ def test_chat_scan_saves_skips_and_fails_songs_individually(client, db_session,
mocker.patch(
"src.api.routers.telegram_scan._identify_tag_and_store",
side_effect=[
{"status": "success", "deduped": False, "download_url": None, "metadata": {"title": "Song One", "artist": "Artist One"}},
{"status": "success", "deduped": True, "download_url": None, "metadata": {"title": "Song Two", "artist": "Artist Two"}},
{"status": "success", "deduped": False, "metadata": {"title": "Song One", "artist": "Artist One"}},
{"status": "success", "deduped": True, "metadata": {"title": "Song Two", "artist": "Artist Two"}},
AudioDecodeError("corrupt"),
],
)
......
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