Commit b7f372fd authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add 30-second preview stream endpoint for Telegram chat audio

Lets a user audition a found chat song before deciding to save it. Trims
with ffmpeg's -t flag so cost doesn't scale with the source file's real
length, and reuses the existing token-in-query-param stream auth so a
plain <audio src> can play it directly.
parent 5ac890f0
Pipeline #1131 passed with stage
in 5 minutes and 16 seconds
......@@ -2,8 +2,10 @@ import uuid
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from starlette.background import BackgroundTask
from src.core.database import AuthAttempt, RefreshToken, User, get_db
from src.core.security import (
......@@ -11,14 +13,19 @@ from src.core.security import (
create_refresh_token,
decode_token,
get_current_user,
get_current_user_for_stream,
hash_password,
hash_token,
verify_password,
)
from src.services import storage
from src.services.audio_processing import AudioDecodeError, trim_audio
import src.telegram_worker.telegram_auth as telegram_auth
import src.telegram_worker.telegram_sync as telegram_sync
PREVIEW_SECONDS = 30
router = APIRouter(prefix="/auth", tags=["Authentication & Telegram"])
......@@ -307,3 +314,41 @@ async def get_chat_music(chat_id: int, current_user: User = Depends(get_current_
return {"status": "success", "music": music}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/telegram/chats/{chat_id}/music/{message_id}/preview")
async def get_chat_music_preview(
chat_id: int,
message_id: int,
current_user: User = Depends(get_current_user_for_stream),
):
"""Streams a short (PREVIEW_SECONDS) clip of a chat's audio message - lets someone hear
what a found song actually sounds like before deciding whether to Save it, without
tagging or writing anything to their library. get_current_user_for_stream (not the plain
get_current_user every other Telegram route here uses) because a plain <audio src> can't
send an Authorization header, same reasoning as /library/stream/{id}.
Downloads and trims fresh on every call rather than caching - previews are meant to be
cheap/ephemeral, and caching would mean tracking and cleaning up clips for songs that may
never get saved."""
if not current_user.telegram_session_string:
raise HTTPException(status_code=400, detail="No linked Telegram session")
dest = storage.new_temp_path(f"preview_{chat_id}_{message_id}")
try:
raw_path = await telegram_sync.download_chat_audio(current_user.telegram_session_string, chat_id, message_id, dest)
except Exception as e:
raise HTTPException(status_code=404, detail=f"Could not download audio from chat: {e}")
try:
preview_path = await trim_audio(raw_path, PREVIEW_SECONDS)
except AudioDecodeError:
raise HTTPException(status_code=422, detail="Couldn't process this audio file - it may be corrupted or in an unsupported format.")
finally:
storage.cleanup_temp(raw_path)
return FileResponse(
preview_path,
media_type="audio/mpeg",
background=BackgroundTask(storage.cleanup_temp, preview_path),
)
......@@ -113,3 +113,25 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
shutil.move(mp3_file_path, final_path)
return final_path
async def trim_audio(raw_file_path: str, seconds: int) -> str:
"""Cuts raw_file_path down to its first `seconds` of audio and re-encodes as MP3, returning
the new file's path (raw_file_path itself is left untouched). Used for a quick preview
clip - `-t` stops ffmpeg reading/encoding past that point rather than trimming a
fully-decoded file after the fact, so this doesn't cost meaningfully more than encoding a
clip of that length would anyway, regardless of how long the source file actually is."""
out_path = f"{raw_file_path}.preview.mp3"
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-y",
"-i", raw_file_path,
"-t", str(seconds),
"-acodec", "libmp3lame", "-b:a", "128k",
out_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
_stdout, stderr = await proc.communicate()
if proc.returncode != 0 or not os.path.exists(out_path):
raise AudioDecodeError(stderr.decode(errors="replace")[-2000:])
return out_path
import os
import tempfile
from src.api.routers import auth as auth_router
from src.api.routers.auth import MAX_LOGIN_ATTEMPTS_PER_USERNAME, MAX_REQUESTS_PER_PHONE
from src.core.database import User
from src.services.audio_processing import AudioDecodeError
def _real_temp_file(content: bytes = b"fake audio bytes") -> str:
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(content)
return path
# --- username/password (primary login) ---
......@@ -363,3 +374,62 @@ def test_auth_chats_music_with_token(client, auth_as, mocker):
assert body["status"] == "success"
assert len(body["music"]) == 1
assert body["music"][0]["title"] == "Song"
def test_chat_music_preview_no_token(client):
response = client.get("/auth/telegram/chats/123/music/1/preview")
assert response.status_code == 401
def test_chat_music_preview_requires_linked_telegram_session(client, auth_as):
headers, _ = auth_as(telegram_session_string=None)
response = client.get("/auth/telegram/chats/123/music/1/preview", headers=headers)
assert response.status_code == 400
def test_chat_music_preview_success(client, auth_as, mocker):
headers, _ = auth_as()
raw_path = _real_temp_file(b"raw downloaded audio")
preview_path = _real_temp_file(b"trimmed 30s clip")
try:
mocker.patch("src.api.routers.auth.telegram_sync.download_chat_audio", return_value=raw_path)
trim = mocker.patch("src.api.routers.auth.trim_audio", return_value=preview_path)
response = client.get("/auth/telegram/chats/123/music/1/preview", headers=headers)
assert response.status_code == 200
assert response.content == b"trimmed 30s clip"
assert response.headers["content-type"] == "audio/mpeg"
trim.assert_called_once_with(raw_path, auth_router.PREVIEW_SECONDS)
# The raw download is cleaned up regardless (only the trimmed clip is ever served);
# the trimmed clip itself is cleaned up after being streamed back.
assert not os.path.exists(raw_path)
assert not os.path.exists(preview_path)
finally:
for p in (raw_path, preview_path):
if os.path.exists(p):
os.remove(p)
def test_chat_music_preview_download_failure(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch("src.api.routers.auth.telegram_sync.download_chat_audio", side_effect=Exception("boom"))
response = client.get("/auth/telegram/chats/123/music/1/preview", headers=headers)
assert response.status_code == 404
def test_chat_music_preview_decode_failure_still_cleans_up_the_raw_download(client, auth_as, mocker):
headers, _ = auth_as()
raw_path = _real_temp_file(b"corrupt audio")
try:
mocker.patch("src.api.routers.auth.telegram_sync.download_chat_audio", return_value=raw_path)
mocker.patch("src.api.routers.auth.trim_audio", side_effect=AudioDecodeError("bad audio"))
response = client.get("/auth/telegram/chats/123/music/1/preview", headers=headers)
assert response.status_code == 422
assert not os.path.exists(raw_path)
finally:
if os.path.exists(raw_path):
os.remove(raw_path)
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