Commit 6c4cb3ed authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Replace Channels with Radio: band+frequency stations, stateless now-playing

Channels shipped a backend nobody built UI for (vibe sets/stories/showcase
had zero frontend); removed outright rather than left half-built. Radio
replaces it: creator-run stations tuned via a band (SM/SF/SR) + 50-200.0
frequency dial, worldwide or local-radius broadcast, a queue that loops
forever. No scheduler or background job anywhere in this codebase, so
"now playing" is fully stateless - elapsed-time-since-creation modulo the
queue's total duration maps deterministically to a (song, offset) pair,
computed fresh on every request. LibrarySong gained duration_seconds
(probed via pydub at tag/upload/claim/remix time, lazily backfilled for
older rows) to make that math possible. Also relaxes /soundmarks/geocode
and /reverse-geocode from business-admin-only to any authenticated user,
needed by the new location picker and never actually business-specific.
parent 7baf7ba5
Pipeline #1223 failed with stage
in 117 minutes and 22 seconds
"""replace channels with radio
Revision ID: 0c9ff986c2e6
Revises: c3a7e5f91b04
Create Date: 2026-10-12 13:30:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '0c9ff986c2e6'
down_revision: Union[str, Sequence[str], None] = 'c3a7e5f91b04'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# Channels shipped a backend (create/follow, vibe sets, 24h audio stories, showcase) that
# the frontend never built UI for - confirmed zero usage before dropping. Children first.
op.drop_table('channel_showcases')
op.drop_table('audio_stories')
op.drop_table('vibe_set_tracks')
op.drop_table('vibe_sets')
op.drop_table('channel_follows')
op.drop_table('channels')
op.add_column('library_songs', sa.Column('duration_seconds', sa.Float(), nullable=True))
op.create_table('radios',
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('artwork_url', sa.String(), nullable=True),
sa.Column('band', sa.String(), nullable=True),
sa.Column('frequency', sa.Float(), nullable=True),
sa.Column('scope', sa.String(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('radius_meters', sa.Float(), nullable=True),
sa.Column('reference_started_at', sa.DateTime(), nullable=True),
sa.Column('schedule_start_minute', sa.Integer(), nullable=True),
sa.Column('schedule_end_minute', sa.Integer(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_radios_id'), 'radios', ['id'], unique=False)
op.create_index(op.f('ix_radios_name'), 'radios', ['name'], unique=False)
op.create_index(op.f('ix_radios_owner_id'), 'radios', ['owner_id'], unique=False)
op.create_table('radio_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('radio_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('position', sa.Integer(), nullable=True),
sa.Column('added_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['radio_id'], ['radios.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_radio_tracks_id'), 'radio_tracks', ['id'], unique=False)
op.create_index(op.f('ix_radio_tracks_radio_id'), 'radio_tracks', ['radio_id'], unique=False)
def downgrade() -> None:
"""Downgrade schema."""
op.drop_index(op.f('ix_radio_tracks_radio_id'), table_name='radio_tracks')
op.drop_index(op.f('ix_radio_tracks_id'), table_name='radio_tracks')
op.drop_table('radio_tracks')
op.drop_index(op.f('ix_radios_owner_id'), table_name='radios')
op.drop_index(op.f('ix_radios_name'), table_name='radios')
op.drop_index(op.f('ix_radios_id'), table_name='radios')
op.drop_table('radios')
op.drop_column('library_songs', 'duration_seconds')
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('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_id'), 'channel_follows', ['id'], unique=False)
op.create_index(op.f('ix_channel_follows_channel_id'), 'channel_follows', ['channel_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_id'), 'vibe_sets', ['id'], unique=False)
op.create_index(op.f('ix_vibe_sets_channel_id'), 'vibe_sets', ['channel_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)
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_id'), 'audio_stories', ['id'], unique=False)
op.create_index(op.f('ix_audio_stories_channel_id'), 'audio_stories', ['channel_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_id'), 'channel_showcases', ['id'], unique=False)
op.create_index(op.f('ix_channel_showcases_channel_id'), 'channel_showcases', ['channel_id'], unique=False)
op.create_index(op.f('ix_channel_showcases_post_id'), 'channel_showcases', ['post_id'], unique=False)
...@@ -10,10 +10,10 @@ from fastapi.openapi.utils import get_openapi ...@@ -10,10 +10,10 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from sqlalchemy import text from sqlalchemy import text
from src.api.routers import auth, channels, discovery, dm, home, library, music, remix, social, soundmarks, telegram_scan from src.api.routers import auth, discovery, dm, home, library, music, radio, remix, social, soundmarks, telegram_scan
from src.core.config import CORS_ORIGINS, DOCS_PASSWORD, DOCS_USERNAME from src.core.config import CORS_ORIGINS, 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, IMAGES_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") LOGIN_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "login.html")
...@@ -83,6 +83,7 @@ app.add_middleware( ...@@ -83,6 +83,7 @@ app.add_middleware(
) )
app.mount("/downloads", StaticFiles(directory=DOWNLOADS_DIR), name="downloads") app.mount("/downloads", StaticFiles(directory=DOWNLOADS_DIR), name="downloads")
app.mount("/images", StaticFiles(directory=IMAGES_DIR), name="images")
app.include_router(auth.router) app.include_router(auth.router)
app.include_router(discovery.router) app.include_router(discovery.router)
...@@ -92,7 +93,7 @@ app.include_router(music.router) ...@@ -92,7 +93,7 @@ app.include_router(music.router)
app.include_router(social.router) app.include_router(social.router)
app.include_router(dm.router) app.include_router(dm.router)
app.include_router(remix.router) app.include_router(remix.router)
app.include_router(channels.router) app.include_router(radio.router)
app.include_router(soundmarks.router) app.include_router(soundmarks.router)
app.include_router(telegram_scan.router) app.include_router(telegram_scan.router)
......
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,
User,
VibeSet,
VibeSetTrack,
get_db,
)
from src.core.security import get_current_user
router = APIRouter(prefix="/channels", tags=["Channels"])
STORY_LIFETIME = timedelta(hours=24)
class ChannelCreate(BaseModel):
name: str
description: Optional[str] = None
avatar_url: Optional[str] = None
class VibeSetCreate(BaseModel):
title: str
description: Optional[str] = None
song_ids: List[int] = []
class StoryCreate(BaseModel):
song_id: int
caption: Optional[str] = None
class ShowcaseCreate(BaseModel):
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), current_user: User = Depends(get_current_user)):
channel = Channel(owner_id=current_user.id, **data.dict())
db.add(channel)
db.commit()
db.refresh(channel)
return channel
@router.get("")
def list_channels(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
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), current_user: User = Depends(get_current_user)):
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), current_user: User = Depends(get_current_user)):
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, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
existing = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == current_user.id
).first()
if existing:
return existing
follow = ChannelFollow(channel_id=channel_id, user_id=current_user.id)
db.add(follow)
db.commit()
db.refresh(follow)
return follow
@router.post("/{channel_id}/unfollow")
def unfollow_channel(channel_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
follow = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == current_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), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, current_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), current_user: User = Depends(get_current_user)):
_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), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, current_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), current_user: User = Depends(get_current_user)):
_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), current_user: User = Depends(get_current_user)
):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, current_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), current_user: User = Depends(get_current_user)):
_get_channel_or_404(channel_id, db)
return (
db.query(ChannelShowcase)
.filter(ChannelShowcase.channel_id == channel_id)
.order_by(ChannelShowcase.added_at.desc())
.all()
)
...@@ -13,7 +13,7 @@ from src.core.config import logger ...@@ -13,7 +13,7 @@ from src.core.config import logger
from src.core.database import IdentifiedTrack, LibrarySong, User, get_db from src.core.database import IdentifiedTrack, LibrarySong, User, get_db
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services import storage from src.services import storage
from src.services.audio_processing import AudioDecodeError, tag_and_convert_audio from src.services.audio_processing import AudioDecodeError, probe_duration_seconds, tag_and_convert_audio
from src.services.music_identification import ( from src.services.music_identification import (
compute_fingerprint, compute_fingerprint,
fetch_lyrics, fetch_lyrics,
...@@ -179,6 +179,7 @@ async def _identify_tag_and_store( ...@@ -179,6 +179,7 @@ async def _identify_tag_and_store(
track_number=candidate.get('track_number'), track_number=candidate.get('track_number'),
file_path=final_path, file_path=final_path,
fingerprint=fingerprint, fingerprint=fingerprint,
duration_seconds=probe_duration_seconds(final_path),
) )
db.add(library_song) db.add(library_song)
db.commit() db.commit()
......
import os
from datetime import datetime, timezone
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Radio, RadioTrack, User
from src.core.security import get_current_user, get_current_user_for_stream
from src.services.audio_processing import probe_duration_seconds
from src.services.geo import haversine_meters
from src.services.media_stream import stream_audio_file
from src.services import storage
router = APIRouter(prefix="/radio", tags=["radio"])
BANDS = {"SM", "SF", "SR"}
FREQUENCY_MIN = 50.0
FREQUENCY_MAX = 200.0
# How close a listener's dial has to land on a station's frequency to count as "tuned in" -
# the frontend applies this same tolerance client-side against the cached /browse list before
# ever fetching now-playing, so dragging a slider doesn't hammer the backend.
TUNING_LOCK_EPSILON = 0.3
# At least 2x TUNING_LOCK_EPSILON, so no two stations' lock-in zones can ever overlap - without
# this gap, a listener's dial could land in a position where it's ambiguous which of two
# stations they've "tuned" to.
FREQUENCY_COLLISION_EPSILON = 0.6
MAX_ARTWORK_BYTES = 5 * 1024 * 1024
ALLOWED_ARTWORK_TYPES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
# A duration that genuinely can't be probed (corrupted file, exotic codec) shouldn't wedge the
# now-playing math - fall back to a plausible average rather than dividing by zero or crashing.
FALLBACK_DURATION_SECONDS = 180.0
# --- Schemas ---
class RadioCreate(BaseModel):
name: str
description: Optional[str] = None
band: str
frequency: float
scope: str # "worldwide" | "local"
latitude: Optional[float] = None
longitude: Optional[float] = None
radius_meters: Optional[float] = None
schedule_start_minute: Optional[int] = None
schedule_end_minute: Optional[int] = None
class RadioUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
band: Optional[str] = None
frequency: Optional[float] = None
scope: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None
radius_meters: Optional[float] = None
schedule_start_minute: Optional[int] = None
schedule_end_minute: Optional[int] = None
class QueueAdd(BaseModel):
song_id: int
class QueueReorder(BaseModel):
track_ids: List[int]
# --- Helpers ---
def _serialize_radio(radio: Radio) -> dict:
return {
"id": radio.id,
"owner_id": radio.owner_id,
"name": radio.name,
"description": radio.description,
"artwork_url": radio.artwork_url,
"band": radio.band,
"frequency": radio.frequency,
"scope": radio.scope,
"latitude": radio.latitude,
"longitude": radio.longitude,
"radius_meters": radio.radius_meters,
"schedule_start_minute": radio.schedule_start_minute,
"schedule_end_minute": radio.schedule_end_minute,
"is_active": radio.is_active,
"created_at": radio.created_at,
}
def _serialize_song(song: LibrarySong) -> dict:
return {
"id": song.id,
"user_id": song.user_id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"coverart": song.coverart,
"duration_seconds": song.duration_seconds,
}
def _check_owns_radio(radio: Radio, current_user: User):
if radio.owner_id != current_user.id:
raise HTTPException(status_code=403, detail="Only this station's creator can do that")
def _get_radio_or_404(db: Session, radio_id: int) -> Radio:
radio = db.query(Radio).filter(Radio.id == radio_id).first()
if not radio:
raise HTTPException(status_code=404, detail="Radio station not found")
return radio
def _validate_band(band: str):
if band not in BANDS:
raise HTTPException(status_code=422, detail=f"Band must be one of {sorted(BANDS)}")
def _validate_frequency(frequency: float) -> float:
if not (FREQUENCY_MIN <= frequency <= FREQUENCY_MAX):
raise HTTPException(status_code=422, detail=f"Frequency must be between {FREQUENCY_MIN} and {FREQUENCY_MAX}")
return round(frequency, 1)
def _check_frequency_collision(db: Session, band: str, frequency: float, exclude_radio_id: Optional[int] = None):
query = db.query(Radio).filter(Radio.is_active == True, Radio.band == band)
if exclude_radio_id is not None:
query = query.filter(Radio.id != exclude_radio_id)
for other in query.all():
# round() the difference before comparing - two 1-decimal-rounded floats can still
# subtract to something like 0.5999999999999943 due to binary float representation,
# which would wrongly trip a "< 0.6" collision check for stations exactly 0.6 apart.
if round(abs(other.frequency - frequency), 3) < FREQUENCY_COLLISION_EPSILON:
raise HTTPException(
status_code=409,
detail=f"Frequency {frequency} on band {band} is too close to an existing station's frequency",
)
def _validate_schedule(start: Optional[int], end: Optional[int]):
if (start is None) != (end is None):
raise HTTPException(status_code=422, detail="schedule_start_minute and schedule_end_minute must be set together or not at all")
for minute in (start, end):
if minute is not None and not (0 <= minute < 1440):
raise HTTPException(status_code=422, detail="Schedule minutes must be between 0 and 1439")
def _validate_scope_fields(scope: str, latitude: Optional[float], longitude: Optional[float], radius_meters: Optional[float]) -> dict:
if scope not in ("worldwide", "local"):
raise HTTPException(status_code=422, detail="scope must be 'worldwide' or 'local'")
if scope == "local":
if latitude is None or longitude is None or radius_meters is None:
raise HTTPException(status_code=422, detail="Local stations require latitude, longitude, and radius_meters")
return {"latitude": latitude, "longitude": longitude, "radius_meters": radius_meters}
return {"latitude": None, "longitude": None, "radius_meters": None}
def _is_on_air(radio: Radio, now: Optional[datetime] = None) -> bool:
if radio.schedule_start_minute is None or radio.schedule_end_minute is None:
return True
now = now or datetime.now(timezone.utc)
current_minute = now.hour * 60 + now.minute
start, end = radio.schedule_start_minute, radio.schedule_end_minute
if start <= end:
return start <= current_minute < end
# Window wraps past midnight (e.g. 22:00-02:00).
return current_minute >= start or current_minute < end
def _ensure_duration(db: Session, song: LibrarySong) -> float:
"""Lazily backfills LibrarySong.duration_seconds for rows that predate the column, the
closest honest analog to a server_default backfill for a value with no sensible constant
default. Falls back to FALLBACK_DURATION_SECONDS (without persisting the fallback, so a
transient probe failure isn't cached forever) when the file can't be probed at all."""
if song.duration_seconds is not None:
return song.duration_seconds
probed = probe_duration_seconds(song.file_path) if song.file_path else None
if probed is not None:
song.duration_seconds = probed
db.commit()
return probed
return FALLBACK_DURATION_SECONDS
def compute_now_playing(db: Session, radio: Radio) -> dict:
"""Stateless now-playing computation - no stored "current song" row, no background job.
Given the queue's ordered tracks and the station's frozen reference_started_at,
elapsed_seconds % total_queue_duration deterministically maps to exactly one
(song, offset-within-song) pair via cumulative-sum arithmetic. Computed fresh on every
call, so playing 10 minutes after tuning in correctly gets whatever is actually on now."""
if not radio.is_active or not _is_on_air(radio):
return {"on_air": False, "song": None, "offset_seconds": None, "artwork_url": radio.artwork_url}
tracks = (
db.query(RadioTrack)
.filter(RadioTrack.radio_id == radio.id)
.order_by(RadioTrack.position.asc())
.all()
)
if not tracks:
return {"on_air": False, "song": None, "offset_seconds": None, "artwork_url": radio.artwork_url}
songs_by_id = {
s.id: s for s in db.query(LibrarySong).filter(LibrarySong.id.in_([t.song_id for t in tracks])).all()
}
durations = []
for track in tracks:
song = songs_by_id.get(track.song_id)
durations.append(_ensure_duration(db, song) if song else FALLBACK_DURATION_SECONDS)
total_duration = sum(durations)
if total_duration <= 0:
return {"on_air": False, "song": None, "offset_seconds": None, "artwork_url": radio.artwork_url}
reference = radio.reference_started_at
if reference.tzinfo is None:
reference = reference.replace(tzinfo=timezone.utc)
elapsed_seconds = max(0.0, (datetime.now(timezone.utc) - reference).total_seconds())
position_in_loop = elapsed_seconds % total_duration
cumulative = 0.0
for track, duration in zip(tracks, durations):
if position_in_loop < cumulative + duration:
song = songs_by_id.get(track.song_id)
return {
"on_air": True,
"song": _serialize_song(song) if song else None,
"offset_seconds": position_in_loop - cumulative,
"artwork_url": radio.artwork_url or (song.coverart if song else None),
}
cumulative += duration
# Floating-point edge case at the exact loop boundary - land on the last track's end.
last_track = tracks[-1]
song = songs_by_id.get(last_track.song_id)
return {
"on_air": True,
"song": _serialize_song(song) if song else None,
"offset_seconds": max(0.0, durations[-1] - 0.01),
"artwork_url": radio.artwork_url or (song.coverart if song else None),
}
# --- CRUD ---
@router.post("", status_code=201)
def create_radio(body: RadioCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_validate_band(body.band)
frequency = _validate_frequency(body.frequency)
_validate_schedule(body.schedule_start_minute, body.schedule_end_minute)
scope_fields = _validate_scope_fields(body.scope, body.latitude, body.longitude, body.radius_meters)
_check_frequency_collision(db, body.band, frequency)
radio = Radio(
owner_id=current_user.id,
name=body.name,
description=body.description,
band=body.band,
frequency=frequency,
scope=body.scope,
schedule_start_minute=body.schedule_start_minute,
schedule_end_minute=body.schedule_end_minute,
reference_started_at=datetime.now(timezone.utc),
is_active=True,
**scope_fields,
)
db.add(radio)
db.commit()
db.refresh(radio)
return {"status": "success", "radio": _serialize_radio(radio)}
@router.get("/mine")
def get_my_radios(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radios = db.query(Radio).filter(Radio.owner_id == current_user.id).all()
return [_serialize_radio(r) for r in radios]
@router.get("/browse")
def browse_radios(
band: Optional[str] = None,
lat: Optional[float] = None,
lon: Optional[float] = None,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Active, on-air, geo-visible stations - deliberately no now-playing info, so a listener
can dial through this cached list client-side (lock-in checked against TUNING_LOCK_EPSILON)
without a request per tick; now-playing is only fetched once locked onto one station."""
query = db.query(Radio).filter(Radio.is_active == True)
if band is not None:
_validate_band(band)
query = query.filter(Radio.band == band)
visible = []
for radio in query.all():
if not _is_on_air(radio):
continue
if radio.scope == "local":
if lat is None or lon is None:
continue
if haversine_meters(lat, lon, radio.latitude, radio.longitude) > radio.radius_meters:
continue
visible.append(_serialize_radio(radio))
return visible
@router.get("/{radio_id}")
def get_radio(radio_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
return {"status": "success", "radio": _serialize_radio(_get_radio_or_404(db, radio_id))}
@router.patch("/{radio_id}")
def update_radio(radio_id: int, body: RadioUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
data = body.dict(exclude_unset=True)
new_band = data.get("band", radio.band)
new_frequency = data.get("frequency", radio.frequency)
if "band" in data:
_validate_band(new_band)
if "frequency" in data:
new_frequency = _validate_frequency(new_frequency)
if "band" in data or "frequency" in data:
_check_frequency_collision(db, new_band, new_frequency, exclude_radio_id=radio.id)
start = data.get("schedule_start_minute", radio.schedule_start_minute)
end = data.get("schedule_end_minute", radio.schedule_end_minute)
if "schedule_start_minute" in data or "schedule_end_minute" in data:
_validate_schedule(start, end)
if "scope" in data or "latitude" in data or "longitude" in data or "radius_meters" in data:
scope = data.get("scope", radio.scope)
latitude = data.get("latitude", radio.latitude)
longitude = data.get("longitude", radio.longitude)
radius_meters = data.get("radius_meters", radio.radius_meters)
scope_fields = _validate_scope_fields(scope, latitude, longitude, radius_meters)
radio.scope = scope
radio.latitude = scope_fields["latitude"]
radio.longitude = scope_fields["longitude"]
radio.radius_meters = scope_fields["radius_meters"]
for field in ("name", "description"):
if field in data:
setattr(radio, field, data[field])
if "band" in data:
radio.band = new_band
if "frequency" in data:
radio.frequency = new_frequency
if "schedule_start_minute" in data:
radio.schedule_start_minute = start
if "schedule_end_minute" in data:
radio.schedule_end_minute = end
db.commit()
db.refresh(radio)
return {"status": "success", "radio": _serialize_radio(radio)}
@router.delete("/{radio_id}")
def delete_radio(radio_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
db.query(RadioTrack).filter(RadioTrack.radio_id == radio.id).delete()
db.delete(radio)
db.commit()
return {"status": "success"}
# --- Now playing / stream / artwork ---
@router.get("/{radio_id}/now-playing")
def get_now_playing(radio_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
return compute_now_playing(db, radio)
@router.get("/{radio_id}/stream")
def stream_radio(radio_id: int, request: Request, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Re-derives the current song fresh on every request via compute_now_playing - so a
listener who starts playing 10 minutes after tuning in correctly gets whatever is actually
on now, not whatever was on when they first connected."""
radio = _get_radio_or_404(db, radio_id)
now_playing = compute_now_playing(db, radio)
if not now_playing["on_air"] or not now_playing["song"]:
raise HTTPException(status_code=404, detail="This station isn't playing anything right now")
song = db.query(LibrarySong).filter(LibrarySong.id == now_playing["song"]["id"]).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return stream_audio_file(song.file_path, request)
@router.post("/{radio_id}/artwork")
async def upload_radio_artwork(
radio_id: int,
file: UploadFile = File(...),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
if file.content_type not in ALLOWED_ARTWORK_TYPES:
raise HTTPException(status_code=422, detail=f"Artwork must be one of {sorted(ALLOWED_ARTWORK_TYPES)}")
data = await file.read()
if len(data) > MAX_ARTWORK_BYTES:
raise HTTPException(status_code=422, detail=f"Artwork must be under {MAX_ARTWORK_BYTES} bytes")
extension = ALLOWED_ARTWORK_TYPES[file.content_type]
radio.artwork_url = storage.store_image(current_user.id, data, extension)
db.commit()
db.refresh(radio)
return {"status": "success", "radio": _serialize_radio(radio)}
# --- Queue ---
@router.get("/{radio_id}/queue")
def get_queue(radio_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
_get_radio_or_404(db, radio_id)
tracks = db.query(RadioTrack).filter(RadioTrack.radio_id == radio_id).order_by(RadioTrack.position.asc()).all()
songs_by_id = {s.id: s for s in db.query(LibrarySong).filter(LibrarySong.id.in_([t.song_id for t in tracks])).all()}
return [
{"track_id": t.id, "position": t.position, "song": _serialize_song(songs_by_id[t.song_id])}
for t in tracks
if t.song_id in songs_by_id
]
@router.post("/{radio_id}/queue", status_code=201)
def add_to_queue(radio_id: int, body: QueueAdd, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
position = db.query(RadioTrack).filter(RadioTrack.radio_id == radio.id).count()
track = RadioTrack(radio_id=radio.id, song_id=body.song_id, position=position)
db.add(track)
db.commit()
db.refresh(track)
return {"status": "success", "track_id": track.id, "position": track.position}
@router.delete("/{radio_id}/queue/{track_id}")
def remove_from_queue(radio_id: int, track_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
track = db.query(RadioTrack).filter(RadioTrack.id == track_id, RadioTrack.radio_id == radio.id).first()
if not track:
raise HTTPException(status_code=404, detail="Track not found in this station's queue")
db.delete(track)
db.commit()
return {"status": "success"}
@router.put("/{radio_id}/queue/reorder")
def reorder_queue(radio_id: int, body: QueueReorder, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
radio = _get_radio_or_404(db, radio_id)
_check_owns_radio(radio, current_user)
tracks = db.query(RadioTrack).filter(RadioTrack.radio_id == radio.id).all()
tracks_by_id = {t.id: t for t in tracks}
if set(body.track_ids) != set(tracks_by_id.keys()):
raise HTTPException(status_code=422, detail="track_ids must be exactly the current queue's track ids")
for position, track_id in enumerate(body.track_ids):
tracks_by_id[track_id].position = position
db.commit()
return {"status": "success"}
...@@ -315,7 +315,7 @@ def search_song_library( ...@@ -315,7 +315,7 @@ def search_song_library(
@router.get("/geocode") @router.get("/geocode")
async def geocode_address(q: str, current_user: User = Depends(get_current_business_admin)): async def geocode_address(q: str, current_user: User = Depends(get_current_user)):
"""Address-search autocomplete for the location picker, backed by OpenStreetMap's free """Address-search autocomplete for the location picker, backed by OpenStreetMap's free
Nominatim geocoder - see NOMINATIM_USER_AGENT for why this has to be a server-side proxy Nominatim geocoder - see NOMINATIM_USER_AGENT for why this has to be a server-side proxy
rather than the webapp calling Nominatim directly.""" rather than the webapp calling Nominatim directly."""
...@@ -341,7 +341,7 @@ async def geocode_address(q: str, current_user: User = Depends(get_current_busin ...@@ -341,7 +341,7 @@ async def geocode_address(q: str, current_user: User = Depends(get_current_busin
@router.get("/reverse-geocode") @router.get("/reverse-geocode")
async def reverse_geocode(lat: float, lon: float, current_user: User = Depends(get_current_business_admin)): async def reverse_geocode(lat: float, lon: float, current_user: User = Depends(get_current_user)):
"""The inverse of /geocode - given coordinates (e.g. from the browser's "locate me"), looks """The inverse of /geocode - given coordinates (e.g. from the browser's "locate me"), looks
up a human-readable address to pre-fill the location picker's search field with. Same up a human-readable address to pre-fill the location picker's search field with. Same
server-side-proxy reasoning as /geocode (NOMINATIM_USER_AGENT).""" server-side-proxy reasoning as /geocode (NOMINATIM_USER_AGENT)."""
......
...@@ -132,6 +132,11 @@ class LibrarySong(Base): ...@@ -132,6 +132,11 @@ class LibrarySong(Base):
# has this exact recording" before re-tagging and re-storing it, independent of title/ # has this exact recording" before re-tagging and re-storing it, independent of title/
# artist text matching (which is unreliable across correction passes). # artist text matching (which is unreliable across correction passes).
fingerprint = Column(String, index=True, nullable=True) fingerprint = Column(String, index=True, nullable=True)
# Nullable - no sensible constant default exists per-row. Populated going forward at
# tag/upload/claim/remix time (probe_duration_seconds, audio_processing.py); pre-existing
# rows are lazily backfilled on first read by Radio's own now-playing computation, the
# closest honest analog to a server_default backfill for a value that can't have one.
duration_seconds = Column(Float, nullable=True)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base): class Playlist(Base):
...@@ -425,59 +430,44 @@ class ChatScanJob(Base): ...@@ -425,59 +430,44 @@ class ChatScanJob(Base):
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) 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)) 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 # --- Radio: creator-run stations tuned via a band+frequency dial, broadcasting worldwide or
# collections), Audio Stories (ephemeral short clips), and showcase specific remixes # to a local area, looping a queue forever. Replaces Channels (2026-10-12) - the creator-hub
# (existing Posts) - the one pillar from the original vision doc with nothing built at all # feature above shipped a backend (Channel/ChannelFollow/VibeSet/VibeSetTrack/AudioStory/
# before this. # ChannelShowcase) that the frontend never built UI for; confirmed zero usage before removal.
class Channel(Base): class Radio(Base):
__tablename__ = "channels" __tablename__ = "radios"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
owner_id = Column(Integer, ForeignKey("users.id"), index=True) owner_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String, index=True) name = Column(String, index=True)
description = Column(String, nullable=True) description = Column(String, nullable=True)
avatar_url = Column(String, nullable=True) artwork_url = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) band = Column(String) # "SM" | "SF" | "SR"
frequency = Column(Float) # 50.0-200.0, 0.1 precision
class ChannelFollow(Base): scope = Column(String) # "worldwide" | "local"
__tablename__ = "channel_follows" latitude = Column(Float, nullable=True) # local scope only
id = Column(Integer, primary_key=True, index=True) longitude = Column(Float, nullable=True) # local scope only
channel_id = Column(Integer, ForeignKey("channels.id"), index=True) radius_meters = Column(Float, nullable=True) # local scope only
user_id = Column(Integer, ForeignKey("users.id"), index=True) # Frozen at creation - the queue's "now playing" position is computed fresh on every
followed_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) # request as elapsed_seconds % total_queue_duration, with no stored playback state or
# scheduler anywhere (see compute_now_playing() in radio.py). Never updated after insert.
class VibeSet(Base): reference_started_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
__tablename__ = "vibe_sets" # Minutes since UTC midnight. Both null = always on (24/7). schedule_end_minute can be
id = Column(Integer, primary_key=True, index=True) # less than schedule_start_minute (a window that wraps past midnight).
channel_id = Column(Integer, ForeignKey("channels.id"), index=True) schedule_start_minute = Column(Integer, nullable=True)
title = Column(String) schedule_end_minute = Column(Integer, nullable=True)
description = Column(String, nullable=True) is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class VibeSetTrack(Base): class RadioTrack(Base):
__tablename__ = "vibe_set_tracks" """One song in a radio's queue, in loop order - mirrors SoundmarkPlaylistTrack's
id = Column(Integer, primary_key=True, index=True) append-ordered shape."""
vibe_set_id = Column(Integer, ForeignKey("vibe_sets.id"), index=True) __tablename__ = "radio_tracks"
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) id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True) radio_id = Column(Integer, ForeignKey("radios.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id")) song_id = Column(Integer, ForeignKey("library_songs.id"))
caption = Column(String, nullable=True) position = Column(Integer, default=0)
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)) added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
......
...@@ -115,6 +115,17 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -115,6 +115,17 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
return final_path return final_path
def probe_duration_seconds(file_path: str) -> float | None:
"""Reads a file's audio length via pydub (ffmpeg under the hood already a dependency for
the rest of this module) without decoding the whole thing into memory. Returns None rather
than raising on an unreadable file - duration is a nice-to-have for Radio's queue-length
math, not something that should block tagging/upload/claim/remix if it fails."""
try:
return len(AudioSegment.from_file(file_path)) / 1000.0
except (CouldntDecodeError, FileNotFoundError, OSError):
return None
async def trim_audio(raw_file_path: str, seconds: int) -> str: async def trim_audio(raw_file_path: str, seconds: int) -> str:
"""Cuts raw_file_path down to its first `seconds` of audio and re-encodes as MP3, returning """Cuts raw_file_path down to its first `seconds` of audio and re-encodes as MP3, returning
the new file's path (raw_file_path itself is left untouched). Used for a quick preview the new file's path (raw_file_path itself is left untouched). Used for a quick preview
......
...@@ -543,7 +543,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li ...@@ -543,7 +543,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
"artist": " + ".join(sorted({s['artist'] for s in songs_info})) + " (Stax AI Remix)", "artist": " + ".join(sorted({s['artist'] for s in songs_info})) + " (Stax AI Remix)",
} }
from src.services.audio_processing import tag_and_convert_audio from src.services.audio_processing import probe_duration_seconds, tag_and_convert_audio
final_local_name = asyncio.run(tag_and_convert_audio(wav_path, candidate)) final_local_name = asyncio.run(tag_and_convert_audio(wav_path, candidate))
final_filename = os.path.basename(final_local_name) final_filename = os.path.basename(final_local_name)
...@@ -559,6 +559,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li ...@@ -559,6 +559,7 @@ def render_remix_sync(job_id: int, input_paths: list, prompt: str, filenames: li
artist=candidate["artist"], artist=candidate["artist"],
genre=plan.get("style") if plan.get("style") and plan.get("style") != "none" else None, genre=plan.get("style") if plan.get("style") and plan.get("style") != "none" else None,
file_path=download_path, file_path=download_path,
duration_seconds=probe_duration_seconds(download_path),
) )
db.add(library_song) db.add(library_song)
db.commit() db.commit()
......
...@@ -55,6 +55,7 @@ def give_from_shared_library(db: Session, current_user: User, title: str, artist ...@@ -55,6 +55,7 @@ def give_from_shared_library(db: Session, current_user: User, title: str, artist
synced_lyrics=source_song.synced_lyrics, synced_lyrics=source_song.synced_lyrics,
file_path=source_song.file_path, file_path=source_song.file_path,
fingerprint=source_song.fingerprint, fingerprint=source_song.fingerprint,
duration_seconds=source_song.duration_seconds,
) )
db.add(given) db.add(given)
db.commit() db.commit()
......
...@@ -8,11 +8,16 @@ import uuid ...@@ -8,11 +8,16 @@ import uuid
LOCAL_STORAGE_ROOT = os.getenv("LOCAL_STORAGE_ROOT", "./var/storage") LOCAL_STORAGE_ROOT = os.getenv("LOCAL_STORAGE_ROOT", "./var/storage")
TEMP_DIR = os.path.join(LOCAL_STORAGE_ROOT, "temp") TEMP_DIR = os.path.join(LOCAL_STORAGE_ROOT, "temp")
DOWNLOADS_DIR = os.path.join(LOCAL_STORAGE_ROOT, "downloads") DOWNLOADS_DIR = os.path.join(LOCAL_STORAGE_ROOT, "downloads")
# Separate from DOWNLOADS_DIR/audio: images (radio station artwork, so far) are meant to be
# publicly viewable by anyone browsing a station, unlike a user's actual audio files - no
# per-user subdirectory or ownership check needed on the read side.
IMAGES_DIR = os.path.join(LOCAL_STORAGE_ROOT, "images")
def _ensure_dirs(): def _ensure_dirs():
os.makedirs(TEMP_DIR, exist_ok=True) os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(DOWNLOADS_DIR, exist_ok=True) os.makedirs(DOWNLOADS_DIR, exist_ok=True)
os.makedirs(IMAGES_DIR, exist_ok=True)
_ensure_dirs() _ensure_dirs()
...@@ -40,6 +45,20 @@ def store_final(user_id: int, local_path: str) -> tuple[str, str]: ...@@ -40,6 +45,20 @@ def store_final(user_id: int, local_path: str) -> tuple[str, str]:
return dest, url_path return dest, url_path
def store_image(owner_id: int, data: bytes, extension: str) -> str:
"""Writes already-validated image bytes (size/content-type checked by the caller) to
durable storage, mirroring store_final's per-owner-subdirectory shape. Returns the url_path
the /images StaticFiles mount serves - there's no local_path to move here since the bytes
come straight from an UploadFile read, not a temp file on disk."""
owner_dir = os.path.join(IMAGES_DIR, str(owner_id))
os.makedirs(owner_dir, exist_ok=True)
dest_name = f"{uuid.uuid4()}.{extension}"
dest = os.path.join(owner_dir, dest_name)
with open(dest, "wb") as f:
f.write(data)
return f"/images/{owner_id}/{dest_name}"
def cleanup_temp(path: str): def cleanup_temp(path: str):
if path and os.path.exists(path): if path and os.path.exists(path):
os.remove(path) os.remove(path)
import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import AudioStory, LibrarySong, 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, headers, name="Test Channel"):
response = client.post("/channels", json={"name": name}, headers=headers)
assert response.status_code == 201
return response.json()["id"]
def test_channel_routes_require_auth(client):
assert client.get("/channels").status_code == 401
assert client.post("/channels", json={"name": "x"}).status_code == 401
def test_create_channel_is_owned_by_the_caller(client, auth_as):
headers, user = auth_as()
response = client.post("/channels", json={"name": "DJ Test's Channel"}, headers=headers)
assert response.status_code == 201
assert response.json()["owner_id"] == user.id
def test_create_and_list_channels(client, auth_as):
headers, _ = auth_as()
channel_id = _make_channel(client, headers, name="DJ Test's Channel")
response = client.get("/channels", headers=headers)
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, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
response = client.get(f"/channels/{channel_id}", headers=headers)
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", headers=follower_headers)
response = client.get(f"/channels/{channel_id}", headers=headers)
assert response.json()["follower_count"] == 1
def test_get_unknown_channel_404s(client, auth_as):
headers, _ = auth_as()
response = client.get("/channels/999999", headers=headers)
assert response.status_code == 404
def test_follow_is_idempotent(client, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
r1 = client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
r2 = client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
assert r1.status_code == 201
assert r2.status_code == 201
assert r1.json()["id"] == r2.json()["id"]
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 1
def test_unfollow(client, auth_as):
headers, _ = auth_as()
follower_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
client.post(f"/channels/{channel_id}/follow", headers=follower_headers)
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 1
response = client.post(f"/channels/{channel_id}/unfollow", headers=follower_headers)
assert response.status_code == 200
assert client.get(f"/channels/{channel_id}", headers=headers).json()["follower_count"] == 0
def test_create_vibe_set_with_tracks_owner_only(client, auth_as):
headers, _ = auth_as()
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Vibe Track")
forbidden = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"title": "Not mine", "song_ids": [song_id]},
headers=other_headers,
)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"title": "Sunday Chill", "song_ids": [song_id]},
headers=headers,
)
assert response.status_code == 201
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}", headers=headers)
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", headers=headers)
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, auth_as):
# /channels/vibe-sets/{id} must not be intercepted by the /{channel_id} catch-all
headers, _ = auth_as()
channel_id = _make_channel(client, headers)
response = client.post(
f"/channels/{channel_id}/vibe-sets", json={"title": "x", "song_ids": []}, headers=headers
)
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}", headers=headers)
assert detail.status_code == 200
assert detail.json()["vibe_set"]["id"] == vibe_set_id
def test_unknown_vibe_set_404s(client, auth_as):
headers, _ = auth_as()
response = client.get("/channels/vibe-sets/999999", headers=headers)
assert response.status_code == 404
def test_create_story_owner_only_and_expiry(client, auth_as):
headers, _ = auth_as()
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
song_id = _make_library_song(title="Story Clip")
forbidden = client.post(f"/channels/{channel_id}/stories", json={"song_id": song_id}, headers=other_headers)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/stories", json={"song_id": song_id, "caption": "vibes"}, headers=headers
)
assert response.status_code == 201
story_id = response.json()["id"]
active = client.get(f"/channels/{channel_id}/stories", headers=headers)
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, auth_as):
headers, _ = auth_as()
channel_id = _make_channel(client, headers)
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", headers=headers)
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()
other_headers, _ = auth_as()
channel_id = _make_channel(client, headers)
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={"post_id": post_id}, headers=other_headers)
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/showcase", json={"post_id": post_id}, headers=headers)
assert response.status_code == 201
listing = client.get(f"/channels/{channel_id}/showcase", headers=headers)
assert listing.status_code == 200
assert any(s["post_id"] == post_id for s in listing.json())
import itertools
import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import LibrarySong, Radio, RadioTrack, SessionLocal
from src.services.audio_processing import probe_duration_seconds
# All tests share one DB session (session-scoped, not reset per test - see conftest.py), and
# the create-radio collision check scans every active station regardless of which test made
# it. Each test that creates ≥1 station pulls its own base frequency from this sequence -
# spaced 2.0 apart, more than 3x FREQUENCY_COLLISION_EPSILON (0.6) - so a test's own small
# internal offsets (e.g. base, base+0.3) never spill into another test's frequency space, no
# matter how many stations across the whole suite end up sharing a band.
_freq_base_seq = itertools.count()
def _next_base_frequency() -> float:
base = 50.0 + (next(_freq_base_seq) * 2.0) % 148.0
return round(base, 1)
def _make_library_song(**overrides):
"""Mirrors test_social.py's helper - fake, non-decodable bytes by default (so
probe_duration_seconds reliably returns None and the FALLBACK_DURATION_SECONDS path is
exercised); pass duration_seconds explicitly for tests that need exact modulo-math control."""
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes")
defaults = dict(user_id=1, title="Test Song", artist="Test Artist", album="Test Album", 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_radio(owner_id: int, reference_started_at=None, **overrides):
"""Direct DB insert (bypassing the create endpoint) for tests that need precise control
over reference_started_at or is_active, which the API doesn't expose for mutation. Still
pulls a fresh base frequency by default, same cross-test-isolation reasoning as above."""
defaults = dict(name="Test Station", band="SM", frequency=_next_base_frequency(), scope="worldwide")
defaults.update(overrides)
db = SessionLocal()
try:
radio = Radio(
owner_id=owner_id,
reference_started_at=reference_started_at or datetime.now(timezone.utc),
is_active=defaults.pop("is_active", True),
**defaults,
)
db.add(radio)
db.commit()
db.refresh(radio)
return radio.id
finally:
db.close()
def _add_track(radio_id: int, song_id: int, position: int):
db = SessionLocal()
try:
track = RadioTrack(radio_id=radio_id, song_id=song_id, position=position)
db.add(track)
db.commit()
db.refresh(track)
return track.id
finally:
db.close()
def _create_radio(client, headers, **overrides) -> dict:
"""POSTs a station with a guaranteed-isolated base frequency unless the caller overrides
band/frequency explicitly (for tests specifically about validation/collision)."""
body = {"name": "Test Station", "band": "SM", "frequency": _next_base_frequency(), "scope": "worldwide"}
body.update(overrides)
response = client.post("/radio", json=body, headers=headers)
assert response.status_code == 201, response.text
return response.json()["radio"]
# ---- Create ----
def test_create_worldwide_station(client, auth_as):
headers, _ = auth_as()
freq = _next_base_frequency()
response = client.post("/radio", json={"name": "My Station", "band": "SM", "frequency": freq, "scope": "worldwide"}, headers=headers)
assert response.status_code == 201
radio = response.json()["radio"]
assert radio["band"] == "SM"
assert radio["frequency"] == freq
assert radio["scope"] == "worldwide"
assert radio["latitude"] is None
assert radio["is_active"] is True
def test_create_local_station_requires_lat_lon_radius(client, auth_as):
headers, _ = auth_as()
freq = _next_base_frequency()
response = client.post("/radio", json={"name": "Local", "band": "SF", "frequency": freq, "scope": "local"}, headers=headers)
assert response.status_code == 422
response = client.post(
"/radio",
json={"name": "Local", "band": "SF", "frequency": freq, "scope": "local", "latitude": 1.0, "longitude": 2.0, "radius_meters": 500},
headers=headers,
)
assert response.status_code == 201
radio = response.json()["radio"]
assert radio["latitude"] == 1.0
assert radio["radius_meters"] == 500
def test_create_rejects_invalid_band(client, auth_as):
headers, _ = auth_as()
response = client.post("/radio", json={"name": "X", "band": "ZZ", "frequency": _next_base_frequency(), "scope": "worldwide"}, headers=headers)
assert response.status_code == 422
def test_create_rejects_out_of_range_frequency(client, auth_as):
headers, _ = auth_as()
response = client.post("/radio", json={"name": "X", "band": "SM", "frequency": 49.9, "scope": "worldwide"}, headers=headers)
assert response.status_code == 422
response = client.post("/radio", json={"name": "X", "band": "SM", "frequency": 200.1, "scope": "worldwide"}, headers=headers)
assert response.status_code == 422
def test_create_rejects_invalid_scope(client, auth_as):
headers, _ = auth_as()
response = client.post("/radio", json={"name": "X", "band": "SM", "frequency": _next_base_frequency(), "scope": "regional"}, headers=headers)
assert response.status_code == 422
def test_frequency_rounds_to_one_decimal(client, auth_as):
headers, _ = auth_as()
base = _next_base_frequency()
response = client.post("/radio", json={"name": "X", "band": "SM", "frequency": base + 0.067, "scope": "worldwide"}, headers=headers)
assert response.status_code == 201
assert response.json()["radio"]["frequency"] == round(base + 0.1, 1)
def test_create_rejects_frequency_collision_on_same_band(client, auth_as):
headers, _ = auth_as()
base = _next_base_frequency()
client.post("/radio", json={"name": "First", "band": "SM", "frequency": base, "scope": "worldwide"}, headers=headers)
response = client.post("/radio", json={"name": "Second", "band": "SM", "frequency": base + 0.3, "scope": "worldwide"}, headers=headers)
assert response.status_code == 409
def test_create_allows_close_frequency_on_different_band(client, auth_as):
headers, _ = auth_as()
base = _next_base_frequency()
client.post("/radio", json={"name": "First", "band": "SM", "frequency": base, "scope": "worldwide"}, headers=headers)
response = client.post("/radio", json={"name": "Second", "band": "SF", "frequency": base + 0.3, "scope": "worldwide"}, headers=headers)
assert response.status_code == 201
def test_create_allows_frequency_far_enough_apart(client, auth_as):
headers, _ = auth_as()
base = _next_base_frequency()
client.post("/radio", json={"name": "First", "band": "SM", "frequency": base, "scope": "worldwide"}, headers=headers)
response = client.post("/radio", json={"name": "Second", "band": "SM", "frequency": base + 0.6, "scope": "worldwide"}, headers=headers)
assert response.status_code == 201
def test_create_rejects_mismatched_schedule_fields(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/radio",
json={"name": "X", "band": "SM", "frequency": _next_base_frequency(), "scope": "worldwide", "schedule_start_minute": 540},
headers=headers,
)
assert response.status_code == 422
def test_create_rejects_out_of_range_schedule_minute(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/radio",
json={
"name": "X", "band": "SM", "frequency": _next_base_frequency(), "scope": "worldwide",
"schedule_start_minute": 1500, "schedule_end_minute": 100,
},
headers=headers,
)
assert response.status_code == 422
def test_create_requires_auth(client):
response = client.post("/radio", json={"name": "X", "band": "SM", "frequency": _next_base_frequency(), "scope": "worldwide"})
assert response.status_code == 401
# ---- Get / mine / update / delete ----
def test_get_radio_by_id(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers, name="X")
response = client.get(f"/radio/{created['id']}", headers=headers)
assert response.status_code == 200
assert response.json()["radio"]["name"] == "X"
def test_get_radio_404(client, auth_as):
headers, _ = auth_as()
response = client.get("/radio/999999", headers=headers)
assert response.status_code == 404
def test_get_my_radios_only_returns_own(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
_create_radio(client, headers_a, name="A1")
_create_radio(client, headers_b, name="B1")
response = client.get("/radio/mine", headers=headers_a)
assert response.status_code == 200
names = [r["name"] for r in response.json()]
assert names == ["A1"]
def test_update_requires_ownership(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
response = client.patch(f"/radio/{created['id']}", json={"name": "Hijacked"}, headers=headers_b)
assert response.status_code == 403
def test_update_renames_station(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.patch(f"/radio/{created['id']}", json={"name": "Renamed"}, headers=headers)
assert response.status_code == 200
assert response.json()["radio"]["name"] == "Renamed"
def test_update_frequency_revalidates_collision(client, auth_as):
headers, _ = auth_as()
base = _next_base_frequency()
client.post("/radio", json={"name": "First", "band": "SM", "frequency": base, "scope": "worldwide"}, headers=headers)
second = client.post("/radio", json={"name": "Second", "band": "SM", "frequency": base + 1.0, "scope": "worldwide"}, headers=headers).json()["radio"]
response = client.patch(f"/radio/{second['id']}", json={"frequency": base + 0.2}, headers=headers)
assert response.status_code == 409
def test_update_frequency_excludes_self_from_collision_check(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
# Re-setting its own frequency to the same value must not collide with itself.
response = client.patch(f"/radio/{created['id']}", json={"frequency": created["frequency"]}, headers=headers)
assert response.status_code == 200
def test_update_scope_to_local_requires_fields(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.patch(f"/radio/{created['id']}", json={"scope": "local"}, headers=headers)
assert response.status_code == 422
response = client.patch(
f"/radio/{created['id']}", json={"scope": "local", "latitude": 1.0, "longitude": 2.0, "radius_meters": 300}, headers=headers
)
assert response.status_code == 200
assert response.json()["radio"]["scope"] == "local"
def test_delete_requires_ownership(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
response = client.delete(f"/radio/{created['id']}", headers=headers_b)
assert response.status_code == 403
def test_delete_removes_station_and_its_queue(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song_id = _make_library_song(user_id=user.id)
client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers)
response = client.delete(f"/radio/{created['id']}", headers=headers)
assert response.status_code == 200
assert client.get(f"/radio/{created['id']}", headers=headers).status_code == 404
db = SessionLocal()
try:
assert db.query(RadioTrack).filter(RadioTrack.radio_id == created["id"]).count() == 0
finally:
db.close()
# ---- Queue ----
def test_queue_add_requires_ownership(client, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
song_id = _make_library_song(user_id=user_a.id)
response = client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers_b)
assert response.status_code == 403
def test_queue_add_404s_on_missing_song(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.post(f"/radio/{created['id']}/queue", json={"song_id": 999999}, headers=headers)
assert response.status_code == 404
def test_queue_add_and_list_in_order(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song1 = _make_library_song(user_id=user.id, title="First")
song2 = _make_library_song(user_id=user.id, title="Second")
client.post(f"/radio/{created['id']}/queue", json={"song_id": song1}, headers=headers)
client.post(f"/radio/{created['id']}/queue", json={"song_id": song2}, headers=headers)
response = client.get(f"/radio/{created['id']}/queue", headers=headers)
assert response.status_code == 200
queue = response.json()
assert [t["song"]["title"] for t in queue] == ["First", "Second"]
def test_queue_allows_the_same_song_twice(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song_id = _make_library_song(user_id=user.id)
client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers)
client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers)
response = client.get(f"/radio/{created['id']}/queue", headers=headers)
assert len(response.json()) == 2
def test_queue_remove_requires_ownership(client, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
song_id = _make_library_song(user_id=user_a.id)
track = client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers_a).json()
response = client.delete(f"/radio/{created['id']}/queue/{track['track_id']}", headers=headers_b)
assert response.status_code == 403
def test_queue_remove_404_on_unknown_track(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.delete(f"/radio/{created['id']}/queue/999999", headers=headers)
assert response.status_code == 404
def test_queue_remove_deletes_the_track(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song_id = _make_library_song(user_id=user.id)
track = client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers).json()
client.delete(f"/radio/{created['id']}/queue/{track['track_id']}", headers=headers)
response = client.get(f"/radio/{created['id']}/queue", headers=headers)
assert response.json() == []
def test_queue_reorder(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song1 = _make_library_song(user_id=user.id, title="First")
song2 = _make_library_song(user_id=user.id, title="Second")
t1 = client.post(f"/radio/{created['id']}/queue", json={"song_id": song1}, headers=headers).json()
t2 = client.post(f"/radio/{created['id']}/queue", json={"song_id": song2}, headers=headers).json()
response = client.put(f"/radio/{created['id']}/queue/reorder", json={"track_ids": [t2["track_id"], t1["track_id"]]}, headers=headers)
assert response.status_code == 200
queue = client.get(f"/radio/{created['id']}/queue", headers=headers).json()
assert [t["song"]["title"] for t in queue] == ["Second", "First"]
def test_queue_reorder_rejects_mismatched_track_ids(client, auth_as):
headers, user = auth_as()
created = _create_radio(client, headers)
song_id = _make_library_song(user_id=user.id)
client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers)
response = client.put(f"/radio/{created['id']}/queue/reorder", json={"track_ids": [999999]}, headers=headers)
assert response.status_code == 422
def test_queue_reorder_requires_ownership(client, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
song_id = _make_library_song(user_id=user_a.id)
track = client.post(f"/radio/{created['id']}/queue", json={"song_id": song_id}, headers=headers_a).json()
response = client.put(f"/radio/{created['id']}/queue/reorder", json={"track_ids": [track["track_id"]]}, headers=headers_b)
assert response.status_code == 403
# ---- Browse ----
def test_browse_lists_active_worldwide_stations(client, auth_as):
headers, _ = auth_as()
_create_radio(client, headers, name="WW")
response = client.get("/radio/browse", headers=headers)
assert response.status_code == 200
assert "WW" in [r["name"] for r in response.json()]
def test_browse_filters_by_band(client, auth_as):
headers, _ = auth_as()
_create_radio(client, headers, name="OnSM", band="SM")
_create_radio(client, headers, name="OnSF", band="SF")
response = client.get("/radio/browse", params={"band": "SF"}, headers=headers)
names = [r["name"] for r in response.json()]
assert "OnSF" in names
assert "OnSM" not in names
def test_browse_excludes_local_station_without_coordinates(client, auth_as):
headers, _ = auth_as()
_create_radio(client, headers, name="Local", scope="local", latitude=10.0, longitude=10.0, radius_meters=1000)
response = client.get("/radio/browse", headers=headers)
assert "Local" not in [r["name"] for r in response.json()]
def test_browse_includes_local_station_within_radius(client, auth_as):
headers, _ = auth_as()
_create_radio(client, headers, name="Local", scope="local", latitude=10.0, longitude=10.0, radius_meters=5000)
response = client.get("/radio/browse", params={"lat": 10.001, "lon": 10.001}, headers=headers)
assert "Local" in [r["name"] for r in response.json()]
def test_browse_excludes_local_station_outside_radius(client, auth_as):
headers, _ = auth_as()
_create_radio(client, headers, name="Local", scope="local", latitude=10.0, longitude=10.0, radius_meters=100)
response = client.get("/radio/browse", params={"lat": 50.0, "lon": 50.0}, headers=headers)
assert "Local" not in [r["name"] for r in response.json()]
def test_browse_excludes_off_air_scheduled_station(client, auth_as):
headers, user = auth_as()
now = datetime.now(timezone.utc)
current_minute = now.hour * 60 + now.minute
# A narrow window guaranteed not to contain the current UTC minute.
off_start = (current_minute + 2) % 1440
off_end = (current_minute + 3) % 1440
_make_radio(user.id, name="Scheduled", schedule_start_minute=off_start, schedule_end_minute=off_end)
response = client.get("/radio/browse", headers=headers)
assert "Scheduled" not in [r["name"] for r in response.json()]
# ---- Now playing: the modulo-arithmetic core ----
def test_now_playing_off_air_when_queue_empty(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.status_code == 200
body = response.json()
assert body["on_air"] is False
assert body["song"] is None
def test_now_playing_off_air_when_inactive(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id, is_active=False)
song_id = _make_library_song(user_id=user.id, duration_seconds=100.0)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["on_air"] is False
def test_now_playing_single_track_at_start(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id, reference_started_at=datetime.now(timezone.utc))
song_id = _make_library_song(user_id=user.id, title="Only Song", duration_seconds=200.0)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
body = response.json()
assert body["on_air"] is True
assert body["song"]["title"] == "Only Song"
assert 0 <= body["offset_seconds"] < 5
def test_now_playing_lands_in_second_track(client, auth_as):
headers, user = auth_as()
# Started 70s ago; track 1 is 60s long, track 2 is 100s long -> 10s into track 2.
started = datetime.now(timezone.utc) - timedelta(seconds=70)
radio_id = _make_radio(user.id, reference_started_at=started)
song1 = _make_library_song(user_id=user.id, title="First", duration_seconds=60.0)
song2 = _make_library_song(user_id=user.id, title="Second", duration_seconds=100.0)
_add_track(radio_id, song1, 0)
_add_track(radio_id, song2, 1)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
body = response.json()
assert body["song"]["title"] == "Second"
assert 8 <= body["offset_seconds"] <= 12
def test_now_playing_loops_back_to_first_track(client, auth_as):
headers, user = auth_as()
# Total queue duration is 100s; started 105s ago -> wrapped around to 5s into track 1.
started = datetime.now(timezone.utc) - timedelta(seconds=105)
radio_id = _make_radio(user.id, reference_started_at=started)
song1 = _make_library_song(user_id=user.id, title="First", duration_seconds=60.0)
song2 = _make_library_song(user_id=user.id, title="Second", duration_seconds=40.0)
_add_track(radio_id, song1, 0)
_add_track(radio_id, song2, 1)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
body = response.json()
assert body["song"]["title"] == "First"
assert 3 <= body["offset_seconds"] <= 7
def test_now_playing_artwork_prefers_station_art_over_song_coverart(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id, artwork_url="/images/1/station.png")
song_id = _make_library_song(user_id=user.id, duration_seconds=100.0, coverart="/images/song-cover.png")
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["artwork_url"] == "/images/1/station.png"
def test_now_playing_artwork_falls_back_to_song_coverart(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
song_id = _make_library_song(user_id=user.id, duration_seconds=100.0, coverart="/images/song-cover.png")
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["artwork_url"] == "/images/song-cover.png"
def test_now_playing_schedule_24_7_when_both_minutes_null(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id, schedule_start_minute=None, schedule_end_minute=None)
song_id = _make_library_song(user_id=user.id, duration_seconds=100.0)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["on_air"] is True
def test_now_playing_schedule_window_wrapping_midnight(client, auth_as):
headers, user = auth_as()
now = datetime.now(timezone.utc)
current_minute = now.hour * 60 + now.minute
# Window starts exactly now and ends one minute before now (wrapping all the way through
# midnight) - start <= current is trivially true, so this is on-air right now regardless
# of the wrap, exercising the start > end branch of _is_on_air.
start = current_minute
end = (current_minute - 1) % 1440
radio_id = _make_radio(user.id, schedule_start_minute=start, schedule_end_minute=end)
song_id = _make_library_song(user_id=user.id, duration_seconds=100.0)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["on_air"] is True
def test_now_playing_backfills_missing_duration(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
# duration_seconds left unset (None) and file is non-decodable fake bytes - exercises the
# probe-fails-so-fall-back-without-persisting path.
song_id = _make_library_song(user_id=user.id)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/now-playing", headers=headers)
assert response.json()["on_air"] is True
db = SessionLocal()
try:
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
assert song.duration_seconds is None # fallback used, not persisted as a lie
finally:
db.close()
def test_probe_duration_seconds_reads_a_real_file():
from pydub import AudioSegment
fd, path = tempfile.mkstemp(suffix=".wav", dir="/tmp")
os.close(fd)
try:
AudioSegment.silent(duration=2500).export(path, format="wav")
duration = probe_duration_seconds(path)
assert duration is not None
assert 2.3 <= duration <= 2.7
finally:
os.remove(path)
def test_probe_duration_seconds_returns_none_for_garbage():
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"not actually audio")
try:
assert probe_duration_seconds(path) is None
finally:
os.remove(path)
def test_probe_duration_seconds_returns_none_for_missing_file():
assert probe_duration_seconds("/tmp/this-file-does-not-exist-radio-test.mp3") is None
def test_now_playing_requires_auth(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
response = client.get(f"/radio/{radio_id}/now-playing")
assert response.status_code == 401
def test_now_playing_404_on_unknown_radio(client, auth_as):
headers, _ = auth_as()
response = client.get("/radio/999999/now-playing", headers=headers)
assert response.status_code == 404
# ---- Stream ----
def test_stream_404_when_not_on_air(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
response = client.get(f"/radio/{radio_id}/stream", headers=headers)
assert response.status_code == 404
def test_stream_serves_the_current_song(client, auth_as):
headers, user = auth_as()
radio_id = _make_radio(user.id)
song_id = _make_library_song(user_id=user.id, duration_seconds=200.0)
_add_track(radio_id, song_id, 0)
response = client.get(f"/radio/{radio_id}/stream", headers=headers)
assert response.status_code == 200
def test_stream_accepts_token_query_param(client, auth_as):
import re
headers, user = auth_as()
radio_id = _make_radio(user.id)
song_id = _make_library_song(user_id=user.id, duration_seconds=200.0)
_add_track(radio_id, song_id, 0)
token = re.sub("^Bearer ", "", headers["Authorization"])
response = client.get(f"/radio/{radio_id}/stream", params={"token": token})
assert response.status_code == 200
# ---- Artwork ----
def test_artwork_upload_requires_ownership(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
created = _create_radio(client, headers_a)
response = client.post(
f"/radio/{created['id']}/artwork", files={"file": ("art.png", b"fake-png-bytes", "image/png")}, headers=headers_b
)
assert response.status_code == 403
def test_artwork_upload_rejects_bad_content_type(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.post(
f"/radio/{created['id']}/artwork", files={"file": ("art.txt", b"not an image", "text/plain")}, headers=headers
)
assert response.status_code == 422
def test_artwork_upload_rejects_oversized_file(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
too_big = b"0" * (5 * 1024 * 1024 + 1)
response = client.post(
f"/radio/{created['id']}/artwork", files={"file": ("art.png", too_big, "image/png")}, headers=headers
)
assert response.status_code == 422
def test_artwork_upload_succeeds_and_sets_url(client, auth_as):
headers, _ = auth_as()
created = _create_radio(client, headers)
response = client.post(
f"/radio/{created['id']}/artwork", files={"file": ("art.png", b"fake-png-bytes", "image/png")}, headers=headers
)
assert response.status_code == 200
artwork_url = response.json()["radio"]["artwork_url"]
assert artwork_url is not None
assert artwork_url.startswith("/images/")
def test_channels_router_is_gone(client):
"""Channels was fully replaced by Radio (2026-10-12) - confirms the old router no longer
responds at all, not just that it's unused."""
response = client.post("/channels", json={"name": "X"})
assert response.status_code == 404
...@@ -858,10 +858,17 @@ def test_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_as, mocke ...@@ -858,10 +858,17 @@ def test_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_as, mocke
assert _FakeAsyncClient.last_request["headers"]["User-Agent"] # non-empty assert _FakeAsyncClient.last_request["headers"]["User-Agent"] # non-empty
def test_geocode_requires_business_admin(client, auth_as): def test_geocode_works_for_any_authenticated_user(client, auth_as, mocker):
# Relaxed from business-admin-only (2026-10-12) - RadioLocationPicker's address search
# needs this too, and there's nothing business-admin-specific about a stateless geocoder
# proxy. Still requires auth (no headers at all 401s), just not that particular role.
headers, _ = auth_as() headers, _ = auth_as()
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeAsyncClient)
response = client.get("/soundmarks/geocode", params={"q": "Paris"}, headers=headers) response = client.get("/soundmarks/geocode", params={"q": "Paris"}, headers=headers)
assert response.status_code == 403 assert response.status_code == 200
response = client.get("/soundmarks/geocode", params={"q": "Paris"})
assert response.status_code == 401
def test_geocode_empty_query_skips_the_network_call(client, auth_as, mocker): def test_geocode_empty_query_skips_the_network_call(client, auth_as, mocker):
...@@ -935,10 +942,15 @@ def test_reverse_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_a ...@@ -935,10 +942,15 @@ def test_reverse_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_a
assert "User-Agent" in _FakeReverseGeocodeAsyncClient.last_request["headers"] assert "User-Agent" in _FakeReverseGeocodeAsyncClient.last_request["headers"]
def test_reverse_geocode_requires_business_admin(client, auth_as): def test_reverse_geocode_works_for_any_authenticated_user(client, auth_as, mocker):
# Relaxed from business-admin-only (2026-10-12) - same reasoning as /geocode above.
headers, _ = auth_as() headers, _ = auth_as()
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeReverseGeocodeAsyncClient)
response = client.get("/soundmarks/reverse-geocode", params={"lat": 1, "lon": 1}, headers=headers) response = client.get("/soundmarks/reverse-geocode", params={"lat": 1, "lon": 1}, headers=headers)
assert response.status_code == 403 assert response.status_code == 200
response = client.get("/soundmarks/reverse-geocode", params={"lat": 1, "lon": 1})
assert response.status_code == 401
def test_reverse_geocode_handles_nominatim_returning_no_match(client, auth_as, mocker): def test_reverse_geocode_handles_nominatim_returning_no_match(client, auth_as, mocker):
......
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