Commit 8ff8c429 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Add Channels: the last social pillar with nothing built before this

Per the original vision doc, Channels are the creator hub - users host
Vibe Sets, Audio Stories, and remix showcases. This pillar had zero
model, router, or definition beyond one paragraph before this commit.

New models (src/core/database.py): Channel, ChannelFollow, VibeSet +
VibeSetTrack (a curated, ordered song collection - same shape as the
existing Playlist/PlaylistTrack pair, owned by a channel instead of a
user), AudioStory (ephemeral - expires_at defaults to 24h from
creation; expired stories are filtered out of the "active" listing
rather than deleted, the same soft-expiry pattern this codebase
already uses for DiscoveredSong's 24h history), and ChannelShowcase
(pins an existing Post - i.e. an actual remix from the tree - to a
channel).

New router (src/api/routers/channels.py): create/list channels, get
channel detail with follower count, follow/unfollow (idempotent),
create/list vibe sets + get one with its tracks, create/list stories,
showcase/list showcased posts. Vibe sets/stories/showcase are owner-
only (403 for anyone else), matching the "creator hub" framing -
followers can browse, only the owner publishes.

Found and fixed a real SQLAlchemy bug while testing create_vibe_set:
returning an ORM object after a *second* db.commit() (for the
VibeSetTrack rows, after the VibeSet itself was already committed and
refreshed) serialized as an empty {} with no error - SQLAlchemy's
expire_on_commit default re-expires already-loaded objects on every
commit, not just the one that touched them. A final db.refresh()
right before returning fixes it. Caught by an actual assertion on the
response body, not just a status-code check.

Also added a route-ordering regression test: GET /channels/vibe-sets/
{id} must be registered before the generic /{channel_id} catch-all,
or FastAPI matches "vibe-sets" against {channel_id}:int first and
422s instead of ever reaching the real route.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent fc48e64c
Pipeline #1004 passed with stage
in 46 minutes and 22 seconds
...@@ -8,7 +8,7 @@ from fastapi.responses import HTMLResponse, RedirectResponse ...@@ -8,7 +8,7 @@ from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music, remix, social from src.api.routers import auth, channels, discovery, library, music, remix, social
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True) os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
...@@ -82,6 +82,7 @@ app.include_router(library.router) ...@@ -82,6 +82,7 @@ app.include_router(library.router)
app.include_router(music.router) app.include_router(music.router)
app.include_router(social.router) app.include_router(social.router)
app.include_router(remix.router) app.include_router(remix.router)
app.include_router(channels.router)
@app.get("/", include_in_schema=False) @app.get("/", include_in_schema=False)
......
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import (
AudioStory,
Channel,
ChannelFollow,
ChannelShowcase,
LibrarySong,
Post,
VibeSet,
VibeSetTrack,
get_db,
)
router = APIRouter(prefix="/channels", tags=["Channels"])
STORY_LIFETIME = timedelta(hours=24)
class ChannelCreate(BaseModel):
owner_id: int
name: str
description: Optional[str] = None
avatar_url: Optional[str] = None
class FollowRequest(BaseModel):
user_id: int
class VibeSetCreate(BaseModel):
user_id: int # must match the channel's owner_id
title: str
description: Optional[str] = None
song_ids: List[int] = []
class StoryCreate(BaseModel):
user_id: int # must match the channel's owner_id
song_id: int
caption: Optional[str] = None
class ShowcaseCreate(BaseModel):
user_id: int # must match the channel's owner_id
post_id: int
def _get_channel_or_404(channel_id: int, db: Session) -> Channel:
channel = db.query(Channel).filter(Channel.id == channel_id).first()
if not channel:
raise HTTPException(status_code=404, detail="Channel not found")
return channel
def _require_owner(channel: Channel, user_id: int):
if channel.owner_id != user_id:
raise HTTPException(status_code=403, detail="Only the channel owner can do this")
@router.post("", status_code=status.HTTP_201_CREATED)
def create_channel(data: ChannelCreate, db: Session = Depends(get_db)):
channel = Channel(**data.dict())
db.add(channel)
db.commit()
db.refresh(channel)
return channel
@router.get("")
def list_channels(db: Session = Depends(get_db)):
return db.query(Channel).order_by(Channel.created_at.desc()).all()
# NOTE: routes with a fixed first path segment (vibe-sets/{id}) must be registered before
# the generic /{channel_id} catch-all below - FastAPI/Starlette match routes in
# registration order, and without an explicit {channel_id:int} converter a request for
# "/channels/vibe-sets/5" would otherwise match "/{channel_id}" first and 422 trying to
# parse "vibe-sets" as an int, never reaching this route at all.
@router.get("/vibe-sets/{vibe_set_id}")
def get_vibe_set(vibe_set_id: int, db: Session = Depends(get_db)):
vibe_set = db.query(VibeSet).filter(VibeSet.id == vibe_set_id).first()
if not vibe_set:
raise HTTPException(status_code=404, detail="Vibe set not found")
tracks = (
db.query(VibeSetTrack)
.filter(VibeSetTrack.vibe_set_id == vibe_set_id)
.order_by(VibeSetTrack.order)
.all()
)
return {"vibe_set": vibe_set, "tracks": tracks}
@router.get("/{channel_id}")
def get_channel(channel_id: int, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
follower_count = db.query(ChannelFollow).filter(ChannelFollow.channel_id == channel_id).count()
return {"channel": channel, "follower_count": follower_count}
@router.post("/{channel_id}/follow", status_code=status.HTTP_201_CREATED)
def follow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
existing = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if existing:
return existing
follow = ChannelFollow(channel_id=channel_id, user_id=data.user_id)
db.add(follow)
db.commit()
db.refresh(follow)
return follow
@router.post("/{channel_id}/unfollow")
def unfollow_channel(channel_id: int, data: FollowRequest, db: Session = Depends(get_db)):
follow = db.query(ChannelFollow).filter(
ChannelFollow.channel_id == channel_id, ChannelFollow.user_id == data.user_id
).first()
if follow:
db.delete(follow)
db.commit()
return {"status": "ok"}
@router.post("/{channel_id}/vibe-sets", status_code=status.HTTP_201_CREATED)
def create_vibe_set(channel_id: int, data: VibeSetCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
vibe_set = VibeSet(channel_id=channel_id, title=data.title, description=data.description)
db.add(vibe_set)
db.commit()
db.refresh(vibe_set)
for i, song_id in enumerate(data.song_ids):
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {song_id} not found")
db.add(VibeSetTrack(vibe_set_id=vibe_set.id, song_id=song_id, order=i))
db.commit()
# SQLAlchemy sessions expire_on_commit by default - the second commit above (for the
# VibeSetTrack rows) re-expires vibe_set's already-loaded attributes even though it
# wasn't touched by that commit, and returning it unrefreshed serializes as {} (no
# error, just silently empty - this is what broke the vibe-set tests). Refresh again
# right before returning.
db.refresh(vibe_set)
return vibe_set
@router.get("/{channel_id}/vibe-sets")
def list_vibe_sets(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return db.query(VibeSet).filter(VibeSet.channel_id == channel_id).order_by(VibeSet.created_at.desc()).all()
@router.post("/{channel_id}/stories", status_code=status.HTTP_201_CREATED)
def create_story(channel_id: int, data: StoryCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song:
raise HTTPException(status_code=400, detail=f"Library song {data.song_id} not found")
story = AudioStory(
channel_id=channel_id,
song_id=data.song_id,
caption=data.caption,
expires_at=datetime.now(timezone.utc) + STORY_LIFETIME,
)
db.add(story)
db.commit()
db.refresh(story)
return story
@router.get("/{channel_id}/stories")
def list_active_stories(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
now = datetime.now(timezone.utc)
return (
db.query(AudioStory)
.filter(AudioStory.channel_id == channel_id, AudioStory.expires_at >= now)
.order_by(AudioStory.created_at.desc())
.all()
)
@router.post("/{channel_id}/showcase", status_code=status.HTTP_201_CREATED)
def showcase_post(channel_id: int, data: ShowcaseCreate, db: Session = Depends(get_db)):
channel = _get_channel_or_404(channel_id, db)
_require_owner(channel, data.user_id)
post = db.query(Post).filter(Post.id == data.post_id).first()
if not post:
raise HTTPException(status_code=400, detail=f"Post {data.post_id} not found")
showcase = ChannelShowcase(channel_id=channel_id, post_id=data.post_id)
db.add(showcase)
db.commit()
db.refresh(showcase)
return showcase
@router.get("/{channel_id}/showcase")
def list_showcase(channel_id: int, db: Session = Depends(get_db)):
_get_channel_or_404(channel_id, db)
return (
db.query(ChannelShowcase)
.filter(ChannelShowcase.channel_id == channel_id)
.order_by(ChannelShowcase.added_at.desc())
.all()
)
...@@ -120,6 +120,61 @@ class RemixJob(Base): ...@@ -120,6 +120,61 @@ class RemixJob(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
# collections), Audio Stories (ephemeral short clips), and showcase specific remixes
# (existing Posts) - the one pillar from the original vision doc with nothing built at all
# before this.
class Channel(Base):
__tablename__ = "channels"
id = Column(Integer, primary_key=True, index=True)
owner_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
avatar_url = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class ChannelFollow(Base):
__tablename__ = "channel_follows"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
followed_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSet(Base):
__tablename__ = "vibe_sets"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
title = Column(String)
description = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class VibeSetTrack(Base):
__tablename__ = "vibe_set_tracks"
id = Column(Integer, primary_key=True, index=True)
vibe_set_id = Column(Integer, ForeignKey("vibe_sets.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
class AudioStory(Base):
__tablename__ = "audio_stories"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
caption = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
expires_at = Column(DateTime) # default 24h from creation, set at insert time (matches
# the existing DiscoveredSong 24h-history pattern: rows
# aren't deleted on expiry, just filtered out of "active"
# queries - see get_active_stories in channels.py)
class ChannelShowcase(Base):
__tablename__ = "channel_showcases"
id = Column(Integer, primary_key=True, index=True)
channel_id = Column(Integer, ForeignKey("channels.id"), index=True)
post_id = Column(Integer, ForeignKey("posts.id"), index=True)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
......
import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import AudioStory, Channel, LibrarySong, Post, SessionLocal
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes")
defaults = dict(title="Song", artist="Artist", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id
finally:
db.close()
def _make_channel(client, owner_id=1, name="Test Channel"):
response = client.post("/channels", json={"owner_id": owner_id, "name": name})
assert response.status_code == 201
return response.json()["id"]
def test_create_and_list_channels(client):
channel_id = _make_channel(client, owner_id=1, name="DJ Test's Channel")
response = client.get("/channels")
assert response.status_code == 200
assert any(c["id"] == channel_id for c in response.json())
def test_get_channel_detail_with_follower_count(client):
channel_id = _make_channel(client)
response = client.get(f"/channels/{channel_id}")
assert response.status_code == 200
body = response.json()
assert body["channel"]["id"] == channel_id
assert body["follower_count"] == 0
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
response = client.get(f"/channels/{channel_id}")
assert response.json()["follower_count"] == 1
def test_get_unknown_channel_404s(client):
response = client.get("/channels/999999")
assert response.status_code == 404
def test_follow_is_idempotent(client):
channel_id = _make_channel(client)
r1 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
r2 = client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert r1.status_code == 201
assert r2.status_code == 201
assert r1.json()["id"] == r2.json()["id"]
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
def test_unfollow(client):
channel_id = _make_channel(client)
client.post(f"/channels/{channel_id}/follow", json={"user_id": 2})
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 1
response = client.post(f"/channels/{channel_id}/unfollow", json={"user_id": 2})
assert response.status_code == 200
assert client.get(f"/channels/{channel_id}").json()["follower_count"] == 0
def test_create_vibe_set_with_tracks_owner_only(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Vibe Track")
forbidden = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 999, "title": "Not mine", "song_ids": [song_id]},
)
assert forbidden.status_code == 403
response = client.post(
f"/channels/{channel_id}/vibe-sets",
json={"user_id": 1, "title": "Sunday Chill", "song_ids": [song_id]},
)
assert response.status_code == 201
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
body = detail.json()
assert body["vibe_set"]["title"] == "Sunday Chill"
assert len(body["tracks"]) == 1
assert body["tracks"][0]["song_id"] == song_id
listing = client.get(f"/channels/{channel_id}/vibe-sets")
assert listing.status_code == 200
assert any(v["id"] == vibe_set_id for v in listing.json())
def test_vibe_set_route_ordering_not_swallowed_by_channel_id(client):
# /channels/vibe-sets/{id} must not be intercepted by the /{channel_id} catch-all
channel_id = _make_channel(client)
response = client.post(
f"/channels/{channel_id}/vibe-sets", json={"user_id": 1, "title": "x", "song_ids": []}
)
vibe_set_id = response.json()["id"]
detail = client.get(f"/channels/vibe-sets/{vibe_set_id}")
assert detail.status_code == 200
assert detail.json()["vibe_set"]["id"] == vibe_set_id
def test_unknown_vibe_set_404s(client):
response = client.get("/channels/vibe-sets/999999")
assert response.status_code == 404
def test_create_story_owner_only_and_expiry(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Story Clip")
forbidden = client.post(f"/channels/{channel_id}/stories", json={"user_id": 999, "song_id": song_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/stories", json={"user_id": 1, "song_id": song_id, "caption": "vibes"})
assert response.status_code == 201
story_id = response.json()["id"]
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert any(s["id"] == story_id for s in active.json())
def test_expired_stories_are_filtered_from_active_listing(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Old Clip")
db = SessionLocal()
try:
expired = AudioStory(
channel_id=channel_id, song_id=song_id, caption="old",
expires_at=datetime.now(timezone.utc) - timedelta(hours=1),
)
db.add(expired)
db.commit()
expired_id = expired.id
finally:
db.close()
active = client.get(f"/channels/{channel_id}/stories")
assert active.status_code == 200
assert not any(s["id"] == expired_id for s in active.json())
def test_showcase_owner_only(client):
channel_id = _make_channel(client, owner_id=1)
song_id = _make_library_song(title="Showcased")
post_response = client.post("/social/posts", json={"user_id": 1, "song_id": song_id, "caption": "check it"})
post_id = post_response.json()["id"]
forbidden = client.post(f"/channels/{channel_id}/showcase", json={"user_id": 999, "post_id": post_id})
assert forbidden.status_code == 403
response = client.post(f"/channels/{channel_id}/showcase", json={"user_id": 1, "post_id": post_id})
assert response.status_code == 201
listing = client.get(f"/channels/{channel_id}/showcase")
assert listing.status_code == 200
assert any(s["post_id"] == post_id for s in listing.json())
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