Commit 5bbe811c authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Replace GeoDrop with LiveLocation: live position + currently-playing song

GeoDrop was a one-off "drop a song at this exact point" pin, permanent
once created. Redesigning it as a live broadcast instead: one row per
user, continuously overwritten as their position and currently-playing
song change, so nearby people see what you're listening to right now,
not a static pin you left once.

- LiveLocation model: unique per user_id, upserted on every meaningful
  location/song change plus a periodic heartbeat while sharing is on.
- PUT /social/live-location - upsert (song_id nullable: sharing your
  position doesn't require actively playing something).
- DELETE /social/live-location - stop sharing.
- GET /social/live-location/nearby - other users' live positions within
  a radius, self-excluded, enriched with song/username, sorted by
  distance. Filters out anything not updated in the last 5 minutes
  (LIVE_LOCATION_STALE_AFTER) - there's no reliable way for a closing
  browser tab to notify the server with an authenticated request, so
  staleness expiry is the actual "they stopped sharing" mechanism, not
  a clean disconnect signal.
- GET /social/live-location/{user_id}/stream - stream whatever a nearby
  user is currently playing, same cross-user reasoning as the other
  social stream endpoints.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 104986d6
Pipeline #1077 passed with stage
in 4 minutes and 43 seconds
"""replace geo_drops with live_locations
Revision ID: 6015f865f019
Revises: e612e2750fa2
Create Date: 2026-08-15 06:25:51.294032
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '6015f865f019'
down_revision: Union[str, Sequence[str], None] = 'e612e2750fa2'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('live_locations',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_live_locations_id'), 'live_locations', ['id'], unique=False)
op.create_index(op.f('ix_live_locations_user_id'), 'live_locations', ['user_id'], unique=True)
op.drop_index(op.f('ix_geo_drops_id'), table_name='geo_drops')
op.drop_index(op.f('ix_geo_drops_user_id'), table_name='geo_drops')
op.drop_table('geo_drops')
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('geo_drops',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.Column('song_id', sa.INTEGER(), nullable=True),
sa.Column('latitude', sa.FLOAT(), nullable=True),
sa.Column('longitude', sa.FLOAT(), nullable=True),
sa.Column('dropped_at', sa.DATETIME(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_geo_drops_user_id'), 'geo_drops', ['user_id'], unique=False)
op.create_index(op.f('ix_geo_drops_id'), 'geo_drops', ['id'], unique=False)
op.drop_index(op.f('ix_live_locations_user_id'), table_name='live_locations')
op.drop_index(op.f('ix_live_locations_id'), table_name='live_locations')
op.drop_table('live_locations')
# ### end Alembic commands ###
import os import os
import time import time
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from fastapi.responses import FileResponse 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, LibrarySong, LiveRoom from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, 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, timedelta, timezone
import math import math
router = APIRouter( router = APIRouter(
...@@ -23,10 +24,10 @@ class PostCreate(BaseModel): ...@@ -23,10 +24,10 @@ class PostCreate(BaseModel):
parent_post_id: int = None parent_post_id: int = None
caption: str = "" caption: str = ""
class GeoDropCreate(BaseModel): class LiveLocationUpdate(BaseModel):
song_id: int
latitude: float latitude: float
longitude: float longitude: float
song_id: Optional[int] = None
class LiveRoomCreate(BaseModel): class LiveRoomCreate(BaseModel):
name: str name: str
...@@ -58,17 +59,16 @@ def _serialize_post(post: Post, db: Session, remix_count: int = None) -> dict: ...@@ -58,17 +59,16 @@ def _serialize_post(post: Post, db: Session, remix_count: int = None) -> dict:
return result return result
def _serialize_drop(drop: GeoDrop, db: Session) -> dict: def _serialize_live_location(loc: LiveLocation, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == drop.song_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == loc.song_id).first() if loc.song_id else None
author = db.query(User).filter(User.id == drop.user_id).first() author = db.query(User).filter(User.id == loc.user_id).first()
return { return {
"id": drop.id, "user_id": loc.user_id,
"user_id": drop.user_id,
"username": author.username if author else None, "username": author.username if author else None,
"song": _serialize_song(song) if song else None, "song": _serialize_song(song) if song else None,
"latitude": drop.latitude, "latitude": loc.latitude,
"longitude": drop.longitude, "longitude": loc.longitude,
"dropped_at": drop.dropped_at, "updated_at": loc.updated_at,
} }
...@@ -149,20 +149,58 @@ def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user: ...@@ -149,20 +149,58 @@ def stream_post_song(post_id: int, db: Session = Depends(get_db), current_user:
raise HTTPException(status_code=404, detail="Audio file not found") raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg") return FileResponse(song.file_path, media_type="audio/mpeg")
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED) LIVE_LOCATION_STALE_AFTER = timedelta(minutes=5) # heartbeats (see the frontend) land well
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): # inside this - anyone who goes quiet longer
song = db.query(LibrarySong).filter(LibrarySong.id == drop.song_id).first() # than this (closed tab, lost connection,
# actually stopped) drops out of nearby
# results on their own, since there's no way
# for a closing tab to reliably notify the
# server with an authenticated request.
@router.put("/live-location")
def share_live_location(
data: LiveLocationUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""Upserts the caller's live position and what they're currently playing - one row per
user, overwritten in place. Called on every meaningful location/song change and as a
periodic heartbeat while sharing is on (see LIVE_LOCATION_STALE_AFTER)."""
if data.song_id is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song: if not song:
raise HTTPException(status_code=404, detail="Song not found") raise HTTPException(status_code=404, detail="Song not found")
db_drop = GeoDrop(user_id=current_user.id, **drop.dict())
db.add(db_drop) loc = db.query(LiveLocation).filter(LiveLocation.user_id == current_user.id).first()
if not loc:
loc = LiveLocation(user_id=current_user.id)
db.add(loc)
loc.latitude = data.latitude
loc.longitude = data.longitude
loc.song_id = data.song_id
db.commit()
db.refresh(loc)
return _serialize_live_location(loc, db)
@router.delete("/live-location")
def stop_sharing_live_location(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
loc = db.query(LiveLocation).filter(LiveLocation.user_id == current_user.id).first()
if loc:
db.delete(loc)
db.commit() db.commit()
db.refresh(db_drop) return {"status": "ok"}
return _serialize_drop(db_drop, db)
@router.get("/geo-drop/nearby") @router.get("/live-location/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_listeners(
all_drops = db.query(GeoDrop).all() lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
cutoff = datetime.now(timezone.utc) - LIVE_LOCATION_STALE_AFTER
all_locations = (
db.query(LiveLocation)
.filter(LiveLocation.user_id != current_user.id, LiveLocation.updated_at >= cutoff)
.all()
)
nearby = [] nearby = []
def haversine(lat1, lon1, lat2, lon2): def haversine(lat1, lon1, lat2, lon2):
...@@ -174,24 +212,25 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session ...@@ -174,24 +212,25 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session
distance = R * c distance = R * c
return distance return distance
for drop in all_drops: for loc in all_locations:
if drop.latitude and drop.longitude: if loc.latitude and loc.longitude:
dist = haversine(lat, lon, drop.latitude, drop.longitude) dist = haversine(lat, lon, loc.latitude, loc.longitude)
if dist <= radius_km: if dist <= radius_km:
nearby.append({"drop": _serialize_drop(drop, db), "distance_km": dist}) nearby.append({"listener": _serialize_live_location(loc, 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") @router.get("/live-location/{user_id}/stream")
def stream_geo_drop(drop_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def stream_live_location_song(user_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 """Streams whatever a nearby user is currently playing, regardless of who uploaded it -
reasoning as /soundmarks/{id}/stream and /social/rooms/{id}/stream, since the whole point same not-scoped-to-caller reasoning as the other social stream endpoints."""
of a drop is a stranger stumbling on it and listening.""" loc = db.query(LiveLocation).filter(LiveLocation.user_id == user_id).first()
drop = db.query(GeoDrop).filter(GeoDrop.id == drop_id).first() if not loc:
if not drop: raise HTTPException(status_code=404, detail="This person isn't sharing their location")
raise HTTPException(status_code=404, detail="Drop not found") if not loc.song_id:
song = db.query(LibrarySong).filter(LibrarySong.id == drop.song_id).first() raise HTTPException(status_code=404, detail="They aren't currently playing anything")
song = db.query(LibrarySong).filter(LibrarySong.id == loc.song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path): 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") raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg") return FileResponse(song.file_path, media_type="audio/mpeg")
......
...@@ -117,18 +117,28 @@ class Post(Base): ...@@ -117,18 +117,28 @@ class Post(Base):
caption = Column(String) caption = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class GeoDrop(Base): class LiveLocation(Base):
__tablename__ = "geo_drops" """A user's live position + whatever they're currently playing, continuously overwritten
as both change - one row per user (unique user_id), not a log. Distinct from Soundmarks'
GeoDrop precursor (a static, one-off "drop a song at a point" pin): this is "what's this
person listening to right now, wherever they currently are," meant to be queried live by
nearby users rather than discovered later. song_id is nullable - sharing your location
doesn't require actively playing something. Rows go stale (excluded from nearby queries,
see get_nearby_listeners) once updated_at is old enough - there's no reliable way for a
browser tab closing to notify the server synchronously with an authenticated request, so
staleness expiry is the real mechanism for "they stopped sharing," not a clean disconnect."""
__tablename__ = "live_locations"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True) user_id = Column(Integer, ForeignKey("users.id"), unique=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
latitude = Column(Float) latitude = Column(Float)
longitude = Column(Float) longitude = Column(Float)
dropped_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class Soundmark(Base): class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from GeoDrop (any user """A curated 'anthem' tied to a real-world place - distinct from LiveLocation (a live
dropping a song for others to stumble on). Three tiers, distinguished by `tier`: per-user broadcast of wherever they currently are, not a persistent place). Three tiers,
distinguished by `tier`:
- "major": a super-admin-curated landmark. One official song (song_id), set directly by a - "major": a super-admin-curated landmark. One official song (song_id), set directly by a
super admin (auto-applied). Anyone else's pick goes through SoundmarkSuggestion instead. super admin (auto-applied). Anyone else's pick goes through SoundmarkSuggestion instead.
......
import os import os
import tempfile import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import LibrarySong, SessionLocal from src.core.database import LibrarySong, LiveLocation, SessionLocal
def _make_library_song(**overrides): def _make_library_song(**overrides):
...@@ -25,7 +26,7 @@ def test_social_router_exists(client): ...@@ -25,7 +26,7 @@ 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
assert "/social/posts" in response.json()["paths"] assert "/social/posts" in response.json()["paths"]
assert "/social/geo-drop" in response.json()["paths"] assert "/social/live-location" in response.json()["paths"]
def test_create_post_requires_auth(client): def test_create_post_requires_auth(client):
...@@ -97,66 +98,151 @@ def test_list_posts_returns_only_top_level_ones_with_remix_counts(client, auth_a ...@@ -97,66 +98,151 @@ def test_list_posts_returns_only_top_level_ones_with_remix_counts(client, auth_a
assert all(p["parent_post_id"] is None for p in body) assert all(p["parent_post_id"] is None for p in body)
def test_create_geo_drop(client, auth_as): def test_share_live_location_creates_then_upserts_a_single_row(client, auth_as):
headers, user = auth_as() headers, user = auth_as()
song_id = _make_library_song(title="Dropped Track") song_id = _make_library_song(title="First Song")
response = client.post(
"/social/geo-drop", first = client.put(
json={"song_id": song_id, "latitude": 34.0522, "longitude": -118.2437}, "/social/live-location",
json={"latitude": 34.0522, "longitude": -118.2437, "song_id": song_id},
headers=headers, headers=headers,
) )
assert response.status_code == 201 assert first.status_code == 200
body = response.json() body = first.json()
assert body["latitude"] == 34.0522 assert body["latitude"] == 34.0522
assert body["user_id"] == user.id assert body["user_id"] == user.id
assert body["username"] == user.username assert body["username"] == user.username
assert body["song"]["title"] == "Dropped Track" assert body["song"]["title"] == "First Song"
other_song_id = _make_library_song(title="Switched Song")
second = client.put(
"/social/live-location",
json={"latitude": 34.06, "longitude": -118.25, "song_id": other_song_id},
headers=headers,
)
assert second.status_code == 200
assert second.json()["song"]["title"] == "Switched Song"
assert second.json()["latitude"] == 34.06
db = SessionLocal()
try:
rows = db.query(LiveLocation).filter(LiveLocation.user_id == user.id).all()
assert len(rows) == 1 # overwritten in place, not a growing log
finally:
db.close()
def test_create_geo_drop_requires_a_real_song(client, auth_as):
def test_share_live_location_allows_no_song(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.post( response = client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
"/social/geo-drop", json={"song_id": 999999, "latitude": 0, "longitude": 0}, headers=headers assert response.status_code == 200
assert response.json()["song"] is None
def test_share_live_location_requires_a_real_song_if_given(client, auth_as):
headers, _ = auth_as()
response = client.put(
"/social/live-location", json={"latitude": 0, "longitude": 0, "song_id": 999999}, headers=headers
) )
assert response.status_code == 404 assert response.status_code == 404
def test_get_nearby_drops(client, auth_as): def test_stop_sharing_removes_the_row(client, auth_as):
headers, user = auth_as()
client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
response = client.delete("/social/live-location", headers=headers)
assert response.status_code == 200
db = SessionLocal()
try:
assert db.query(LiveLocation).filter(LiveLocation.user_id == user.id).first() is None
finally:
db.close()
def test_stop_sharing_when_never_shared_is_a_no_op(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.get("/social/geo-drop/nearby?lat=34.05&lon=-118.24&radius_km=10", headers=headers) response = client.delete("/social/live-location", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert isinstance(response.json(), list)
def test_nearby_drops_include_song_info_and_distance(client, auth_as): def test_get_nearby_listeners_excludes_self(client, auth_as):
# The test DB persists for the whole session (see conftest.py) rather than resetting per
# test, so "nearby" queries - unlike everything else in this file, which scopes by a
# specific id - need deliberately unique, far-apart coordinates per test to avoid picking
# up other tests' rows within the query radius.
headers, _ = auth_as() headers, _ = auth_as()
song_id = _make_library_song()
client.put(
"/social/live-location", json={"latitude": 10.0, "longitude": 10.0, "song_id": song_id}, headers=headers
)
response = client.get("/social/live-location/nearby?lat=10.0&lon=10.0&radius_km=10", headers=headers)
assert response.status_code == 200
assert response.json() == []
def test_get_nearby_listeners_includes_song_info_and_distance(client, auth_as):
mine_headers, _ = auth_as()
other_headers, other = auth_as()
song_id = _make_library_song(title="Close By") song_id = _make_library_song(title="Close By")
client.post( client.put(
"/social/geo-drop", json={"song_id": song_id, "latitude": 34.0522, "longitude": -118.2437}, headers=headers "/social/live-location",
json={"latitude": 20.0, "longitude": 20.0, "song_id": song_id},
headers=other_headers,
) )
response = client.get("/social/geo-drop/nearby?lat=34.0522&lon=-118.2437&radius_km=1", headers=headers) response = client.get("/social/live-location/nearby?lat=20.0&lon=20.0&radius_km=1", headers=mine_headers)
assert response.status_code == 200 assert response.status_code == 200
body = response.json() body = response.json()
assert any(d["drop"]["song"]["title"] == "Close By" for d in body) assert len(body) == 1
assert all("distance_km" in d for d in body) assert body[0]["listener"]["song"]["title"] == "Close By"
assert body[0]["listener"]["user_id"] == other.id
assert "distance_km" in body[0]
def test_get_nearby_listeners_excludes_stale_entries(client, auth_as):
mine_headers, _ = auth_as()
other_headers, other = auth_as()
client.put("/social/live-location", json={"latitude": 30.0, "longitude": 30.0}, headers=other_headers)
def test_stream_geo_drop_works_regardless_of_who_uploaded_it(client, auth_as): db = SessionLocal()
try:
loc = db.query(LiveLocation).filter(LiveLocation.user_id == other.id).first()
loc.updated_at = datetime.now(timezone.utc) - timedelta(minutes=10)
db.commit()
finally:
db.close()
response = client.get("/social/live-location/nearby?lat=30.0&lon=30.0&radius_km=10", headers=mine_headers)
assert response.status_code == 200
assert response.json() == []
def test_stream_live_location_song_works_regardless_of_who_uploaded_it(client, auth_as):
song_id = _make_library_song(user_id=999) # uploaded by someone else entirely song_id = _make_library_song(user_id=999) # uploaded by someone else entirely
headers, _ = auth_as() headers, user = auth_as()
drop_id = client.post( client.put(
"/social/geo-drop", json={"song_id": song_id, "latitude": 0, "longitude": 0}, headers=headers "/social/live-location", json={"latitude": 0, "longitude": 0, "song_id": song_id}, headers=headers
).json()["id"] )
response = client.get(f"/social/geo-drop/{drop_id}/stream", headers=headers) response = client.get(f"/social/live-location/{user.id}/stream", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert response.content == b"fake mp3 bytes" assert response.content == b"fake mp3 bytes"
def test_stream_geo_drop_404s_for_unknown_drop(client, auth_as): def test_stream_live_location_404s_when_not_sharing(client, auth_as):
headers, _ = auth_as() headers, _ = auth_as()
response = client.get("/social/geo-drop/999999/stream", headers=headers) response = client.get("/social/live-location/999999/stream", headers=headers)
assert response.status_code == 404
def test_stream_live_location_404s_when_nothing_playing(client, auth_as):
headers, user = auth_as()
client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
response = client.get(f"/social/live-location/{user.id}/stream", headers=headers)
assert response.status_code == 404 assert response.status_code == 404
......
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