Commit 78e816ec authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Merge origin/dev (remix engine, live rooms, channels, custom console) into dev

Reconciles the hardening/caching/deploy-pipeline work on this branch with the
previously-unmerged remix engine, Pass-the-Aux room websocket infra, Channels
router, and custom API console from origin/dev.

Conflict resolution notes:
- Kept the current JWT/session-based auth (src/core/security.py) over origin/dev's
  older session-string-header auth; adapted its unique test coverage (chats/music
  endpoint, discovery listen/swipe content paths, library search/stream/lyrics/
  playlist content paths, remix-tree tests) to the current auth_as fixture instead
  of dropping that coverage.
- Kept origin/dev's branded login-page + session-cookie docs auth (superset of the
  plain HTTP Basic version), and its recursive _build_remix_tree over a flat one-
  level version.
- Replaced the stopgap _run_lightweight_migrations()/create_all-at-import-time in
  database.py with Alembic, which both sides now share as the single source of
  truth for schema; generated a new migration for the 7 tables origin/dev added
  (Correction, RemixJob, Channel, ChannelFollow, VibeSet, VibeSetTrack, AudioStory,
  ChannelShowcase).
- Fixed a real bug surfaced by the merge: remix_engine.py and remix.py hardcoded
  /root/antigrav-stax-audio/* for stem cache/temp/downloads, a different directory
  than storage.py's LOCAL_STORAGE_ROOT-based paths that main.py's /downloads mount
  actually serves - remix downloads would have 404'd. Both now share storage.py's
  paths.
- deploy.sh and .gitlab-ci.yml now install CPU-only torch and libsndfile1, needed
  by the remix engine's demucs/librosa dependency chain.
- test_channels.py::test_showcase_owner_only still posted to /social/posts without
  auth headers; updated to use the auth_as fixture like the rest of the suite.

104 tests pass (up from 40 pre-merge + origin/dev's own suite, combined and
de-duplicated).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parents 92a8a0e4 9c7c9c22
Pipeline #1010 failed
...@@ -9,9 +9,9 @@ LALAL_API_KEY=your_lalal_api_key_here ...@@ -9,9 +9,9 @@ LALAL_API_KEY=your_lalal_api_key_here
# No default, no fallback: the app refuses to start without it. # No default, no fallback: the app refuses to start without it.
JWT_SECRET= JWT_SECRET=
# Gate for the interactive API docs (/docs, /openapi.json) # HTTP Basic Auth credentials gating /docs and /openapi.json
DOCS_USERNAME=your_docs_username DOCS_USERNAME=choose_a_username
DOCS_PASSWORD=your_docs_password DOCS_PASSWORD=choose_a_strong_password
# Where uploaded/tagged audio lives locally. Defaults to ./var/storage if unset. # Where uploaded/tagged audio lives locally. Defaults to ./var/storage if unset.
LOCAL_STORAGE_ROOT=./var/storage LOCAL_STORAGE_ROOT=./var/storage
......
...@@ -16,7 +16,10 @@ test: ...@@ -16,7 +16,10 @@ test:
stage: test stage: test
image: python:3.10-slim image: python:3.10-slim
before_script: before_script:
- apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg git - apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg git libsndfile1
# CPU-only torch first - this repo has no GPU anywhere, and the default PyPI
# wheel is a multi-GB CUDA build that would blow out CI time/disk for nothing.
- pip install --index-url https://download.pytorch.org/whl/cpu torch
- pip install --prefer-binary -q -r requirements.txt - pip install --prefer-binary -q -r requirements.txt
script: script:
- PYTHONPATH=. pytest tests/ -v - PYTHONPATH=. pytest tests/ -v
......
"""add remix, channels, and correction tables
Revision ID: d7aa8b954a33
Revises: 704f3f6d4916
Create Date: 2026-08-09 09:01:33.744604
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd7aa8b954a33'
down_revision: Union[str, Sequence[str], None] = '704f3f6d4916'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('corrections',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('artist', sa.String(), nullable=True),
sa.Column('source', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_corrections_id'), 'corrections', ['id'], unique=False)
op.create_index(op.f('ix_corrections_user_id'), 'corrections', ['user_id'], unique=False)
op.create_table('channels',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('avatar_url', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channels_id'), 'channels', ['id'], unique=False)
op.create_index(op.f('ix_channels_name'), 'channels', ['name'], unique=False)
op.create_index(op.f('ix_channels_owner_id'), 'channels', ['owner_id'], unique=False)
op.create_table('audio_stories',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('caption', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_audio_stories_channel_id'), 'audio_stories', ['channel_id'], unique=False)
op.create_index(op.f('ix_audio_stories_id'), 'audio_stories', ['id'], unique=False)
op.create_table('channel_follows',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('followed_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channel_follows_channel_id'), 'channel_follows', ['channel_id'], unique=False)
op.create_index(op.f('ix_channel_follows_id'), 'channel_follows', ['id'], unique=False)
op.create_index(op.f('ix_channel_follows_user_id'), 'channel_follows', ['user_id'], unique=False)
op.create_table('vibe_sets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_vibe_sets_channel_id'), 'vibe_sets', ['channel_id'], unique=False)
op.create_index(op.f('ix_vibe_sets_id'), 'vibe_sets', ['id'], unique=False)
op.create_table('channel_showcases',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.Integer(), nullable=True),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.Column('added_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['channel_id'], ['channels.id'], ),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_channel_showcases_channel_id'), 'channel_showcases', ['channel_id'], unique=False)
op.create_index(op.f('ix_channel_showcases_id'), 'channel_showcases', ['id'], unique=False)
op.create_index(op.f('ix_channel_showcases_post_id'), 'channel_showcases', ['post_id'], unique=False)
op.create_table('remix_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('status', sa.String(), nullable=True),
sa.Column('stage_detail', sa.String(), nullable=True),
sa.Column('prompt', sa.String(), nullable=True),
sa.Column('input_paths', sa.String(), nullable=True),
sa.Column('plan_json', sa.String(), nullable=True),
sa.Column('remix_name', sa.String(), nullable=True),
sa.Column('result_filename', sa.String(), nullable=True),
sa.Column('result_song_id', sa.Integer(), nullable=True),
sa.Column('result_post_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_post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['result_song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_remix_jobs_id'), 'remix_jobs', ['id'], unique=False)
op.create_table('vibe_set_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('vibe_set_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('order', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['vibe_set_id'], ['vibe_sets.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_vibe_set_tracks_id'), 'vibe_set_tracks', ['id'], unique=False)
op.create_index(op.f('ix_vibe_set_tracks_vibe_set_id'), 'vibe_set_tracks', ['vibe_set_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_vibe_set_tracks_vibe_set_id'), table_name='vibe_set_tracks')
op.drop_index(op.f('ix_vibe_set_tracks_id'), table_name='vibe_set_tracks')
op.drop_table('vibe_set_tracks')
op.drop_index(op.f('ix_remix_jobs_id'), table_name='remix_jobs')
op.drop_table('remix_jobs')
op.drop_index(op.f('ix_channel_showcases_post_id'), table_name='channel_showcases')
op.drop_index(op.f('ix_channel_showcases_id'), table_name='channel_showcases')
op.drop_index(op.f('ix_channel_showcases_channel_id'), table_name='channel_showcases')
op.drop_table('channel_showcases')
op.drop_index(op.f('ix_vibe_sets_id'), table_name='vibe_sets')
op.drop_index(op.f('ix_vibe_sets_channel_id'), table_name='vibe_sets')
op.drop_table('vibe_sets')
op.drop_index(op.f('ix_channel_follows_user_id'), table_name='channel_follows')
op.drop_index(op.f('ix_channel_follows_id'), table_name='channel_follows')
op.drop_index(op.f('ix_channel_follows_channel_id'), table_name='channel_follows')
op.drop_table('channel_follows')
op.drop_index(op.f('ix_audio_stories_id'), table_name='audio_stories')
op.drop_index(op.f('ix_audio_stories_channel_id'), table_name='audio_stories')
op.drop_table('audio_stories')
op.drop_index(op.f('ix_channels_owner_id'), table_name='channels')
op.drop_index(op.f('ix_channels_name'), table_name='channels')
op.drop_index(op.f('ix_channels_id'), table_name='channels')
op.drop_table('channels')
op.drop_index(op.f('ix_corrections_user_id'), table_name='corrections')
op.drop_index(op.f('ix_corrections_id'), table_name='corrections')
op.drop_table('corrections')
# ### end Alembic commands ###
...@@ -32,7 +32,7 @@ log "Ensuring system packages are present" ...@@ -32,7 +32,7 @@ log "Ensuring system packages are present"
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
apt-get update -qq apt-get update -qq
apt-get install -y -qq --no-install-recommends \ apt-get install -y -qq --no-install-recommends \
python3 python3-venv ffmpeg git curl build-essential python3 python3-venv ffmpeg git curl build-essential libsndfile1
# --- 2. Repo - clone on a bare box, fetch+reset on an already-deployed one ----------------- # --- 2. Repo - clone on a bare box, fetch+reset on an already-deployed one -----------------
if [ ! -d "$DEPLOY_DIR/.git" ]; then if [ ! -d "$DEPLOY_DIR/.git" ]; then
...@@ -63,6 +63,9 @@ fi ...@@ -63,6 +63,9 @@ fi
log "Installing dependencies into $VENV_DIR" log "Installing dependencies into $VENV_DIR"
# shellcheck disable=SC1091 # shellcheck disable=SC1091
source "$VENV_DIR/bin/activate" source "$VENV_DIR/bin/activate"
# CPU-only torch first - this VPS has no GPU, and the default PyPI wheel is a multi-GB CUDA
# build. pip skips this entirely on repeat runs once the CPU wheel is already satisfied.
pip install --prefer-binary -q --index-url https://download.pytorch.org/whl/cpu torch
pip install --prefer-binary -q -r requirements.txt pip install --prefer-binary -q -r requirements.txt
# --- 4. .env - only (re)written when the CI job actually supplied prod secrets, so a manual # --- 4. .env - only (re)written when the CI job actually supplied prod secrets, so a manual
......
[Unit]
Description=Stax Backend API Service (dev branch)
After=network.target
[Service]
User=root
WorkingDirectory=/root/stax_backend_api-dev
ExecStart=/root/stax_backend_api-dev/venv/bin/uvicorn src.api.main:app --host 0.0.0.0 --port 8001
Restart=always
RestartSec=3
Environment=PYTHONPATH=/root/stax_backend_api-dev
Environment=HTTP_PROXY=http://127.0.0.1:8118
Environment=HTTPS_PROXY=http://127.0.0.1:8118
Environment=http_proxy=http://127.0.0.1:8118
Environment=https_proxy=http://127.0.0.1:8118
Environment=NO_PROXY=127.0.0.1,localhost
Environment=no_proxy=127.0.0.1,localhost
[Install]
WantedBy=multi-user.target
...@@ -10,6 +10,9 @@ google-generativeai==0.8.3 ...@@ -10,6 +10,9 @@ google-generativeai==0.8.3
pedalboard==0.9.8 pedalboard==0.9.8
fastapi>=0.110.0 fastapi>=0.110.0
uvicorn>=0.28.0 uvicorn>=0.28.0
websockets>=13.0 # uvicorn's WebSocket protocol implementation - without this, uvicorn
# silently has no WebSocket support at all (no error, connections just
# fail); needed for the Pass-the-Aux room websocket routes
sqlalchemy>=2.0.0 sqlalchemy>=2.0.0
httpx>=0.27.0 httpx>=0.27.0
python-multipart>=0.0.9 python-multipart>=0.0.9
...@@ -19,3 +22,15 @@ pyrogram>=2.0.106 ...@@ -19,3 +22,15 @@ pyrogram>=2.0.106
tgcrypto>=1.2.5 tgcrypto>=1.2.5
pyjwt>=2.8.0 pyjwt>=2.8.0
alembic>=1.13.0 alembic>=1.13.0
# Remix engine. Install torch CPU-only *before* this file, this VPS has no GPU:
# pip install torch --index-url https://download.pytorch.org/whl/cpu
# Otherwise pip pulls the default CUDA wheel (multiple GB, useless here).
# numpy is pinned <2: this VPS's virtualized CPU exposes no SSE3/SSE4/AVX at all,
# and numpy>=2's default wheels require the x86-64-v2 baseline and segfault/RuntimeError
# on import here. 1.26.4 is what the rest of this project already runs on successfully.
numpy==1.26.4
scipy==1.13.1
demucs>=4.0.1
librosa>=0.10.2
soundfile>=0.12.1
import base64
import os import os
import secrets import secrets
from fastapi import Depends, FastAPI, HTTPException, status from datetime import datetime, timedelta, timezone
from fastapi import Depends, FastAPI, Form, HTTPException, Request, status
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from sqlalchemy import text from sqlalchemy import text
from src.api.routers import auth, discovery, library, music, social from src.api.routers import auth, channels, discovery, library, music, remix, social
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR from src.services.storage import DOWNLOADS_DIR
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html") CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
LOGIN_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "login.html")
# --- Docs auth: a real branded login page + session cookie, with HTTP Basic kept as a
# fallback for scripted/curl access (no browser to show a login page to). Sessions are
# in-memory only - lost on restart, which is fine for an admin-facing docs gate. ---
SESSION_COOKIE_NAME = "stax_docs_session"
SESSION_DURATION = timedelta(hours=24)
_active_sessions: dict[str, datetime] = {}
def _create_session() -> str:
token = secrets.token_urlsafe(32)
_active_sessions[token] = datetime.now(timezone.utc) + SESSION_DURATION
return token
def _check_session_cookie(request: Request) -> bool:
token = request.cookies.get(SESSION_COOKIE_NAME)
if not token:
return False
expiry = _active_sessions.get(token)
if not expiry or expiry < datetime.now(timezone.utc):
_active_sessions.pop(token, None)
return False
return True
def _check_basic_auth(request: Request) -> bool:
auth_header = request.headers.get("authorization", "")
if not auth_header.lower().startswith("basic "):
return False
try:
decoded = base64.b64decode(auth_header[6:]).decode()
username, _, password = decoded.partition(":")
except Exception:
return False
if not DOCS_USERNAME or not DOCS_PASSWORD:
return False
return secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD)
docs_security = HTTPBasic()
def _is_authenticated(request: Request) -> bool:
return _check_session_cookie(request) or _check_basic_auth(request)
def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security)):
def require_docs_auth(request: Request):
if not DOCS_USERNAME or not DOCS_PASSWORD: if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.") raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
valid_username = secrets.compare_digest(credentials.username, DOCS_USERNAME) if not _is_authenticated(request):
valid_password = secrets.compare_digest(credentials.password, DOCS_PASSWORD)
if not (valid_username and valid_password):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password", detail="Not authenticated",
headers={"WWW-Authenticate": "Basic"}, headers={"WWW-Authenticate": "Basic"},
) )
return credentials.username
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
...@@ -40,6 +81,8 @@ app.include_router(discovery.router) ...@@ -40,6 +81,8 @@ app.include_router(discovery.router)
app.include_router(library.router) app.include_router(library.router)
app.include_router(music.router) app.include_router(music.router)
app.include_router(social.router) app.include_router(social.router)
app.include_router(remix.router)
app.include_router(channels.router)
@app.get("/", include_in_schema=False) @app.get("/", include_in_schema=False)
...@@ -47,6 +90,12 @@ async def root(): ...@@ -47,6 +90,12 @@ async def root():
return RedirectResponse(url="/docs") return RedirectResponse(url="/docs")
@app.get("/login", include_in_schema=False, response_class=HTMLResponse)
async def login_page():
with open(LOGIN_HTML_PATH, "r") as f:
return f.read()
@app.get("/healthz", include_in_schema=False) @app.get("/healthz", include_in_schema=False)
async def healthz(): async def healthz():
"""Unauthenticated liveness/readiness probe for the deploy script - confirms the process """Unauthenticated liveness/readiness probe for the deploy script - confirms the process
...@@ -62,20 +111,47 @@ async def healthz(): ...@@ -62,20 +111,47 @@ async def healthz():
return {"status": "ok"} return {"status": "ok"}
@app.post("/login", include_in_schema=False)
async def login_submit(username: str = Form(...), password: str = Form(...)):
if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
if secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD):
token = _create_session()
response = RedirectResponse(url="/docs", status_code=status.HTTP_303_SEE_OTHER)
response.set_cookie(
SESSION_COOKIE_NAME, token, httponly=True, samesite="lax",
max_age=int(SESSION_DURATION.total_seconds()),
)
return response
return RedirectResponse(url="/login?error=1", status_code=status.HTTP_303_SEE_OTHER)
@app.get("/logout", include_in_schema=False)
async def logout(request: Request):
token = request.cookies.get(SESSION_COOKIE_NAME)
if token:
_active_sessions.pop(token, None)
response = RedirectResponse(url="/login")
response.delete_cookie(SESSION_COOKIE_NAME)
return response
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse) @app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)): async def get_documentation(request: Request):
if not _is_authenticated(request):
return RedirectResponse(url="/login")
with open(CONSOLE_HTML_PATH, "r") as f: with open(CONSOLE_HTML_PATH, "r") as f:
return f.read() return f.read()
@app.get("/openapi.json", include_in_schema=False) @app.get("/openapi.json", include_in_schema=False)
async def openapi(username: str = Depends(verify_docs_auth)): async def openapi(request: Request, _auth=Depends(require_docs_auth)):
if app.openapi_schema: if app.openapi_schema:
return app.openapi_schema return app.openapi_schema
openapi_schema = get_openapi( openapi_schema = get_openapi(
title="Stax Music API", title="Stax Music API",
version="1.0.0", version="1.0.0",
description="API backend for the Stax App. Features music tagging and batch remixing.", description="API backend for the Stax App. Features music tagging, batch remixing, and AI multi-song remixing.",
routes=app.routes, routes=app.routes,
) )
app.openapi_schema = openapi_schema app.openapi_schema = openapi_schema
......
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import (
AudioStory,
Channel,
ChannelFollow,
ChannelShowcase,
LibrarySong,
Post,
VibeSet,
VibeSetTrack,
get_db,
)
router = APIRouter(prefix="/channels", tags=["Channels"])
STORY_LIFETIME = timedelta(hours=24)
class ChannelCreate(BaseModel):
owner_id: int
name: str
description: Optional[str] = None
avatar_url: Optional[str] = None
class FollowRequest(BaseModel):
user_id: int
class VibeSetCreate(BaseModel):
user_id: int # must match the channel's owner_id
title: str
description: Optional[str] = None
song_ids: List[int] = []
class StoryCreate(BaseModel):
user_id: int # must match the channel's owner_id
song_id: int
caption: Optional[str] = None
class ShowcaseCreate(BaseModel):
user_id: int # must match the channel's owner_id
post_id: int
def _get_channel_or_404(channel_id: int, db: Session) -> Channel:
channel = db.query(Channel).filter(Channel.id == channel_id).first()
if not channel:
raise HTTPException(status_code=404, detail="Channel not found")
return channel
def _require_owner(channel: Channel, user_id: int):
if channel.owner_id != user_id:
raise HTTPException(status_code=403, detail="Only the channel owner can do this")
@router.post("", status_code=status.HTTP_201_CREATED)
def create_channel(data: ChannelCreate, db: Session = Depends(get_db)):
channel = Channel(**data.dict())
db.add(channel)
db.commit()
db.refresh(channel)
return channel
@router.get("")
def list_channels(db: Session = Depends(get_db)):
return db.query(Channel).order_by(Channel.created_at.desc()).all()
# NOTE: routes with a fixed first path segment (vibe-sets/{id}) must be registered before
# the generic /{channel_id} catch-all below - FastAPI/Starlette match routes in
# registration order, and without an explicit {channel_id:int} converter a request for
# "/channels/vibe-sets/5" would otherwise match "/{channel_id}" first and 422 trying to
# parse "vibe-sets" as an int, never reaching this route at all.
@router.get("/vibe-sets/{vibe_set_id}")
def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db)):
vibe_set = db.query(VibeSet).filter(VibeSet.id == vibe_set_id).first()
if not vibe_set:
raise HTTPException(status_code=404, detail="Vibe set not found")
tracks = (
db.query(VibeSetTrack)
.filter(VibeSetTrack.vibe_set_id == vibe_set_id)
.order_by(VibeSetTrack.order)
.all()
)
return {"vibe_set": vibe_set, "tracks": tracks}
@router.get("/{channel_id}")
def get_channel(channel_id: int, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
follower_count = db.query(ChannelFollow).filter(ChannelFollow.channel_id == channel_id).count()
return {"channel": channel, "follower_count": follower_count}
@router.post("/{channel_id}/follow", status_code=status.HTTP_201_CREATED)
def follow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
existing = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if existing:
return existing
follow = ChannelFollow(channel_id=channel_id, user_id=data.user_id)
db.add(follow)
db.commit()
db.refresh(follow)
return follow
@router.post("/{channel_id}/unfollow")
def unfollow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
follow = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if follow:
db.delete(follow)
db.commit()
return {"status": "ok"}
@router.post("/{channel_id}/vibe-sets", status_code=status.HTTP_201_CREATED)
def create_vibe_set(channel_id: int, data: VibeSetCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
vibe_set = VibeSet(channel_id=channel_id, title=data.title, description=data.description)
db.add(vibe_set)
db.commit()
db.refresh(vibe_set)
for i, song_id in enumerate(data.song_ids):
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found")
db.add(VibeSetTrack(vibe_set_id=vibe_set.id, song_id=song_id, order=i))
db.commit()
# SQLAlchemy sessions expire_on_commit by default - the second commit above (for the
# VibeSetTrack rows) re-expires vibe_set's already-loaded attributes even though it
# wasn't touched by that commit, and returning it unrefreshed serializes as {} (no
# error, just silently empty - this is what broke the vibe-set tests). Refresh again
# right before returning.
db.refresh(vibe_set)
return vibe_set
@router.get("/{channel_id}/vibe-sets")
def list_vibe_sets(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return db.query(VibeSet).filter(VibeSet.channel_id == channel_id).order_by(VibeSet.created_at.desc()).all()
@router.post("/{channel_id}/stories", status_code=status.HTTP_201_CREATED)
def create_story(channel_id: int, data: StoryCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {data.song_id} not found")
story = AudioStory(
channel_id=channel_id,
song_id=data.song_id,
caption=data.caption,
expires_at=datetime.now(timezone.utc) + STORY_LIFETIME,
)
db.add(story)
db.commit()
db.refresh(story)
return story
@router.get("/{channel_id}/stories")
def list_active_stories(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
now = datetime.now(timezone.utc)
return (
db.query(AudioStory)
.filter(AudioStory.channel_id == channel_id, AudioStory.expires_at >= now)
.order_by(AudioStory.created_at.desc())
.all()
)
@router.post("/{channel_id}/showcase", status_code=status.HTTP_201_CREATED)
def showcase_post(channel_id: int, data: ShowcaseCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
post = db.query(Post).filter(Post.id == data.post_id).first()
if not post:
raise HTTPException(status_code=400, detail=f"Post {data.post_id} not found")
showcase = ChannelShowcase(channel_id=channel_id, post_id=data.post_id)
db.add(showcase)
db.commit()
db.refresh(showcase)
return showcase
@router.get("/{channel_id}/showcase")
def list_showcase(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return (
db.query(ChannelShowcase)
.filter(ChannelShowcase.channel_id == channel_id)
.order_by(ChannelShowcase.added_at.desc())
.all()
)
import json
import os
import shutil
import uuid
from typing import List, Optional
from fastapi import APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Request, UploadFile
from sqlalchemy.orm import Session
from src.core.database import LibrarySong, RemixJob, get_db
from src.services import storage
from src.services.remix_engine import render_remix_sync
router = APIRouter(prefix="/remix", tags=["AI Remix"])
MAX_SONGS = 5
TEMP_DIR = storage.TEMP_DIR
@router.post("")
async def create_remix(
background_tasks: BackgroundTasks,
prompt: str = Form(..., description="Natural-language description of the remix you want, e.g. 'blend the vocals of the first song over the beat of the second, slowed down and dreamy'"),
files: List[UploadFile] = File(default=[], description="Audio files to remix together"),
library_song_ids: Optional[str] = Form(None, description="Comma-separated LibrarySong IDs to use as sources instead of (or alongside) uploaded files - using library songs is what lets the finished remix link back into the social/remix-tree graph"),
user_id: Optional[int] = Form(None, description="Attributes the resulting library entry and social post to this user"),
db: Session = Depends(get_db),
):
# Deliberately does nothing here except fast local I/O (save uploads, look up library
# rows) - no identify_audio/Shazam/AcoustID calls. Those are real network calls that can
# take ~30s each to time out, and doing them here would block this response for
# potentially minutes with multiple files. All of that happens inside the background
# job instead, where it belongs alongside the rest of the slow pipeline.
parsed_library_ids = [s.strip() for s in (library_song_ids or "").split(",") if s.strip()]
total_requested = len(parsed_library_ids) + len(files)
if total_requested == 0:
raise HTTPException(status_code=400, detail="At least one audio file or library_song_id is required.")
if total_requested > MAX_SONGS:
raise HTTPException(status_code=400, detail=f"At most {MAX_SONGS} songs are supported per remix.")
input_paths = []
filenames = []
source_song_ids = [] # parallel to input_paths: LibrarySong.id if this source came from
# the library (so the finished remix's Post can link back to it),
# None for a fresh upload with no existing library entry.
if library_song_ids:
for raw_id in library_song_ids.split(","):
raw_id = raw_id.strip()
if not raw_id:
continue
try:
song_id = int(raw_id)
except ValueError:
raise HTTPException(status_code=400, detail=f"Invalid library_song_ids value: {raw_id!r}")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found or its file is missing.")
input_paths.append(song.file_path)
filenames.append(song.title or os.path.basename(song.file_path))
source_song_ids.append(song.id)
try:
for f in files:
temp_path = os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{f.filename}")
with open(temp_path, "wb") as buffer:
shutil.copyfileobj(f.file, buffer)
input_paths.append(temp_path)
filenames.append(f.filename)
source_song_ids.append(None)
except Exception as e:
for p in input_paths:
if os.path.exists(p) and p.startswith(TEMP_DIR):
os.remove(p)
raise HTTPException(status_code=500, detail=f"Failed to receive uploaded files: {e}")
job = RemixJob(status="queued", prompt=prompt, input_paths=json.dumps(input_paths))
db.add(job)
db.commit()
db.refresh(job)
background_tasks.add_task(render_remix_sync, job.id, input_paths, prompt, filenames, source_song_ids, user_id)
return {"job_id": job.id, "status": job.status, "status_url": f"/remix/{job.id}"}
@router.get("/{job_id}")
async def get_remix_status(job_id: int, request: Request, db: Session = Depends(get_db)):
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
if not job:
raise HTTPException(status_code=404, detail="Remix job not found.")
response = {
"job_id": job.id,
"status": job.status,
"stage_detail": job.stage_detail,
"remix_name": job.remix_name,
}
if job.plan_json:
response["plan"] = json.loads(job.plan_json)
if job.status == "done" and job.result_filename:
response["download_url"] = f"{str(request.base_url).rstrip('/')}/downloads/{job.result_filename}"
response["library_song_id"] = job.result_song_id
response["post_id"] = job.result_post_id
if job.status == "error":
response["error"] = job.error
return response
from fastapi import APIRouter, Depends, HTTPException, status import time
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom from src.core.database import get_db, SessionLocal, User, Post, GeoDrop, LiveRoom
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services.room_manager import room_manager
from datetime import datetime, timezone from datetime import datetime, timezone
import math import math
...@@ -39,18 +42,27 @@ def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: U ...@@ -39,18 +42,27 @@ def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: U
db.refresh(db_post) db.refresh(db_post)
return db_post return db_post
MAX_TREE_DEPTH = 50 # guards against runaway recursion on pathological/corrupted data;
# normal remix trees (remixes of remixes of remixes...) come nowhere
# close to this in practice.
def _build_remix_tree(post_id: int, db: Session, depth: int = 0) -> dict:
post = db.query(Post).filter(Post.id == post_id).first()
children = db.query(Post).filter(Post.parent_post_id == post_id).all() if depth < MAX_TREE_DEPTH else []
return {
"post": post,
"children": [_build_remix_tree(c.id, db, depth + 1) for c in children],
}
@router.get("/posts/{post_id}/tree") @router.get("/posts/{post_id}/tree")
def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
post = db.query(Post).filter(Post.id == post_id).first() post = db.query(Post).filter(Post.id == post_id).first()
if not post: if not post:
raise HTTPException(status_code=404, detail="Post not found") raise HTTPException(status_code=404, detail="Post not found")
children = db.query(Post).filter(Post.parent_post_id == post_id).all() return _build_remix_tree(post_id, db)
return {
"post": post,
"children": children
}
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED) @router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
...@@ -94,3 +106,126 @@ def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), curren ...@@ -94,3 +106,126 @@ def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), curren
def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all() rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms return rooms
# --- Pass-the-Aux: live room WebSocket ---
# Chat, reactions/fire-meter, presence, and DJ handoff are all in-memory ephemeral state
# (src/services/room_manager.py) - only dj_id and current_song_id persist to the LiveRoom
# row, since those are the only parts that make sense to still be true if someone checks
# the room later via GET /social/rooms rather than being connected live.
def _get_room_or_none(room_id: int):
db = SessionLocal()
try:
return db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
finally:
db.close()
def _set_room_dj(room_id: int, dj_id: int):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.dj_id = dj_id
db.commit()
finally:
db.close()
def _set_room_current_song(room_id: int, song_id):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.current_song_id = song_id
db.commit()
finally:
db.close()
@router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, user_id: int):
room_row = _get_room_or_none(room_id)
if not room_row:
await websocket.close(code=4404)
return
if not room_row.is_active:
await websocket.close(code=4403)
return
await room_manager.connect(room_id, user_id, websocket)
state = room_manager.get_room(room_id)
await websocket.send_json({
"type": "snapshot",
"dj_id": room_row.dj_id,
"current_song_id": room_row.current_song_id,
"presence": room_manager.presence(room_id),
"chat_history": list(state.chat_history),
"fire_count": state.fire_count(),
"dj_queue": state.dj_queue,
})
await room_manager.broadcast(room_id, {"type": "user_joined", "user_id": user_id}, exclude_user_id=user_id)
try:
while True:
data = await websocket.receive_json()
msg_type = data.get("type")
if msg_type == "chat":
text = str(data.get("text", ""))[:500]
if not text.strip():
continue
chat_msg = {"type": "chat", "user_id": user_id, "text": text}
state.chat_history.append(chat_msg)
await room_manager.broadcast(room_id, chat_msg)
elif msg_type == "reaction":
emoji = str(data.get("emoji", "🔥"))[:8]
if emoji == "🔥":
state.fire_events.append(time.time())
await room_manager.broadcast(room_id, {
"type": "reaction", "user_id": user_id, "emoji": emoji, "fire_count": state.fire_count(),
})
elif msg_type == "request_aux":
if user_id != room_row.dj_id and user_id not in state.dj_queue:
state.dj_queue.append(user_id)
await room_manager.broadcast(room_id, {"type": "queue_updated", "dj_queue": state.dj_queue})
elif msg_type == "pass_aux":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can pass the aux."})
continue
next_dj = None
if state.dj_queue:
next_dj = state.dj_queue.pop(0)
else:
requested = data.get("to_user_id")
if requested in state.connections:
next_dj = requested
if next_dj is not None:
room_row.dj_id = next_dj
_set_room_dj(room_id, next_dj)
await room_manager.broadcast(room_id, {"type": "dj_changed", "dj_id": next_dj, "dj_queue": state.dj_queue})
else:
await websocket.send_json({"type": "error", "detail": "No one is waiting to take the aux."})
elif msg_type == "now_playing":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can change what's playing."})
continue
song_id = data.get("song_id")
room_row.current_song_id = song_id
_set_room_current_song(room_id, song_id)
await room_manager.broadcast(room_id, {"type": "now_playing_changed", "song_id": song_id, "dj_id": user_id})
else:
await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"})
except WebSocketDisconnect:
pass
finally:
room_manager.disconnect(room_id, user_id)
await room_manager.broadcast(room_id, {"type": "user_left", "user_id": user_id})
...@@ -254,10 +254,47 @@ ...@@ -254,10 +254,47 @@
<header> <header>
<h1>🎧 Stax<span> API</span> Console</h1> <h1>🎧 Stax<span> API</span> Console</h1>
<span class="badge" id="instance-badge">…</span> <span class="badge" id="instance-badge">…</span>
<a href="/logout" style="margin-left:auto; color:var(--text-dim); font-size:12.5px; text-decoration:none;">Log out</a>
</header> </header>
<main> <main>
<section id="remix-section">
<h2>🎛 AI Remix</h2>
<p class="desc">Upload 1&ndash;5 songs and describe the remix in plain language. Gemini listens to each track and directs the arrangement (sections, harmonic key matching, sidechain, style), and Demucs does the actual stem separation before rendering.</p>
<div class="dropzone" id="remix-drop">
Drop up to 5 audio files here, or click to choose
<input type="file" id="remix-file-input" multiple accept="audio/*">
</div>
<div class="filelist" id="remix-filelist"></div>
<textarea id="remix-prompt" rows="2" placeholder="e.g. Blend the vocals of the first song over the drums of the second, slowed down with heavy reverb"></textarea>
<button class="primary" id="remix-submit">Create Remix</button>
<div class="progress-track" id="remix-progress" style="display:none;">
<div class="progress-step" data-stage="queued">Queued</div>
<div class="progress-step" data-stage="planning">Planning</div>
<div class="progress-step" data-stage="separating">Separating</div>
<div class="progress-step" data-stage="mixing">Mixing</div>
<div class="progress-step" data-stage="mastering">Mastering</div>
<div class="progress-step" data-stage="tagging">Tagging</div>
<div class="progress-step" data-stage="done">Done</div>
</div>
<div class="status-line" id="remix-status"></div>
<div class="result-card" id="remix-result">
<h3 id="remix-result-name"></h3>
<div class="row"><span>Target BPM</span><b id="remix-result-bpm"></b></div>
<div class="row"><span>Target key</span><b id="remix-result-key"></b></div>
<div class="row"><span>Style</span><b id="remix-result-style"></b></div>
<div class="row"><span>Sidechain</span><b id="remix-result-sidechain"></b></div>
<div id="remix-result-sections" style="margin-top:10px;"></div>
<audio controls id="remix-result-audio"></audio>
</div>
</section>
<section id="tag-section"> <section id="tag-section">
<h2>🏷 Tag &amp; Identify</h2> <h2>🏷 Tag &amp; Identify</h2>
<p class="desc">Upload a single untagged track. It's fingerprinted (Shazam/AcoustID, Gemini fallback), tagged with title/artist/album/art/lyrics, and returned as a finished MP3.</p> <p class="desc">Upload a single untagged track. It's fingerprinted (Shazam/AcoustID, Gemini fallback), tagged with title/artist/album/art/lyrics, and returned as a finished MP3.</p>
...@@ -328,6 +365,104 @@ function setupDropzone(dropEl, inputEl, listEl, multiple) { ...@@ -328,6 +365,104 @@ function setupDropzone(dropEl, inputEl, listEl, multiple) {
return { getFiles: () => files }; return { getFiles: () => files };
} }
// ---------- Remix flow ----------
const remixDz = setupDropzone($('#remix-drop'), $('#remix-file-input'), $('#remix-filelist'), true);
function setRemixStage(stage, isError) {
$$('#remix-progress .progress-step').forEach(el => {
el.classList.remove('active', 'done', 'error');
const order = ['queued','planning','separating','mixing','mastering','tagging','done'];
const cur = order.indexOf(stage);
const idx = order.indexOf(el.dataset.stage);
if (isError && idx === cur) el.classList.add('error');
else if (idx < cur || (idx === cur && stage === 'done')) el.classList.add('done');
else if (idx === cur) el.classList.add('active');
});
}
$('#remix-submit').addEventListener('click', async () => {
const files = remixDz.getFiles();
const prompt = $('#remix-prompt').value.trim();
const statusEl = $('#remix-status');
const resultEl = $('#remix-result');
resultEl.classList.remove('show');
if (!files.length) { statusEl.textContent = 'Add at least one audio file first.'; statusEl.className = 'status-line error'; return; }
if (!prompt) { statusEl.textContent = 'Describe the remix you want first.'; statusEl.className = 'status-line error'; return; }
$('#remix-submit').disabled = true;
$('#remix-progress').style.display = 'flex';
setRemixStage('queued', false);
statusEl.className = 'status-line';
statusEl.innerHTML = '<span class="loading-spin"></span>Submitting…';
const form = new FormData();
form.append('prompt', prompt);
files.forEach(f => form.append('files', f));
try {
const res = await fetch('/remix', { method: 'POST', body: form, credentials: 'same-origin' });
if (!res.ok) throw new Error((await res.json()).detail || res.statusText);
const job = await res.json();
statusEl.innerHTML = `<span class="loading-spin"></span>Job #${job.job_id} queued…`;
poll(job.job_id);
} catch (e) {
statusEl.textContent = 'Failed to submit: ' + e.message;
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
}
async function poll(jobId) {
try {
const res = await fetch(`/remix/${jobId}`, { credentials: 'same-origin' });
const data = await res.json();
setRemixStage(data.status, data.status === 'error');
if (data.status === 'error') {
statusEl.textContent = 'Remix failed: ' + (data.error || 'unknown error');
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
return;
}
statusEl.innerHTML = `<span class="loading-spin"></span>${data.stage_detail || data.status}`;
if (data.status === 'done') {
statusEl.textContent = 'Done.';
$('#remix-submit').disabled = false;
$('#remix-result-name').textContent = data.remix_name || 'Remix';
if (data.plan) {
const p = data.plan;
const noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
$('#remix-result-bpm').textContent = p.target_bpm ?? '—';
$('#remix-result-key').textContent = (p.target_key_tonic !== undefined) ? noteNames[p.target_key_tonic] : '—';
$('#remix-result-style').textContent = p.style && p.style !== 'none' ? p.style : 'none';
$('#remix-result-sidechain').textContent = (p.sidechain && p.sidechain.enabled)
? `on (song #${p.sidechain.source_index} drums, ${Math.round((p.sidechain.amount||0)*100)}%)`
: 'off';
const sectionsEl = $('#remix-result-sections');
sectionsEl.innerHTML = '';
(p.sections || []).forEach(section => {
const row = document.createElement('div');
row.className = 'section-row';
const roles = (section.song_roles || [])
.map(r => `#${r.index}: ${(r.stems || []).join('+') || 'none'}`)
.join(' · ');
row.innerHTML = `<span class="section-name">${section.name}</span><span class="section-range">${Math.round(section.start_fraction*100)}%&ndash;${Math.round(section.end_fraction*100)}%</span><div class="section-roles">${roles || 'nothing active'}</div>`;
sectionsEl.appendChild(row);
});
}
$('#remix-result-audio').src = data.download_url;
resultEl.classList.add('show');
return;
}
setTimeout(() => poll(jobId), 2500);
} catch (e) {
statusEl.textContent = 'Lost connection while polling: ' + e.message;
statusEl.className = 'status-line error';
$('#remix-submit').disabled = false;
}
}
});
// ---------- Tag flow ---------- // ---------- Tag flow ----------
const tagDz = setupDropzone($('#tag-drop'), $('#tag-file-input'), $('#tag-filelist'), false); const tagDz = setupDropzone($('#tag-drop'), $('#tag-file-input'), $('#tag-filelist'), false);
......
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stax API Console - Login</title>
<style>
:root {
--bg: #0D0F12;
--panel: #14171C;
--panel-2: #1B1F26;
--border: #262B33;
--text: #E7ECF2;
--text-dim: #8A93A3;
--accent: #00E5FF;
--accent-dim: #00B8CC;
--bad: #FF5C7A;
}
* { box-sizing: border-box; }
html, body {
height: 100%;
margin: 0;
}
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.card {
width: 100%;
max-width: 340px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 32px;
margin: 20px;
}
.card h1 {
font-size: 19px;
margin: 0 0 4px 0;
text-align: center;
}
.card h1 span { color: var(--accent); }
.card p.sub {
text-align: center;
color: var(--text-dim);
font-size: 12.5px;
margin: 0 0 24px 0;
}
label {
display: block;
font-size: 11.5px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.04em;
margin-bottom: 6px;
}
input {
width: 100%;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
padding: 11px 12px;
font-size: 14px;
margin-bottom: 16px;
}
input:focus { outline: none; border-color: var(--accent); }
button {
width: 100%;
background: var(--accent);
color: #06141A;
border: none;
border-radius: 8px;
padding: 12px;
font-weight: 700;
font-size: 14px;
cursor: pointer;
margin-top: 4px;
}
button:hover { background: var(--accent-dim); }
.error {
display: none;
background: rgba(255, 92, 122, 0.1);
border: 1px solid var(--bad);
color: var(--bad);
border-radius: 8px;
padding: 10px 12px;
font-size: 12.5px;
margin-bottom: 16px;
text-align: center;
}
.error.show { display: block; }
</style>
</head>
<body>
<div class="card">
<h1>🎧 Stax<span> API</span></h1>
<p class="sub">Sign in to view the API console</p>
<div class="error" id="error-box">Incorrect username or password.</div>
<form method="post" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" autocomplete="current-password" required>
<button type="submit">Sign In</button>
</form>
</div>
<script>
if (new URLSearchParams(location.search).get('error') === '1') {
document.getElementById('error-box').classList.add('show');
}
</script>
</body>
</html>
...@@ -145,9 +145,108 @@ class IdentifiedTrack(Base): ...@@ -145,9 +145,108 @@ class IdentifiedTrack(Base):
lyrics = Column(String) lyrics = Column(String)
identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Correction(Base):
__tablename__ = "corrections"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True)
title = Column(String)
artist = Column(String)
source = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RemixJob(Base):
__tablename__ = "remix_jobs"
id = Column(Integer, primary_key=True, index=True)
status = Column(String, default="queued") # queued, planning, separating, mixing, mastering, tagging, done, error
stage_detail = Column(String, nullable=True)
prompt = Column(String)
input_paths = Column(String) # JSON-encoded list of source file paths
plan_json = Column(String, nullable=True) # the AI-generated remix plan, once produced
remix_name = Column(String, nullable=True)
result_filename = Column(String, nullable=True)
result_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True) # set once the finished remix is registered in the library
result_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True) # set once the finished remix is posted to the social feed
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))
# --- Channels: the creator hub. Users host a channel and publish Vibe Sets (curated song
# collections), Audio Stories (ephemeral short clips), and showcase specific remixes
# (existing Posts) - the one pillar from the original vision doc with nothing built at all
# before this.
class Channel(Base):
__tablename__ = "channels"
id = Column(Integer, primary_key=True, index=True)
owner_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
avatar_url = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class ChannelFollow(Base):
__tablename__ = "channel_follows"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
followed_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSet(Base):
__tablename__ = "vibe_sets"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
title = Column(String)
description = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSetTrack(Base):
__tablename__ = "vibe_set_tracks"
id = Column(Integer, primary_key=True, index=True)
vibe_set_id = Column(Integer, ForeignKey("vibe_sets.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
class AudioStory(Base):
__tablename__ = "audio_stories"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
caption = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
expires_at = Column(DateTime) # default 24h from creation, set at insert time (matches
# the existing DiscoveredSong 24h-history pattern: rows
# aren't deleted on expiry, just filtered out of "active"
# queries - see get_active_stories in channels.py)
class ChannelShowcase(Base):
__tablename__ = "channel_showcases"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
post_id = Column(Integer, ForeignKey("posts.id"), index=True)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def get_db(): def get_db():
db = SessionLocal() db = SessionLocal()
try: try:
yield db yield db
finally: finally:
db.close() db.close()
def init_db():
"""Schema is normally created/updated via `alembic upgrade head` (see alembic/). This is
a defensive fallback for src/telegram_bot/bot.py, which calls it before starting in case
the bot runs as a standalone process before migrations have ever been applied - create_all
only fills in missing tables, it won't conflict with Alembic-managed ones."""
Base.metadata.create_all(bind=engine)
def log_correction(user_id: int, title: str, artist: str, source: str):
"""Records a user's manual song-ID correction/confirmation from the Telegram bot flow
(picking from candidates, typing manually, or confirming a Gemini guess) as a simple
audit trail - was called from bot.py but never implemented anywhere."""
db = SessionLocal()
try:
db.add(Correction(user_id=user_id, title=title, artist=artist, source=source))
db.commit()
finally:
db.close()
import os import os
import shutil
import aiohttp import aiohttp
from pydub import AudioSegment from pydub import AudioSegment
from mutagen.mp3 import MP3 from mutagen.mp3 import MP3
...@@ -18,7 +19,6 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -18,7 +19,6 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
# 1. Convert to MP3 (or skip if already MP3) # 1. Convert to MP3 (or skip if already MP3)
if raw_file_path.lower().endswith('.mp3'): if raw_file_path.lower().endswith('.mp3'):
mp3_file_path = f"{raw_file_path}_tagged.mp3" mp3_file_path = f"{raw_file_path}_tagged.mp3"
import shutil
shutil.copyfile(raw_file_path, mp3_file_path) shutil.copyfile(raw_file_path, mp3_file_path)
else: else:
mp3_file_path = f"{raw_file_path}.mp3" mp3_file_path = f"{raw_file_path}.mp3"
...@@ -55,11 +55,14 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -55,11 +55,14 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
# Persian text saved as v2.3+UTF-8 renders as mojibake in many players. # Persian text saved as v2.3+UTF-8 renders as mojibake in many players.
mp3.save(v2_version=4) mp3.save(v2_version=4)
# 3. Rename file # 3. Move into place. shutil.move (not os.rename) - the source lives under a temp dir
# that can be a different filesystem/mount from the destination (e.g. a separate CI
# build volume), and os.rename raises "Invalid cross-device link" (EXDEV) whenever
# source and destination aren't on the same filesystem. shutil.move falls back to a
# copy+delete in that case, so it works regardless of the deployment's mount topology.
safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip() safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip()
final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3" final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3"
import shutil as _shutil
final_path = os.path.join(os.path.dirname(mp3_file_path) or ".", final_filename) final_path = os.path.join(os.path.dirname(mp3_file_path) or ".", final_filename)
_shutil.move(mp3_file_path, final_path) shutil.move(mp3_file_path, final_path)
return final_path return final_path
This diff is collapsed.
import time
from collections import deque
from fastapi import WebSocket
MAX_CHAT_HISTORY = 50
FIRE_DECAY_SECONDS = 30 # a "fire meter" reading is how many 🔥 reactions landed in the
# last N seconds, not a lifetime total - it should visibly cool
# off when the room isn't currently popping.
class RoomState:
"""All in-memory, per-room, ephemeral live-session state. None of this is meant to
survive a process restart - it's the equivalent of "who's in the room right now,"
not a historical record. LiveRoom.dj_id/current_song_id in the DB are the durable
parts, updated alongside this."""
def __init__(self):
self.connections: dict[int, WebSocket] = {} # user_id -> websocket
self.chat_history: deque = deque(maxlen=MAX_CHAT_HISTORY)
self.dj_queue: list = [] # user_ids waiting to be handed the aux
self.fire_events: deque = deque() # timestamps of recent fire reactions
def fire_count(self) -> int:
cutoff = time.time() - FIRE_DECAY_SECONDS
while self.fire_events and self.fire_events[0] < cutoff:
self.fire_events.popleft()
return len(self.fire_events)
class RoomConnectionManager:
def __init__(self):
self.rooms: dict[int, RoomState] = {}
def get_room(self, room_id: int) -> RoomState:
if room_id not in self.rooms:
self.rooms[room_id] = RoomState()
return self.rooms[room_id]
async def connect(self, room_id: int, user_id: int, websocket: WebSocket):
await websocket.accept()
self.get_room(room_id).connections[user_id] = websocket
def disconnect(self, room_id: int, user_id: int):
room = self.rooms.get(room_id)
if not room:
return
room.connections.pop(user_id, None)
if user_id in room.dj_queue:
room.dj_queue.remove(user_id)
# An empty room's ephemeral state (chat history, fire meter, queue) is discarded -
# the next person to join starts a fresh session, matching how a live room should
# behave once everyone's left.
if not room.connections:
self.rooms.pop(room_id, None)
async def broadcast(self, room_id: int, message: dict, exclude_user_id: int = None):
room = self.rooms.get(room_id)
if not room:
return
dead = []
for uid, ws in list(room.connections.items()):
if uid == exclude_user_id:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(uid)
for uid in dead:
room.connections.pop(uid, None)
def presence(self, room_id: int) -> list:
room = self.rooms.get(room_id)
return list(room.connections.keys()) if room else []
room_manager = RoomConnectionManager()
...@@ -22,6 +22,11 @@ def test_auth_request_code_upstream_failure_returns_400(client, mocker): ...@@ -22,6 +22,11 @@ def test_auth_request_code_upstream_failure_returns_400(client, mocker):
assert response.status_code == 400 assert response.status_code == 400
def test_auth_request_code_missing_field(client):
response = client.post("/auth/request_code", json={})
assert response.status_code == 422
def test_auth_request_code_rate_limited_per_phone(client, mocker): def test_auth_request_code_rate_limited_per_phone(client, mocker):
mocker.patch( mocker.patch(
"src.telegram_worker.telegram_auth.request_code", "src.telegram_worker.telegram_auth.request_code",
...@@ -41,6 +46,7 @@ def test_auth_login_missing_fields(client): ...@@ -41,6 +46,7 @@ def test_auth_login_missing_fields(client):
assert response.status_code == 422 assert response.status_code == 422
def test_auth_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker): def test_auth_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker):
mocker.patch( mocker.patch(
"src.telegram_worker.telegram_auth.login", "src.telegram_worker.telegram_auth.login",
...@@ -105,3 +111,17 @@ def test_auth_chats_with_token(client, auth_as, mocker): ...@@ -105,3 +111,17 @@ def test_auth_chats_with_token(client, auth_as, mocker):
response = client.get("/auth/chats", headers=headers) response = client.get("/auth/chats", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert response.json()["chats"][0]["title"] == "Test Chat" assert response.json()["chats"][0]["title"] == "Test Chat"
def test_auth_chats_music_with_token(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch(
"src.telegram_worker.telegram_sync.get_chat_music",
return_value=[{"message_id": 1, "title": "Song", "artist": "Someone", "duration": 180, "file_name": "song.mp3"}],
)
response = client.get("/auth/chats/123/music", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert len(body["music"]) == 1
assert body["music"][0]["title"] == "Song"
import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import AudioStory, Channel, LibrarySong, Post, SessionLocal
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes")
defaults = dict(title="Song", artist="Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id
finally:
db.close()
def _make_channel(client, owner_id=1, name="Test Channel"):
response = client.post("/channels", json={"owner_id": owner_id, "name": name})
assert response.status_code == 201
return response.json()["id"]
def test_create_and_list_channels(client):
channel_id = _make_channel(client, owner_id=1, name="DJ Test's Channel")
response = client.get("/channels")
assert response.status_code == 200
assert any(c["id"] == channel_id for c in response.json())
def test_get_channel_detail_with_follower_count(client):
channel_id = _make_channel(client)
response = client.get(f"/channels/{channel_id}")
assert response.status_code == 200
body = response.json()
assert body["channel"]["id"] == channel_id
assert body["follower_count"] == 0
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
response = client.get(f"/channels/{channel_id}")
assert response.json()["follower_count"] == 1
def test_get_unknown_channel_404s(client):
response = client.get("/channels/999999")
assert response.status_code == 404
def test_follow_is_idempotent(client):
channel_id = _make_channel(client)
r1 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
r2 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert r1.status_code == 201
assert r2.status_code == 201
assert r1.json()["id"] == r2.json()["id"]
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
def test_unfollow(client):
channel_id = _make_channel(client)
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
response = client.post(f"/channels/{channel_id}/unfollow", json={"user_id": 2})
assert response.status_code == 200
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 0
def test_create_vibe_set_with_tracks_owner_only(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Vibe Track")
forbidden = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 999, "title": "Not mine", "song_ids": [song_id]},
)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 1, "title": "Sunday Chill", "song_ids": [song_id]},
)
assert response.status_code == 201
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
body = detail.json()
assert body["vibe_set"]["title"] == "Sunday Chill"
assert len(body["tracks"]) == 1
assert body["tracks"][0]["song_id"] == song_id
listing = client.get(f"/channels/{channel_id}/vibe-sets")
assert listing.status_code == 200
assert any(v["id"] == vibe_set_id for v in listing.json())
def test_vibe_set_route_ordering_not_swallowed_by_channel_id(client):
# /channels/vibe-sets/{id} must not be intercepted by the /{channel_id} catch-all
channel_id = _make_channel(client)
response = client.post(
f"/channels/{channel_id}/vibe-sets", json={"user_id": 1, "title": "x", "song_ids": []}
)
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
assert detail.json()["vibe_set"]["id"] == vibe_set_id
def test_unknown_vibe_set_404s(client):
response = client.get("/channels/vibe-sets/999999")
assert response.status_code == 404
def test_create_story_owner_only_and_expiry(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Story Clip")
forbidden = client.post(f"/channels/{channel_id}/stories", json={"user_id": 999, "song_id": song_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/stories", json={"user_id": 1, "song_id": song_id, "caption": "vibes"})
assert response.status_code == 201
story_id = response.json()["id"]
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert any(s["id"] == story_id for s in active.json())
def test_expired_stories_are_filtered_from_active_listing(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Old Clip")
db = SessionLocal()
try:
expired = AudioStory(
channel_id=channel_id, song_id=song_id, caption="old",
expires_at=datetime.now(timezone.utc) - timedelta(hours=1),
)
db.add(expired)
db.commit()
expired_id = expired.id
finally:
db.close()
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert not any(s["id"] == expired_id for s in active.json())
def test_showcase_owner_only(client, auth_as):
headers, user = auth_as()
channel_id = _make_channel(client, owner_id=user.id)
song_id = _make_library_song(title="Showcased")
post_response = client.post("/social/posts", json={"song_id": song_id, "caption": "check it"}, headers=headers)
post_id = post_response.json()["id"]
forbidden = client.post(f"/channels/{channel_id}/showcase", json={"user_id": 999, "post_id": post_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/showcase", json={"user_id": user.id, "post_id": post_id})
assert response.status_code == 201
listing = client.get(f"/channels/{channel_id}/showcase")
assert listing.status_code == 200
assert any(s["post_id"] == post_id for s in listing.json())
from src.core.database import Correction, SessionLocal, init_db, log_correction
def test_init_db_is_idempotent():
# Should not raise even when tables already exist (called at import time too)
init_db()
init_db()
def test_log_correction_persists_a_row():
log_correction(user_id=42, title="Test Song", artist="Test Artist", source="Manual Entry")
db = SessionLocal()
try:
row = (
db.query(Correction)
.filter(Correction.user_id == 42, Correction.title == "Test Song")
.order_by(Correction.id.desc())
.first()
)
assert row is not None
assert row.artist == "Test Artist"
assert row.source == "Manual Entry"
finally:
db.close()
import io
from src.api.routers import discovery as discovery_router
from src.core.database import DiscoveredSong from src.core.database import DiscoveredSong
...@@ -41,3 +44,56 @@ def test_discovery_swipe_other_users_song_not_found(client, db_session, auth_as) ...@@ -41,3 +44,56 @@ def test_discovery_swipe_other_users_song_not_found(client, db_session, auth_as)
response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers_b) response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers_b)
assert response.status_code == 404 assert response.status_code == 404
def _dummy_audio_file():
return ("clip.mp3", io.BytesIO(b"not-real-audio-bytes-but-thats-fine-for-this-mock"), "audio/mpeg")
def test_discovery_listen_success_creates_row(client, db_session, auth_as, monkeypatch):
headers, user = auth_as()
async def _fake_identify_hit(path):
return [{"title": "Dummy Song", "artist": "Dummy Artist", "genre": "Pop", "coverart": "http://example.com/art.jpg"}]
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["detected"]["title"] == "Dummy Song"
row = db_session.query(DiscoveredSong).filter(DiscoveredSong.id == body["discovery_id"]).first()
assert row is not None
assert row.user_id == user.id
assert row.title == "Dummy Song"
assert row.artist == "Dummy Artist"
def test_discovery_listen_no_match(client, auth_as, monkeypatch):
headers, _ = auth_as()
async def _fake_identify_miss(path):
return []
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_miss)
response = client.post("/discovery/listen", headers=headers, files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "error"
assert "message" in body
def test_discovery_swipe_success_updates_liked(client, db_session, auth_as):
headers, user = auth_as()
song = DiscoveredSong(user_id=user.id, title="Swipe Me", artist="Someone", genre="Rock")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers)
assert response.status_code == 200
assert response.json()["status"] == "success"
db_session.refresh(song)
assert song.liked is True
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
def test_docs_redirects_to_login_when_unauthenticated(client):
response = client.get("/docs", follow_redirects=False)
assert response.status_code in (302, 307)
assert response.headers["location"] == "/login"
def test_login_page_renders(client):
response = client.get("/login")
assert response.status_code == 200
assert "Sign in to view the API console" in response.text
def test_login_wrong_credentials_redirects_with_error(client):
response = client.post(
"/login", data={"username": "wrong", "password": "wrong"}, follow_redirects=False
)
assert response.status_code == 303
assert response.headers["location"] == "/login?error=1"
assert "stax_docs_session" not in response.cookies
def test_login_correct_credentials_sets_session_and_unlocks_docs(client):
response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert response.status_code == 303
assert response.headers["location"] == "/docs"
assert "stax_docs_session" in response.cookies
docs_response = client.get("/docs")
assert docs_response.status_code == 200
assert "Stax API Console" in docs_response.text
openapi_response = client.get("/openapi.json")
assert openapi_response.status_code == 200
def test_basic_auth_fallback_still_works(client):
response = client.get("/openapi.json", auth=(DOCS_USERNAME, DOCS_PASSWORD))
assert response.status_code == 200
def test_logout_clears_session(client):
login_response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert "stax_docs_session" in login_response.cookies
logout_response = client.get("/logout", follow_redirects=False)
assert logout_response.status_code in (302, 307)
docs_response = client.get("/docs", follow_redirects=False)
assert docs_response.status_code in (302, 307)
assert docs_response.headers["location"] == "/login"
from src.core.database import LibrarySong import os
import tempfile
from src.core.database import LibrarySong, PlaylistTrack
def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"): def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"):
...@@ -9,6 +12,21 @@ def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"): ...@@ -9,6 +12,21 @@ def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"):
return song return song
def _make_library_song(db_session, user_id, **overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for stream test")
defaults = dict(user_id=user_id, title="Test Song", artist="Test Artist", album="Test Album", genre="Pop", lyrics="la la la", file_path=path)
defaults.update(overrides)
song = LibrarySong(**defaults)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
return song, path
def test_library_requires_auth(client): def test_library_requires_auth(client):
response = client.get("/library") response = client.get("/library")
assert response.status_code == 401 assert response.status_code == 401
...@@ -41,6 +59,30 @@ def test_library_search_scoped(client, db_session, auth_as): ...@@ -41,6 +59,30 @@ def test_library_search_scoped(client, db_session, auth_as):
assert len(response.json()["results"]) == 1 assert len(response.json()["results"]) == 1
def test_library_search_finds_match(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id, title="Unique Searchable Title Xyzzy")
try:
response = client.post("/library/search", data={"query": "Xyzzy"}, headers=headers)
assert response.status_code == 200
results = response.json()["results"]
assert any(r["id"] == song.id for r in results)
finally:
os.remove(path)
def test_library_stream_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for stream test"
assert response.headers["content-type"] == "audio/mpeg"
finally:
os.remove(path)
def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as): def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as):
headers_a, user_a = auth_as() headers_a, user_a = auth_as()
headers_b, user_b = auth_as() headers_b, user_b = auth_as()
...@@ -50,6 +92,40 @@ def test_library_stream_not_found_for_other_users_song(client, db_session, auth_ ...@@ -50,6 +92,40 @@ def test_library_stream_not_found_for_other_users_song(client, db_session, auth_
assert response.status_code == 404 assert response.status_code == 404
def test_library_stream_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/stream/99999", headers=headers)
assert response.status_code == 404
def test_library_stream_missing_file_on_disk(client, db_session, auth_as):
headers, user = auth_as()
song = LibrarySong(user_id=user.id, title="Ghost Song", artist="Nobody", file_path="/tmp/does_not_exist_xyz.mp3")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
response = client.get(f"/library/stream/{song.id}", headers=headers)
assert response.status_code == 404
def test_library_lyrics_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id, lyrics="these are the test lyrics")
try:
response = client.get(f"/library/lyrics/{song.id}", headers=headers)
assert response.status_code == 200
assert response.json()["lyrics"] == "these are the test lyrics"
finally:
os.remove(path)
def test_library_lyrics_unknown_id(client, auth_as):
headers, _ = auth_as()
response = client.get("/library/lyrics/99999", headers=headers)
assert response.status_code == 404
def test_playlists_endpoints(client, auth_as): def test_playlists_endpoints(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.get("/playlists", headers=headers) response = client.get("/playlists", headers=headers)
...@@ -61,6 +137,7 @@ def test_playlists_endpoints(client, auth_as): ...@@ -61,6 +137,7 @@ def test_playlists_endpoints(client, auth_as):
playlist_id = response.json()["playlist"]["id"] playlist_id = response.json()["playlist"]["id"]
response = client.get("/playlists", headers=headers) response = client.get("/playlists", headers=headers)
assert response.status_code == 200
playlists = response.json()["playlists"] playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists) assert any(p["id"] == playlist_id for p in playlists)
...@@ -78,3 +155,31 @@ def test_playlist_add_invalid(client, auth_as): ...@@ -78,3 +155,31 @@ def test_playlist_add_invalid(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.post("/playlists/99999/add", data={"song_id": 99999}, headers=headers) response = client.post("/playlists/99999/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404 assert response.status_code == 404
def test_playlist_add_success(client, db_session, auth_as):
headers, user = auth_as()
song, path = _make_library_song(db_session, user.id)
try:
pl_response = client.post("/playlists", json={"name": "Add Test Playlist"}, headers=headers)
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["status"] == "success"
track = db_session.query(PlaylistTrack).filter(
PlaylistTrack.playlist_id == playlist_id, PlaylistTrack.song_id == song.id
).first()
assert track is not None
finally:
os.remove(path)
def test_playlist_add_song_not_found(client, auth_as):
headers, _ = auth_as()
pl_response = client.post("/playlists", json={"name": "Another Playlist"}, headers=headers)
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404
import io
import os
import tempfile
from src.api.routers import remix as remix_router
from src.core.database import LibrarySong, SessionLocal
def _wav_bytes():
# A tiny valid WAV file is enough - the engine itself is mocked out below,
# these tests only exercise the API contract (validation, job bookkeeping).
import struct
sample_rate = 8000
samples = b"\x00\x00" * sample_rate # 1 second of silence, 16-bit mono
data_size = len(samples)
header = struct.pack(
"<4sI4s4sIHHIIHH4sI",
b"RIFF", 36 + data_size, b"WAVE", b"fmt ", 16, 1, 1,
sample_rate, sample_rate * 2, 2, 16, b"data", data_size,
)
return header + samples
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".wav", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(_wav_bytes())
defaults = dict(title="Library Song", artist="Library Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id, path
finally:
db.close()
def test_remix_requires_at_least_one_file(client):
response = client.post("/remix", data={"prompt": "make it slower"}, files=[])
assert response.status_code == 400
def test_remix_rejects_more_than_five_songs(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
files = [("files", (f"song{i}.wav", io.BytesIO(_wav_bytes()), "audio/wav")) for i in range(6)]
response = client.post("/remix", data={"prompt": "mashup"}, files=files)
assert response.status_code == 400
def test_remix_does_not_call_identify_audio_before_responding(client, monkeypatch):
# The whole point of the earlier fix: identify_audio (real Shazam/AcoustID network
# calls, ~30s each on a miss) must never run inside the request/response cycle - only
# inside the background job. If someone re-adds it to the endpoint, this call would
# hang/raise instead of the fast, synchronous response below.
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["job_id"] = job_id
captured["input_paths"] = input_paths
captured["prompt"] = prompt
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
assert not hasattr(remix_router, "identify_audio"), (
"identify_audio got imported back into the router - it belongs in the "
"background job (remix_engine.render_remix_sync), not the request handler."
)
files = [
("files", ("song_a.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
("files", ("song_b.wav", io.BytesIO(_wav_bytes()), "audio/wav")),
]
response = client.post("/remix", data={"prompt": "blend the vocals of the first over the beat of the second"}, files=files)
assert response.status_code == 200
body = response.json()
assert body["status"] == "queued"
job_id = body["job_id"]
status_response = client.get(f"/remix/{job_id}")
assert status_response.status_code == 200
assert status_response.json()["job_id"] == job_id
assert captured["job_id"] == job_id
assert len(captured["input_paths"]) == 2
assert captured["filenames"] == ["song_a.wav", "song_b.wav"]
assert captured["source_song_ids"] == [None, None]
assert captured["user_id"] is None
def test_remix_accepts_library_song_ids(client, monkeypatch):
song_id, path = _make_library_song()
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["input_paths"] = input_paths
captured["filenames"] = filenames
captured["source_song_ids"] = source_song_ids
captured["user_id"] = user_id
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
response = client.post(
"/remix",
data={"prompt": "remix this", "library_song_ids": str(song_id), "user_id": "7"},
)
assert response.status_code == 200
assert captured["input_paths"] == [path]
assert captured["filenames"] == ["Library Song"]
assert captured["source_song_ids"] == [song_id]
assert captured["user_id"] == 7
finally:
os.remove(path)
def test_remix_rejects_unknown_library_song_id(client, monkeypatch):
monkeypatch.setattr(remix_router, "render_remix_sync", lambda *a, **kw: None)
response = client.post("/remix", data={"prompt": "remix this", "library_song_ids": "999999"})
assert response.status_code == 400
def test_remix_mixes_library_songs_and_uploads(client, monkeypatch):
song_id, path = _make_library_song(title="From Library")
try:
captured = {}
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
captured["source_song_ids"] = source_song_ids
captured["filenames"] = filenames
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("uploaded.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post(
"/remix",
data={"prompt": "mashup", "library_song_ids": str(song_id)},
files=files,
)
assert response.status_code == 200
assert captured["source_song_ids"] == [song_id, None]
assert captured["filenames"] == ["From Library", "uploaded.wav"]
finally:
os.remove(path)
def test_remix_status_surfaces_library_and_post_ids_when_done(client, monkeypatch):
from src.core.database import RemixJob, SessionLocal as SL
def fake_render(job_id, input_paths, prompt, filenames, source_song_ids=None, user_id=None):
db = SL()
try:
job = db.query(RemixJob).filter(RemixJob.id == job_id).first()
job.status = "done"
job.result_filename = "fake.mp3"
job.result_song_id = 123
job.result_post_id = 456
db.commit()
finally:
db.close()
monkeypatch.setattr(remix_router, "render_remix_sync", fake_render)
files = [("files", ("song.wav", io.BytesIO(_wav_bytes()), "audio/wav"))]
response = client.post("/remix", data={"prompt": "test"}, files=files)
job_id = response.json()["job_id"]
status_response = client.get(f"/remix/{job_id}")
body = status_response.json()
assert body["status"] == "done"
assert body["library_song_id"] == 123
assert body["post_id"] == 456
def test_remix_status_404_for_unknown_job(client):
response = client.get("/remix/999999")
assert response.status_code == 404
import os
import numpy as np
from src.services.remix_engine import (
_coerce_gain_db,
_pad_add,
_semitone_shift_to_key,
_sidechain_gain_envelope,
_tile_to_length,
detect_key,
)
def test_coerce_gain_db_passes_through_numbers():
assert _coerce_gain_db(-3.0) == -3.0
assert _coerce_gain_db(0) == 0.0
def test_coerce_gain_db_averages_per_stem_dict():
# Observed live from Gemini: a per-stem breakdown instead of the single float the
# schema asks for, when a song_role lists multiple stems.
assert _coerce_gain_db({"drums": -6.0, "other": 0.0}) == -3.0
def test_coerce_gain_db_falls_back_to_zero_for_junk():
assert _coerce_gain_db(None) == 0.0
assert _coerce_gain_db("loud") == 0.0
assert _coerce_gain_db({}) == 0.0
def test_semitone_shift_same_key_is_zero():
assert _semitone_shift_to_key(3, 3) == 0
def test_semitone_shift_picks_smallest_magnitude_direction():
# C (0) -> F# (6): exactly 6 either way, must be within [-6, 6]
shift = _semitone_shift_to_key(0, 6)
assert shift in (-6, 6)
# C (0) -> C# (1): +1 is closer than -11
assert _semitone_shift_to_key(0, 1) == 1
# C (0) -> B (11): -1 is closer than +11
assert _semitone_shift_to_key(0, 11) == -1
def test_semitone_shift_always_in_range():
for a in range(12):
for b in range(12):
shift = _semitone_shift_to_key(a, b)
assert -6 <= shift <= 6
assert (a + shift) % 12 == b
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
def test_detect_key_returns_valid_structure():
key = detect_key(os.path.join(FIXTURES_DIR, "tone.wav"))
assert 0 <= key["tonic"] <= 11
assert key["mode"] in ("major", "minor")
assert key["name"] == f"{['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'][key['tonic']]} {key['mode']}"
def test_sidechain_envelope_ducks_loud_regions_more():
sr = 8000
silence = np.zeros(sr, dtype=np.float32)
loud = np.ones(sr, dtype=np.float32)
source = np.concatenate([silence, loud])
envelope = _sidechain_gain_envelope(source, sr, amount=0.8)
assert envelope.shape == source.shape
assert envelope.min() >= 0.2 - 1e-6 # amount=0.8 -> floor of 1-0.8=0.2
assert envelope.max() <= 1.0
# the loud region should be ducked more (lower gain) than the silent region
assert envelope[:sr].mean() > envelope[sr:].mean()
def test_pad_add_matches_longer_length():
a = np.array([1.0, 2.0, 3.0], dtype=np.float32)
b = np.array([10.0, 20.0], dtype=np.float32)
result = _pad_add(a, b)
assert len(result) == 3
assert np.allclose(result, [11.0, 22.0, 3.0])
def test_tile_to_length_extends_short_audio():
audio = np.array([1.0, 2.0], dtype=np.float32)
result = _tile_to_length(audio, 5)
assert len(result) == 5
assert np.allclose(result, [1.0, 2.0, 1.0, 2.0, 1.0])
def test_tile_to_length_truncates_long_audio():
audio = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
result = _tile_to_length(audio, 2)
assert np.allclose(result, [1.0, 2.0])
def test_tile_to_length_handles_empty_audio():
result = _tile_to_length(np.array([], dtype=np.float32), 4)
assert len(result) == 4
assert np.allclose(result, 0)
from src.core.database import LiveRoom, SessionLocal
def _make_room(dj_id=1, name="Test Room"):
db = SessionLocal()
try:
room = LiveRoom(dj_id=dj_id, name=name, is_active=True)
db.add(room)
db.commit()
db.refresh(room)
return room.id
finally:
db.close()
def test_websocket_closes_for_unknown_room(client):
from starlette.websockets import WebSocketDisconnect
import pytest
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/social/rooms/999999/ws?user_id=1"):
pass
def test_websocket_snapshot_on_connect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
snapshot = ws.receive_json()
assert snapshot["type"] == "snapshot"
assert snapshot["dj_id"] == 1
assert snapshot["presence"] == [1]
assert snapshot["chat_history"] == []
assert snapshot["fire_count"] == 0
assert snapshot["dj_queue"] == []
def test_websocket_broadcasts_chat_between_clients(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
joined = ws1.receive_json()
assert joined == {"type": "user_joined", "user_id": 2}
ws2.send_json({"type": "chat", "text": "hey everyone"})
chat_on_ws1 = ws1.receive_json()
assert chat_on_ws1 == {"type": "chat", "user_id": 2, "text": "hey everyone"}
# Broadcasts (chat/reactions) intentionally include the sender too - simpler,
# more predictable than an asymmetric "everyone except me" rule, and clients
# can always ignore/dedupe their own user_id if they update optimistically.
# This bit a manual live-server test script during development (it assumed
# sender exclusion and read messages out of order) - locking it in explicitly.
chat_echoed_to_sender = ws2.receive_json()
assert chat_echoed_to_sender == {"type": "chat", "user_id": 2, "text": "hey everyone"}
def test_websocket_reaction_increments_fire_count(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "reaction", "emoji": "🔥"})
reaction = ws.receive_json()
assert reaction["type"] == "reaction"
assert reaction["emoji"] == "🔥"
assert reaction["fire_count"] == 1
def test_websocket_dj_handoff_flow(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws:
listener_ws.receive_json() # snapshot
dj_ws.receive_json() # user_joined for user 2
listener_ws.send_json({"type": "request_aux"})
queue_update_on_listener = listener_ws.receive_json()
queue_update_on_dj = dj_ws.receive_json()
assert queue_update_on_listener == {"type": "queue_updated", "dj_queue": [2]}
assert queue_update_on_dj == {"type": "queue_updated", "dj_queue": [2]}
dj_ws.send_json({"type": "pass_aux"})
dj_changed_on_dj = dj_ws.receive_json()
dj_changed_on_listener = listener_ws.receive_json()
assert dj_changed_on_dj == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
assert dj_changed_on_listener == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.dj_id == 2
finally:
db.close()
def test_websocket_only_dj_can_pass_aux(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "pass_aux"})
error = ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can pass the aux."}
def test_websocket_only_dj_can_set_now_playing(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 42})
update = dj_ws.receive_json()
assert update == {"type": "now_playing_changed", "song_id": 42, "dj_id": 1}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.current_song_id == 42
finally:
db.close()
def test_websocket_user_left_broadcast_on_disconnect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
ws1.receive_json() # user_joined
left = ws1.receive_json()
assert left == {"type": "user_left", "user_id": 2}
...@@ -68,3 +68,58 @@ def test_get_active_rooms(client, auth_as): ...@@ -68,3 +68,58 @@ def test_get_active_rooms(client, auth_as):
response = client.get("/social/rooms", headers=headers) response = client.get("/social/rooms", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert isinstance(response.json(), list) assert isinstance(response.json(), list)
def test_remix_tree_not_found(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/posts/999999/tree", headers=headers)
assert response.status_code == 404
def test_remix_tree_with_children(client, auth_as):
headers, _ = auth_as()
root_res = client.post("/social/posts", json={"song_id": 1, "caption": "root post"}, headers=headers)
root_id = root_res.json()["id"]
child_res = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "a remix of the root"
}, headers=headers)
assert child_res.status_code == 201
response = client.get(f"/social/posts/{root_id}/tree", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["post"]["id"] == root_id
assert len(body["children"]) == 1
assert body["children"][0]["post"]["id"] == child_res.json()["id"]
def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as):
headers, _ = auth_as()
root_id = client.post("/social/posts", json={"song_id": 1, "caption": "gen 0"}, headers=headers).json()["id"]
child_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "gen 1",
}, headers=headers).json()["id"]
grandchild_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": child_id, "caption": "gen 2",
}, headers=headers).json()["id"]
response = client.get(f"/social/posts/{root_id}/tree", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["post"]["id"] == root_id
assert len(body["children"]) == 1
child_node = body["children"][0]
assert child_node["post"]["id"] == child_id
assert len(child_node["children"]) == 1
grandchild_node = child_node["children"][0]
assert grandchild_node["post"]["id"] == grandchild_id
assert grandchild_node["children"] == []
def test_remix_tree_leaf_node_has_no_children(client, auth_as):
headers, _ = auth_as()
leaf_id = client.post("/social/posts", json={"song_id": 1, "caption": "no remixes yet"}, headers=headers).json()["id"]
response = client.get(f"/social/posts/{leaf_id}/tree", headers=headers)
assert response.json()["children"] == []
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