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
from fastapi.staticfiles import StaticFiles
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.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")
LOGIN_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "login.html")
......@@ -83,6 +83,7 @@ app.add_middleware(
)
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(discovery.router)
......@@ -92,7 +93,7 @@ app.include_router(music.router)
app.include_router(social.router)
app.include_router(dm.router)
app.include_router(remix.router)
app.include_router(channels.router)
app.include_router(radio.router)
app.include_router(soundmarks.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
from src.core.database import IdentifiedTrack, LibrarySong, User, get_db
from src.core.security import get_current_user
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 (
compute_fingerprint,
fetch_lyrics,
......@@ -179,6 +179,7 @@ async def _identify_tag_and_store(
track_number=candidate.get('track_number'),
file_path=final_path,
fingerprint=fingerprint,
duration_seconds=probe_duration_seconds(final_path),
)
db.add(library_song)
db.commit()
......
This diff is collapsed.
......@@ -315,7 +315,7 @@ def search_song_library(
@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
Nominatim geocoder - see NOMINATIM_USER_AGENT for why this has to be a server-side proxy
rather than the webapp calling Nominatim directly."""
......@@ -341,7 +341,7 @@ async def geocode_address(q: str, current_user: User = Depends(get_current_busin
@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
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)."""
......
......@@ -132,6 +132,11 @@ class LibrarySong(Base):
# has this exact recording" before re-tagging and re-storing it, independent of title/
# artist text matching (which is unreliable across correction passes).
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))
class Playlist(Base):
......@@ -425,59 +430,44 @@ class ChatScanJob(Base):
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.
# --- Radio: creator-run stations tuned via a band+frequency dial, broadcasting worldwide or
# to a local area, looping a queue forever. Replaces Channels (2026-10-12) - the creator-hub
# feature above shipped a backend (Channel/ChannelFollow/VibeSet/VibeSetTrack/AudioStory/
# ChannelShowcase) that the frontend never built UI for; confirmed zero usage before removal.
class Channel(Base):
__tablename__ = "channels"
class Radio(Base):
__tablename__ = "radios"
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)
artwork_url = Column(String, nullable=True)
band = Column(String) # "SM" | "SF" | "SR"
frequency = Column(Float) # 50.0-200.0, 0.1 precision
scope = Column(String) # "worldwide" | "local"
latitude = Column(Float, nullable=True) # local scope only
longitude = Column(Float, nullable=True) # local scope only
radius_meters = Column(Float, nullable=True) # local scope only
# Frozen at creation - the queue's "now playing" position is computed fresh on every
# 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.
reference_started_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
# Minutes since UTC midnight. Both null = always on (24/7). schedule_end_minute can be
# less than schedule_start_minute (a window that wraps past midnight).
schedule_start_minute = Column(Integer, nullable=True)
schedule_end_minute = Column(Integer, nullable=True)
is_active = Column(Boolean, default=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))
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"
class RadioTrack(Base):
"""One song in a radio's queue, in loop order - mirrors SoundmarkPlaylistTrack's
append-ordered shape."""
__tablename__ = "radio_tracks"
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"))
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)
position = Column(Integer, default=0)
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:
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:
"""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
......
......@@ -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)",
}
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_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
artist=candidate["artist"],
genre=plan.get("style") if plan.get("style") and plan.get("style") != "none" else None,
file_path=download_path,
duration_seconds=probe_duration_seconds(download_path),
)
db.add(library_song)
db.commit()
......
......@@ -55,6 +55,7 @@ def give_from_shared_library(db: Session, current_user: User, title: str, artist
synced_lyrics=source_song.synced_lyrics,
file_path=source_song.file_path,
fingerprint=source_song.fingerprint,
duration_seconds=source_song.duration_seconds,
)
db.add(given)
db.commit()
......
......@@ -8,11 +8,16 @@ import uuid
LOCAL_STORAGE_ROOT = os.getenv("LOCAL_STORAGE_ROOT", "./var/storage")
TEMP_DIR = os.path.join(LOCAL_STORAGE_ROOT, "temp")
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():
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(DOWNLOADS_DIR, exist_ok=True)
os.makedirs(IMAGES_DIR, exist_ok=True)
_ensure_dirs()
......@@ -40,6 +45,20 @@ def store_final(user_id: int, local_path: str) -> tuple[str, str]:
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):
if path and os.path.exists(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())
This diff is collapsed.
......@@ -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
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()
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeAsyncClient)
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):
......@@ -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"]
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()
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeReverseGeocodeAsyncClient)
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):
......
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