Commit 77a227a2 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Enrich Posts/GeoDrop responses, validate songs exist, add list/stream endpoints

Posts and GeoDrop only ever returned bare song_id/user_id, had no way
to browse posts at all (only create one or fetch one specific post's
remix tree by id), and let you create a post/drop referencing a
nonexistent song_id with no validation.

- GET /social/posts: recent top-level posts (remixes nest under their
  parent via the existing tree endpoint instead), with a remix_count so
  the frontend doesn't need a second call to know if a post has replies.
- Post/GeoDrop responses now include full song metadata
  (title/artist/album/coverart) and the author's username.
- create_post/create_geo_drop now 404 if the song (or, for remixes, the
  parent post) doesn't exist instead of silently creating a dangling row.
- GET /social/geo-drop/{id}/stream: stream a dropped song regardless of
  who uploaded it, mirroring /soundmarks/{id}/stream and
  /social/rooms/{id}/stream's same reasoning - the whole point of a
  drop is someone else finding and playing it.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent f25ef119
Pipeline #1073 passed with stage
in 5 minutes and 4 seconds
...@@ -31,18 +31,87 @@ class GeoDropCreate(BaseModel): ...@@ -31,18 +31,87 @@ class GeoDropCreate(BaseModel):
class LiveRoomCreate(BaseModel): class LiveRoomCreate(BaseModel):
name: str name: str
# --- Serialization helpers ---
# Posts/drops/rooms only ever store song_id/user_id - every response enriches those into real
# song metadata (title/artist/coverart) and a username so the frontend isn't forced into an
# extra round-trip per item just to show what's actually in a feed.
def _serialize_song(song: LibrarySong) -> dict:
return {"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
def _serialize_post(post: Post, db: Session, remix_count: int = None) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == post.song_id).first()
author = db.query(User).filter(User.id == post.user_id).first()
result = {
"id": post.id,
"user_id": post.user_id,
"username": author.username if author else None,
"song": _serialize_song(song) if song else None,
"parent_post_id": post.parent_post_id,
"caption": post.caption,
"created_at": post.created_at,
}
if remix_count is not None:
result["remix_count"] = remix_count
return result
def _serialize_drop(drop: GeoDrop, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == drop.song_id).first()
author = db.query(User).filter(User.id == drop.user_id).first()
return {
"id": drop.id,
"user_id": drop.user_id,
"username": author.username if author else None,
"song": _serialize_song(song) if song else None,
"latitude": drop.latitude,
"longitude": drop.longitude,
"dropped_at": drop.dropped_at,
}
# --- Endpoints --- # --- Endpoints ---
# Posts/drops/rooms are shared social content by design, so reads aren't filtered to the # Posts/drops/rooms are shared social content by design, so reads aren't filtered to the
# caller's own rows - only writes are, by deriving the author from the auth token instead of # caller's own rows - only writes are, by deriving the author from the auth token instead of
# trusting a client-supplied user_id/dj_id. # trusting a client-supplied user_id/dj_id.
POSTS_PAGE_SIZE = 50
@router.get("/posts")
def list_posts(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Recent top-level posts (not remixes - those show up nested under their parent via
GET /posts/{id}/tree instead of cluttering the main feed)."""
posts = (
db.query(Post)
.filter(Post.parent_post_id.is_(None))
.order_by(Post.created_at.desc())
.limit(POSTS_PAGE_SIZE)
.all()
)
return [
_serialize_post(p, db, remix_count=db.query(Post).filter(Post.parent_post_id == p.id).count())
for p in posts
]
@router.post("/posts", status_code=status.HTTP_201_CREATED) @router.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == post.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
if post.parent_post_id is not None:
parent = db.query(Post).filter(Post.id == post.parent_post_id).first()
if not parent:
raise HTTPException(status_code=404, detail="Post being remixed not found")
db_post = Post(user_id=current_user.id, **post.dict()) db_post = Post(user_id=current_user.id, **post.dict())
db.add(db_post) db.add(db_post)
db.commit() db.commit()
db.refresh(db_post) db.refresh(db_post)
return db_post return _serialize_post(db_post, db)
MAX_TREE_DEPTH = 50 # guards against runaway recursion on pathological/corrupted data; MAX_TREE_DEPTH = 50 # guards against runaway recursion on pathological/corrupted data;
# normal remix trees (remixes of remixes of remixes...) come nowhere # normal remix trees (remixes of remixes of remixes...) come nowhere
...@@ -53,7 +122,7 @@ def _build_remix_tree(post_id: int, db: Session, depth: int = 0) -> dict: ...@@ -53,7 +122,7 @@ def _build_remix_tree(post_id: int, db: Session, depth: int = 0) -> dict:
post = db.query(Post).filter(Post.id == post_id).first() post = db.query(Post).filter(Post.id == post_id).first()
children = db.query(Post).filter(Post.parent_post_id == post_id).all() if depth < MAX_TREE_DEPTH else [] children = db.query(Post).filter(Post.parent_post_id == post_id).all() if depth < MAX_TREE_DEPTH else []
return { return {
"post": post, "post": _serialize_post(post, db),
"children": [_build_remix_tree(c.id, db, depth + 1) for c in children], "children": [_build_remix_tree(c.id, db, depth + 1) for c in children],
} }
...@@ -68,11 +137,14 @@ def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: Us ...@@ -68,11 +137,14 @@ def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: Us
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED) @router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == drop.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
db_drop = GeoDrop(user_id=current_user.id, **drop.dict()) db_drop = GeoDrop(user_id=current_user.id, **drop.dict())
db.add(db_drop) db.add(db_drop)
db.commit() db.commit()
db.refresh(db_drop) db.refresh(db_drop)
return db_drop return _serialize_drop(db_drop, db)
@router.get("/geo-drop/nearby") @router.get("/geo-drop/nearby")
def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
...@@ -92,10 +164,25 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session ...@@ -92,10 +164,25 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session
if drop.latitude and drop.longitude: if drop.latitude and drop.longitude:
dist = haversine(lat, lon, drop.latitude, drop.longitude) dist = haversine(lat, lon, drop.latitude, drop.longitude)
if dist <= radius_km: if dist <= radius_km:
nearby.append({"drop": drop, "distance_km": dist}) nearby.append({"drop": _serialize_drop(drop, db), "distance_km": dist})
return sorted(nearby, key=lambda x: x["distance_km"]) return sorted(nearby, key=lambda x: x["distance_km"])
@router.get("/geo-drop/{drop_id}/stream")
def stream_geo_drop(drop_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Streams a dropped song regardless of who uploaded it - same not-scoped-to-caller
reasoning as /soundmarks/{id}/stream and /social/rooms/{id}/stream, since the whole point
of a drop is a stranger stumbling on it and listening."""
drop = db.query(GeoDrop).filter(GeoDrop.id == drop_id).first()
if not drop:
raise HTTPException(status_code=404, detail="Drop not found")
song = db.query(LibrarySong).filter(LibrarySong.id == drop.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")
@router.post("/rooms", status_code=status.HTTP_201_CREATED) @router.post("/rooms", status_code=status.HTTP_201_CREATED)
def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_room = LiveRoom(dj_id=current_user.id, **room.dict()) db_room = LiveRoom(dj_id=current_user.id, **room.dict())
...@@ -140,10 +227,6 @@ def _get_room_or_none(room_id: int): ...@@ -140,10 +227,6 @@ 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: def _get_song_dict_or_none(song_id) -> dict | None:
if song_id is None: if song_id is None:
return None return None
......
import os
import tempfile
from src.core.database import 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(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 test_social_router_exists(client): def test_social_router_exists(client):
response = client.get("/openapi.json", auth=("test-docs-user", "test-docs-password")) response = client.get("/openapi.json", auth=("test-docs-user", "test-docs-password"))
assert response.status_code == 200 assert response.status_code == 200
...@@ -12,40 +35,90 @@ def test_create_post_requires_auth(client): ...@@ -12,40 +35,90 @@ def test_create_post_requires_auth(client):
def test_create_post_derives_user_from_token(client, auth_as): def test_create_post_derives_user_from_token(client, auth_as):
headers, user = auth_as() headers, user = auth_as()
song_id = _make_library_song(title="My First Remix")
response = client.post( response = client.post(
"/social/posts", "/social/posts",
json={"song_id": 1, "caption": "My first remix!"}, json={"song_id": song_id, "caption": "My first remix!"},
headers=headers, headers=headers,
) )
assert response.status_code == 201 assert response.status_code == 201
body = response.json() body = response.json()
assert body["caption"] == "My first remix!" assert body["caption"] == "My first remix!"
assert body["user_id"] == user.id assert body["user_id"] == user.id
assert body["username"] == user.username
assert body["song"]["title"] == "My First Remix"
assert body["parent_post_id"] is None
def test_post_body_cannot_impersonate_another_user(client, auth_as): def test_post_body_cannot_impersonate_another_user(client, auth_as):
"""The old API took user_id in the body, letting any caller post as anyone. Even if a """The old API took user_id in the body, letting any caller post as anyone. Even if a
client still sends one, it must be ignored in favor of the authenticated caller.""" client still sends one, it must be ignored in favor of the authenticated caller."""
headers, user = auth_as() headers, user = auth_as()
song_id = _make_library_song()
response = client.post( response = client.post(
"/social/posts", "/social/posts",
json={"song_id": 1, "caption": "impersonation attempt", "user_id": 999999}, json={"song_id": song_id, "caption": "impersonation attempt", "user_id": 999999},
headers=headers, headers=headers,
) )
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["user_id"] == user.id assert response.json()["user_id"] == user.id
def test_create_post_requires_a_real_song(client, auth_as):
headers, _ = auth_as()
response = client.post("/social/posts", json={"song_id": 999999, "caption": "x"}, headers=headers)
assert response.status_code == 404
def test_create_post_requires_a_real_parent_when_remixing(client, auth_as):
headers, _ = auth_as()
song_id = _make_library_song()
response = client.post(
"/social/posts", json={"song_id": song_id, "parent_post_id": 999999, "caption": "x"}, headers=headers
)
assert response.status_code == 404
def test_list_posts_returns_only_top_level_ones_with_remix_counts(client, auth_as):
headers, _ = auth_as()
song_id = _make_library_song()
root = client.post("/social/posts", json={"song_id": song_id, "caption": "root"}, headers=headers).json()
client.post(
"/social/posts", json={"song_id": song_id, "parent_post_id": root["id"], "caption": "a remix"}, headers=headers
)
response = client.get("/social/posts", headers=headers)
assert response.status_code == 200
body = response.json()
posts_by_id = {p["id"]: p for p in body}
assert root["id"] in posts_by_id
assert posts_by_id[root["id"]]["remix_count"] == 1
# The remix itself is a child, not a top-level feed entry.
assert all(p["parent_post_id"] is None for p in body)
def test_create_geo_drop(client, auth_as): def test_create_geo_drop(client, auth_as):
headers, user = auth_as() headers, user = auth_as()
song_id = _make_library_song(title="Dropped Track")
response = client.post( response = client.post(
"/social/geo-drop", "/social/geo-drop",
json={"song_id": 1, "latitude": 34.0522, "longitude": -118.2437}, json={"song_id": song_id, "latitude": 34.0522, "longitude": -118.2437},
headers=headers, headers=headers,
) )
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["latitude"] == 34.0522 body = response.json()
assert response.json()["user_id"] == user.id assert body["latitude"] == 34.0522
assert body["user_id"] == user.id
assert body["username"] == user.username
assert body["song"]["title"] == "Dropped Track"
def test_create_geo_drop_requires_a_real_song(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/social/geo-drop", json={"song_id": 999999, "latitude": 0, "longitude": 0}, headers=headers
)
assert response.status_code == 404
def test_get_nearby_drops(client, auth_as): def test_get_nearby_drops(client, auth_as):
...@@ -55,6 +128,38 @@ def test_get_nearby_drops(client, auth_as): ...@@ -55,6 +128,38 @@ def test_get_nearby_drops(client, auth_as):
assert isinstance(response.json(), list) assert isinstance(response.json(), list)
def test_nearby_drops_include_song_info_and_distance(client, auth_as):
headers, _ = auth_as()
song_id = _make_library_song(title="Close By")
client.post(
"/social/geo-drop", json={"song_id": song_id, "latitude": 34.0522, "longitude": -118.2437}, headers=headers
)
response = client.get("/social/geo-drop/nearby?lat=34.0522&lon=-118.2437&radius_km=1", headers=headers)
assert response.status_code == 200
body = response.json()
assert any(d["drop"]["song"]["title"] == "Close By" for d in body)
assert all("distance_km" in d for d in body)
def test_stream_geo_drop_works_regardless_of_who_uploaded_it(client, auth_as):
song_id = _make_library_song(user_id=999) # uploaded by someone else entirely
headers, _ = auth_as()
drop_id = client.post(
"/social/geo-drop", json={"song_id": song_id, "latitude": 0, "longitude": 0}, headers=headers
).json()["id"]
response = client.get(f"/social/geo-drop/{drop_id}/stream", headers=headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes"
def test_stream_geo_drop_404s_for_unknown_drop(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/geo-drop/999999/stream", headers=headers)
assert response.status_code == 404
def test_create_live_room(client, auth_as): def test_create_live_room(client, auth_as):
headers, user = auth_as() headers, user = auth_as()
response = client.post("/social/rooms", json={"name": "Late Night LoFi"}, headers=headers) response = client.post("/social/rooms", json={"name": "Late Night LoFi"}, headers=headers)
...@@ -78,11 +183,12 @@ def test_remix_tree_not_found(client, auth_as): ...@@ -78,11 +183,12 @@ def test_remix_tree_not_found(client, auth_as):
def test_remix_tree_with_children(client, auth_as): def test_remix_tree_with_children(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
root_res = client.post("/social/posts", json={"song_id": 1, "caption": "root post"}, headers=headers) song_id = _make_library_song()
root_res = client.post("/social/posts", json={"song_id": song_id, "caption": "root post"}, headers=headers)
root_id = root_res.json()["id"] root_id = root_res.json()["id"]
child_res = client.post("/social/posts", json={ child_res = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "a remix of the root" "song_id": song_id, "parent_post_id": root_id, "caption": "a remix of the root"
}, headers=headers) }, headers=headers)
assert child_res.status_code == 201 assert child_res.status_code == 201
...@@ -96,12 +202,13 @@ def test_remix_tree_with_children(client, auth_as): ...@@ -96,12 +202,13 @@ def test_remix_tree_with_children(client, auth_as):
def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as): def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
root_id = client.post("/social/posts", json={"song_id": 1, "caption": "gen 0"}, headers=headers).json()["id"] song_id = _make_library_song()
root_id = client.post("/social/posts", json={"song_id": song_id, "caption": "gen 0"}, headers=headers).json()["id"]
child_id = client.post("/social/posts", json={ child_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": root_id, "caption": "gen 1", "song_id": song_id, "parent_post_id": root_id, "caption": "gen 1",
}, headers=headers).json()["id"] }, headers=headers).json()["id"]
grandchild_id = client.post("/social/posts", json={ grandchild_id = client.post("/social/posts", json={
"song_id": 1, "parent_post_id": child_id, "caption": "gen 2", "song_id": song_id, "parent_post_id": child_id, "caption": "gen 2",
}, headers=headers).json()["id"] }, headers=headers).json()["id"]
response = client.get(f"/social/posts/{root_id}/tree", headers=headers) response = client.get(f"/social/posts/{root_id}/tree", headers=headers)
...@@ -120,6 +227,9 @@ def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as): ...@@ -120,6 +227,9 @@ def test_remix_tree_is_recursive_across_multiple_generations(client, auth_as):
def test_remix_tree_leaf_node_has_no_children(client, auth_as): def test_remix_tree_leaf_node_has_no_children(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
leaf_id = client.post("/social/posts", json={"song_id": 1, "caption": "no remixes yet"}, headers=headers).json()["id"] song_id = _make_library_song()
leaf_id = client.post(
"/social/posts", json={"song_id": song_id, "caption": "no remixes yet"}, headers=headers
).json()["id"]
response = client.get(f"/social/posts/{leaf_id}/tree", headers=headers) response = client.get(f"/social/posts/{leaf_id}/tree", headers=headers)
assert response.json()["children"] == [] assert response.json()["children"] == []
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment