feat(wave-v2): add LLM reranking, mood modes, auto-rotation scheduler and Navidrome auth
This commit is contained in:
1 parent
3b3d591bfd
commit
fb1a5e01dd
11 files changed
+736
-37
No files matched your search
+112
-21
@@ -1,9 +1,10 @@
|
||||
import os
|
||||
import asyncio
|
||||
import urllib.parse
|
||||
from fastapi import FastAPI, Request, HTTPException, Query
|
||||
from fastapi import FastAPI, Request, HTTPException, Query, Form, Depends, status
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
@@ -12,6 +13,13 @@ from app.db import init_db, get_recent_tracks, get_tracks_count, get_db
|
||||
from app.queue import sync_manager
|
||||
from app.core.search import search_all
|
||||
from app.core.tagger import get_track_dest_path
|
||||
from app.core.auth import (
|
||||
verify_credentials,
|
||||
create_session_token,
|
||||
get_authenticated_user,
|
||||
require_auth,
|
||||
COOKIE_NAME
|
||||
)
|
||||
from app.wave.rotator import wave_rotator
|
||||
from app.wave.playlist import ensure_smart_playlist
|
||||
|
||||
@@ -25,6 +33,23 @@ templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))
|
||||
class DownloadRequest(BaseModel):
|
||||
url: str
|
||||
|
||||
class WaveGenerateRequest(BaseModel):
|
||||
mood: Optional[str] = "auto"
|
||||
|
||||
async def _wave_auto_rotation_loop():
|
||||
"""Background loop to periodically rotate and refill Smart Wave buffer."""
|
||||
while True:
|
||||
try:
|
||||
# Sleep interval in hours
|
||||
await asyncio.sleep(settings.WAVE_AUTO_ROTATE_HOURS * 3600)
|
||||
print(f"[AutoRotate] Running scheduled Wave rotation & refill (every {settings.WAVE_AUTO_ROTATE_HOURS}h)...")
|
||||
await wave_rotator.fill_buffer(mood="auto")
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"[AutoRotate] Error during scheduled rotation: {e}")
|
||||
await asyncio.sleep(300)
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup():
|
||||
init_db()
|
||||
@@ -33,18 +58,71 @@ def on_startup():
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to ensure smart playlist: {e}")
|
||||
|
||||
# Launch background auto-rotation task
|
||||
if settings.WAVE_AUTO_ROTATE_HOURS > 0:
|
||||
asyncio.create_task(_wave_auto_rotation_loop())
|
||||
|
||||
def get_prefix(request: Request) -> str:
|
||||
"""Return URL prefix when hosted behind reverse proxy."""
|
||||
prefix = request.headers.get("x-forwarded-prefix", "")
|
||||
if prefix:
|
||||
return prefix.rstrip("/")
|
||||
if "music.qpid.pro" in request.headers.get("host", ""):
|
||||
return "/sync"
|
||||
return ""
|
||||
|
||||
# --- Authentication Routes ---
|
||||
@app.get("/login")
|
||||
def login_page(request: Request):
|
||||
if get_authenticated_user(request):
|
||||
return RedirectResponse(url=f"{get_prefix(request)}/", status_code=303)
|
||||
return templates.TemplateResponse(request=request, name="login.html")
|
||||
|
||||
@app.post("/login")
|
||||
def handle_login(request: Request, username: str = Form(...), password: str = Form(...)):
|
||||
user = username.strip()
|
||||
pwd = password.strip()
|
||||
if verify_credentials(user, pwd):
|
||||
resp = RedirectResponse(url=f"{get_prefix(request)}/", status_code=303)
|
||||
token = create_session_token(user)
|
||||
resp.set_cookie(
|
||||
key=COOKIE_NAME,
|
||||
value=token,
|
||||
max_age=30 * 86400,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/"
|
||||
)
|
||||
return resp
|
||||
return templates.TemplateResponse(
|
||||
request=request,
|
||||
name="login.html",
|
||||
context={"error": "Неверное имя пользователя или пароль Navidrome"}
|
||||
)
|
||||
|
||||
@app.get("/logout")
|
||||
@app.post("/logout")
|
||||
def handle_logout(request: Request):
|
||||
resp = RedirectResponse(url=f"{get_prefix(request)}/login", status_code=303)
|
||||
resp.delete_cookie(COOKIE_NAME, path="/")
|
||||
return resp
|
||||
|
||||
# --- Protected Views & API Endpoints ---
|
||||
@app.get("/")
|
||||
def read_root(request: Request):
|
||||
return templates.TemplateResponse(request=request, name="index.html")
|
||||
user = get_authenticated_user(request)
|
||||
if not user:
|
||||
return RedirectResponse(url=f"{get_prefix(request)}/login", status_code=303)
|
||||
return templates.TemplateResponse(request=request, name="index.html", context={"user": user})
|
||||
|
||||
@app.get("/api/search")
|
||||
async def search_music(q: str = Query(..., min_length=1)):
|
||||
async def search_music(q: str = Query(..., min_length=1), user: str = Depends(require_auth)):
|
||||
"""Search tracks and albums across Yandex, Apple Music and YouTube."""
|
||||
results = await search_all(q.strip())
|
||||
return results
|
||||
|
||||
@app.post("/api/download")
|
||||
async def start_download(req: DownloadRequest):
|
||||
async def start_download(req: DownloadRequest, user: str = Depends(require_auth)):
|
||||
url = req.url.strip()
|
||||
if not url:
|
||||
raise HTTPException(status_code=400, detail="URL is required")
|
||||
@@ -53,7 +131,7 @@ async def start_download(req: DownloadRequest):
|
||||
return {"task_id": task.id, "status": task.status}
|
||||
|
||||
@app.get("/api/direct-download")
|
||||
async def direct_download(url: str = Query(...)):
|
||||
async def direct_download(url: str = Query(...), user: str = Depends(require_auth)):
|
||||
"""Download track directly to user's browser/device."""
|
||||
provider = sync_manager.get_provider(url)
|
||||
tracks = await provider.resolve(url)
|
||||
@@ -75,19 +153,27 @@ async def direct_download(url: str = Query(...)):
|
||||
if not success and track.service == "yandex":
|
||||
success = await sync_manager.universal_provider.download_track(track, dest_path)
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail="Failed to download track")
|
||||
raise HTTPException(status_code=500, detail="Failed to fetch track audio")
|
||||
|
||||
filename = f"{track.artist} - {track.title}.mp3"
|
||||
encoded_filename = urllib.parse.quote(filename)
|
||||
quoted_filename = urllib.parse.quote(filename)
|
||||
return FileResponse(
|
||||
dest_path,
|
||||
media_type="audio/mpeg",
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}
|
||||
headers={
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{quoted_filename}"
|
||||
}
|
||||
)
|
||||
|
||||
@app.get("/api/stream")
|
||||
async def stream_audio(url: str = Query(...)):
|
||||
async def stream_audio(request: Request, url: str = Query(...)):
|
||||
"""Stream audio track for in-browser playback and seeking with HTTP Range support."""
|
||||
# Ensure user has access
|
||||
user = get_authenticated_user(request)
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
# Local file preview (e.g. Wave buffer tracks)
|
||||
if url.startswith("/") and os.path.exists(url) and os.path.realpath(url).startswith(os.path.realpath(settings.MUSIC_DIR)):
|
||||
return FileResponse(
|
||||
url,
|
||||
@@ -127,7 +213,7 @@ async def stream_audio(url: str = Query(...)):
|
||||
)
|
||||
|
||||
@app.post("/api/sync/yandex-likes")
|
||||
async def sync_yandex_likes():
|
||||
async def sync_yandex_likes(user: str = Depends(require_auth)):
|
||||
if not settings.YANDEX_MUSIC_TOKEN:
|
||||
raise HTTPException(status_code=400, detail="Yandex Music Token is not configured.")
|
||||
|
||||
@@ -135,39 +221,44 @@ async def sync_yandex_likes():
|
||||
return {"task_id": task.id, "status": task.status}
|
||||
|
||||
@app.get("/api/tasks")
|
||||
def list_tasks():
|
||||
def list_tasks(user: str = Depends(require_auth)):
|
||||
return list(sync_manager.tasks.values())
|
||||
|
||||
@app.get("/api/tasks/{task_id}")
|
||||
def get_task(task_id: str):
|
||||
def get_task(task_id: str, user: str = Depends(require_auth)):
|
||||
if task_id not in sync_manager.tasks:
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
return sync_manager.tasks[task_id]
|
||||
|
||||
@app.get("/api/history")
|
||||
def get_history(limit: int = 50):
|
||||
def get_history(limit: int = 50, user: str = Depends(require_auth)):
|
||||
tracks = get_recent_tracks(limit)
|
||||
total = get_tracks_count()
|
||||
return {"total": total, "tracks": tracks}
|
||||
|
||||
@app.get("/api/health")
|
||||
def healthcheck():
|
||||
return {"status": "ok", "yandex_configured": bool(settings.YANDEX_MUSIC_TOKEN)}
|
||||
return {
|
||||
"status": "ok",
|
||||
"yandex_configured": bool(settings.YANDEX_MUSIC_TOKEN),
|
||||
"auth_enabled": settings.AUTH_ENABLED
|
||||
}
|
||||
|
||||
# --- Smart Wave Endpoints ---
|
||||
# --- Smart Wave Endpoints (Phase 2) ---
|
||||
@app.get("/api/wave/status")
|
||||
def get_wave_status():
|
||||
def get_wave_status(user: str = Depends(require_auth)):
|
||||
"""Return status of Smart Wave buffer."""
|
||||
return wave_rotator.get_status()
|
||||
|
||||
@app.post("/api/wave/generate")
|
||||
async def generate_wave():
|
||||
"""Discover candidates and fill Smart Wave buffer up to capacity."""
|
||||
result = await wave_rotator.fill_buffer()
|
||||
async def generate_wave(req: Optional[WaveGenerateRequest] = None, user: str = Depends(require_auth)):
|
||||
"""Discover candidates and fill Smart Wave buffer up to capacity using LLM reranker."""
|
||||
mood = req.mood if req else "auto"
|
||||
result = await wave_rotator.fill_buffer(mood=mood)
|
||||
return result
|
||||
|
||||
@app.post("/api/wave/rotate")
|
||||
def rotate_wave():
|
||||
def rotate_wave(user: str = Depends(require_auth)):
|
||||
"""Promote starred tracks and purge expired tracks in Smart Wave buffer."""
|
||||
promoted = wave_rotator.promote_starred_tracks()
|
||||
purged = wave_rotator.purge_expired_tracks()
|
||||
|
||||
Reference in new issue
Block a user