Commit 58f8389f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add now-playing to live rooms: full song metadata + cross-user streaming

Rooms could already chat, react, and request/pass the aux, but nobody
could actually hear anything - now_playing only ever broadcast a bare
song_id, there was no way to stream a song you didn't upload yourself
(the DJ's pick usually isn't the listener's own library song), and the
DJ could set a nonexistent song_id with no validation.

Adds full song metadata (title/artist/album/coverart) to both the
snapshot and now_playing_changed broadcasts, validates the song exists
before setting it, and adds GET /social/rooms/{id}/stream - mirrors
/soundmarks/{id}/stream's same "shared social content, not scoped to
the uploader" reasoning - so any room member can actually play what the
DJ picked.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 1df8a1ab
Pipeline #1069 passed with stage
in 5 minutes and 23 seconds
import os
import time import time
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from fastapi.responses import FileResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, SessionLocal, User, Post, GeoDrop, LiveRoom from src.core.database import get_db, SessionLocal, User, Post, GeoDrop, LibrarySong, LiveRoom
from src.core.security import get_current_user from src.core.security import get_current_user
from src.services.room_manager import room_manager from src.services.room_manager import room_manager
from datetime import datetime, timezone from datetime import datetime, timezone
...@@ -108,6 +110,22 @@ def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends ...@@ -108,6 +110,22 @@ def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends
return rooms return rooms
@router.get("/rooms/{room_id}/stream")
def stream_room_song(room_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Streams whatever's currently playing in a room, regardless of who uploaded the
underlying LibrarySong - shared social content by design (see the top-of-file note),
mirroring /soundmarks/{id}/stream's same not-scoped-to-caller reasoning."""
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if not room:
raise HTTPException(status_code=404, detail="Room not found")
if not room.current_song_id:
raise HTTPException(status_code=404, detail="Nothing is playing in this room right now")
song = db.query(LibrarySong).filter(LibrarySong.id == room.current_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 FileResponse(song.file_path, media_type="audio/mpeg")
# --- Pass-the-Aux: live room WebSocket --- # --- Pass-the-Aux: live room WebSocket ---
# Chat, reactions/fire-meter, presence, and DJ handoff are all in-memory ephemeral state # Chat, reactions/fire-meter, presence, and DJ handoff are all in-memory ephemeral state
# (src/services/room_manager.py) - only dj_id and current_song_id persist to the LiveRoom # (src/services/room_manager.py) - only dj_id and current_song_id persist to the LiveRoom
...@@ -122,6 +140,21 @@ def _get_room_or_none(room_id: int): ...@@ -122,6 +140,21 @@ def _get_room_or_none(room_id: int):
db.close() db.close()
def _serialize_song(song: LibrarySong) -> dict:
return {"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
def _get_song_dict_or_none(song_id) -> dict | None:
if song_id is None:
return None
db = SessionLocal()
try:
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first()
return _serialize_song(song) if song else None
finally:
db.close()
def _set_room_dj(room_id: int, dj_id: int): def _set_room_dj(room_id: int, dj_id: int):
db = SessionLocal() db = SessionLocal()
try: try:
...@@ -161,6 +194,7 @@ async def room_websocket(websocket: WebSocket, room_id: int, user_id: int): ...@@ -161,6 +194,7 @@ async def room_websocket(websocket: WebSocket, room_id: int, user_id: int):
"type": "snapshot", "type": "snapshot",
"dj_id": room_row.dj_id, "dj_id": room_row.dj_id,
"current_song_id": room_row.current_song_id, "current_song_id": room_row.current_song_id,
"current_song": _get_song_dict_or_none(room_row.current_song_id),
"presence": room_manager.presence(room_id), "presence": room_manager.presence(room_id),
"chat_history": list(state.chat_history), "chat_history": list(state.chat_history),
"fire_count": state.fire_count(), "fire_count": state.fire_count(),
...@@ -217,9 +251,15 @@ async def room_websocket(websocket: WebSocket, room_id: int, user_id: int): ...@@ -217,9 +251,15 @@ async def room_websocket(websocket: WebSocket, room_id: int, user_id: int):
await websocket.send_json({"type": "error", "detail": "Only the current DJ can change what's playing."}) await websocket.send_json({"type": "error", "detail": "Only the current DJ can change what's playing."})
continue continue
song_id = data.get("song_id") song_id = data.get("song_id")
song = _get_song_dict_or_none(song_id)
if song_id is not None and song is None:
await websocket.send_json({"type": "error", "detail": "That song no longer exists."})
continue
room_row.current_song_id = song_id room_row.current_song_id = song_id
_set_room_current_song(room_id, song_id) _set_room_current_song(room_id, song_id)
await room_manager.broadcast(room_id, {"type": "now_playing_changed", "song_id": song_id, "dj_id": user_id}) await room_manager.broadcast(
room_id, {"type": "now_playing_changed", "song_id": song_id, "song": song, "dj_id": user_id}
)
else: else:
await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"}) await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"})
......
from src.core.database import LiveRoom, SessionLocal import os
import tempfile
from src.core.database import LibrarySong, LiveRoom, SessionLocal
def _make_room(dj_id=1, name="Test Room"): def _make_room(dj_id=1, name="Test Room"):
...@@ -13,6 +16,23 @@ def _make_room(dj_id=1, name="Test Room"): ...@@ -13,6 +16,23 @@ def _make_room(dj_id=1, name="Test Room"):
db.close() db.close()
def _make_library_song(user_id=1, **overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for room stream test")
db = SessionLocal()
try:
defaults = dict(user_id=user_id, title="Test Anthem", artist="Test Artist", album="Test Album", genre="Pop", file_path=path)
defaults.update(overrides)
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id, path
finally:
db.close()
def test_websocket_closes_for_unknown_room(client): def test_websocket_closes_for_unknown_room(client):
from starlette.websockets import WebSocketDisconnect from starlette.websockets import WebSocketDisconnect
import pytest import pytest
...@@ -105,20 +125,97 @@ def test_websocket_only_dj_can_pass_aux(client): ...@@ -105,20 +125,97 @@ def test_websocket_only_dj_can_pass_aux(client):
def test_websocket_only_dj_can_set_now_playing(client): def test_websocket_only_dj_can_set_now_playing(client):
song_id, path = _make_library_song()
try:
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws: with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 42}) dj_ws.send_json({"type": "now_playing", "song_id": song_id})
update = dj_ws.receive_json() update = dj_ws.receive_json()
assert update == {"type": "now_playing_changed", "song_id": 42, "dj_id": 1} assert update == {
"type": "now_playing_changed",
"song_id": song_id,
"song": {"id": song_id, "title": "Test Anthem", "artist": "Test Artist", "album": "Test Album", "coverart": None},
"dj_id": 1,
}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.current_song_id == song_id
finally:
db.close()
finally:
os.remove(path)
def test_websocket_now_playing_rejects_a_song_that_does_not_exist(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 999999})
error = dj_ws.receive_json()
assert error == {"type": "error", "detail": "That song no longer exists."}
def test_websocket_non_dj_cannot_set_now_playing(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws:
listener_ws.receive_json() # snapshot
listener_ws.send_json({"type": "now_playing", "song_id": 1})
error = listener_ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can change what's playing."}
def test_websocket_snapshot_includes_current_song_once_playing(client):
song_id, path = _make_library_song()
try:
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": song_id})
dj_ws.receive_json() # now_playing_changed
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws:
snapshot = listener_ws.receive_json()
assert snapshot["current_song_id"] == song_id
assert snapshot["current_song"]["title"] == "Test Anthem"
finally:
os.remove(path)
def test_stream_room_song_works_regardless_of_who_uploaded_it(client, auth_as):
song_id, path = _make_library_song(user_id=999) # uploaded by someone else entirely
try:
room_id = _make_room(dj_id=1)
db = SessionLocal() db = SessionLocal()
try: try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first() room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.current_song_id == 42 room.current_song_id = song_id
db.commit()
finally: finally:
db.close() db.close()
headers, _ = auth_as()
response = client.get(f"/social/rooms/{room_id}/stream", headers=headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for room stream test"
finally:
os.remove(path)
def test_stream_room_song_404s_when_nothing_is_playing(client, auth_as):
room_id = _make_room(dj_id=1)
headers, _ = auth_as()
response = client.get(f"/social/rooms/{room_id}/stream", headers=headers)
assert response.status_code == 404
def test_stream_room_song_404s_for_unknown_room(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/rooms/999999/stream", headers=headers)
assert response.status_code == 404
def test_websocket_user_left_broadcast_on_disconnect(client): def test_websocket_user_left_broadcast_on_disconnect(client):
room_id = _make_room(dj_id=1) room_id = _make_room(dj_id=1)
......
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