Commit 50bcb35e authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add room chat persistence, location/DM privacy controls, and direct messages

Rooms chat now persists to a room_messages table instead of an in-memory
deque that was discarded the instant a room emptied. Two new opt-in privacy
flags on UserProfile (share_location_enabled, allow_direct_messages) gate
live-location visibility and a new 1-on-1 direct-messaging feature, closing
a real gap where LiveLocation rows were visible to any authenticated user
with zero consent check. The Rooms websocket's connection-registry logic
was extracted into a shared ConnectionManager so DMs reuse the same
JWT-over-query-param transport instead of a second implementation.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent cab57b31
Pipeline #1187 passed with stage
in 4 minutes and 18 seconds
"""add room messages, dm threads/messages, and location/dm privacy flags
Revision ID: 83f2d110f07c
Revises: 4e6ef348478e
Create Date: 2026-09-13 06:42:18.829051
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '83f2d110f07c'
down_revision: Union[str, Sequence[str], None] = '4e6ef348478e'
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('dm_threads',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_a_id', sa.Integer(), nullable=False),
sa.Column('user_b_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_a_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['user_b_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_a_id', 'user_b_id', name='uq_dm_thread_pair')
)
op.create_index(op.f('ix_dm_threads_id'), 'dm_threads', ['id'], unique=False)
op.create_index(op.f('ix_dm_threads_user_a_id'), 'dm_threads', ['user_a_id'], unique=False)
op.create_index(op.f('ix_dm_threads_user_b_id'), 'dm_threads', ['user_b_id'], unique=False)
op.create_table('dm_messages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('thread_id', sa.Integer(), nullable=False),
sa.Column('sender_id', sa.Integer(), nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['thread_id'], ['dm_threads.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_dm_messages_created_at'), 'dm_messages', ['created_at'], unique=False)
op.create_index(op.f('ix_dm_messages_id'), 'dm_messages', ['id'], unique=False)
op.create_index(op.f('ix_dm_messages_sender_id'), 'dm_messages', ['sender_id'], unique=False)
op.create_index(op.f('ix_dm_messages_thread_id'), 'dm_messages', ['thread_id'], unique=False)
op.create_table('room_messages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['room_id'], ['live_rooms.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_room_messages_created_at'), 'room_messages', ['created_at'], unique=False)
op.create_index(op.f('ix_room_messages_id'), 'room_messages', ['id'], unique=False)
op.create_index(op.f('ix_room_messages_room_id'), 'room_messages', ['room_id'], unique=False)
op.create_index(op.f('ix_room_messages_user_id'), 'room_messages', ['user_id'], unique=False)
op.add_column('user_profiles', sa.Column('share_location_enabled', sa.Boolean(), server_default='0', nullable=False))
op.add_column('user_profiles', sa.Column('allow_direct_messages', sa.Boolean(), server_default='0', nullable=False))
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user_profiles', 'allow_direct_messages')
op.drop_column('user_profiles', 'share_location_enabled')
op.drop_index(op.f('ix_room_messages_user_id'), table_name='room_messages')
op.drop_index(op.f('ix_room_messages_room_id'), table_name='room_messages')
op.drop_index(op.f('ix_room_messages_id'), table_name='room_messages')
op.drop_index(op.f('ix_room_messages_created_at'), table_name='room_messages')
op.drop_table('room_messages')
op.drop_index(op.f('ix_dm_messages_thread_id'), table_name='dm_messages')
op.drop_index(op.f('ix_dm_messages_sender_id'), table_name='dm_messages')
op.drop_index(op.f('ix_dm_messages_id'), table_name='dm_messages')
op.drop_index(op.f('ix_dm_messages_created_at'), table_name='dm_messages')
op.drop_table('dm_messages')
op.drop_index(op.f('ix_dm_threads_user_b_id'), table_name='dm_threads')
op.drop_index(op.f('ix_dm_threads_user_a_id'), table_name='dm_threads')
op.drop_index(op.f('ix_dm_threads_id'), table_name='dm_threads')
op.drop_table('dm_threads')
# ### end Alembic commands ###
......@@ -10,7 +10,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, channels, discovery, library, music, remix, social, soundmarks, telegram_scan
from src.api.routers import auth, channels, discovery, dm, library, music, 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
......@@ -89,6 +89,7 @@ app.include_router(discovery.router)
app.include_router(library.router)
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(soundmarks.router)
......
......@@ -7,7 +7,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from starlette.background import BackgroundTask
from src.core.database import AuthAttempt, RefreshToken, User, get_db
from src.core.database import AuthAttempt, RefreshToken, User, UserProfile, get_db
from src.core.security import (
create_access_token,
create_refresh_token,
......@@ -87,6 +87,13 @@ class RefreshReq(BaseModel):
refresh_token: str
class PrivacyUpdateReq(BaseModel):
"""Partial update - both fields optional so a client can flip just one toggle without
having to already know the current value of the other."""
share_location_enabled: bool | None = None
allow_direct_messages: bool | None = None
class TokenResponse(BaseModel):
access_token: str
refresh_token: str
......@@ -280,16 +287,60 @@ async def auth_logout(req: RefreshReq, db: Session = Depends(get_db)):
return {"status": "success"}
def _get_or_create_profile(db: Session, user_id: int) -> UserProfile:
"""Most users have no UserProfile row at all yet - this table was otherwise unused before
the privacy toggles were added to it. Every read/write of those toggles goes through this
so a missing row is created with the correct (opted-out) defaults rather than requiring
every caller to special-case "no profile yet"."""
profile = db.query(UserProfile).filter(UserProfile.user_id == user_id).first()
if not profile:
profile = UserProfile(user_id=user_id)
db.add(profile)
db.commit()
db.refresh(profile)
return profile
@router.get("/me")
async def auth_me(current_user: User = Depends(get_current_user)):
async def auth_me(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Lets the client know who's logged in and what they're allowed to see - the webapp uses
`role` to decide whether to show the business/super admin panels."""
`role` to decide whether to show the business/super admin panels, and `privacy` to render
the Settings toggles and to know whether to prompt the user to opt in before sharing
location or expecting to be reachable for DMs."""
profile = _get_or_create_profile(db, current_user.id)
return {
"status": "success",
"user": {
"id": current_user.id,
"username": current_user.username,
"role": current_user.role,
"privacy": {
"share_location_enabled": profile.share_location_enabled,
"allow_direct_messages": profile.allow_direct_messages,
},
},
}
@router.patch("/privacy")
async def update_privacy(
req: PrivacyUpdateReq, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""Turning share_location_enabled off does NOT delete the caller's LiveLocation row (see
social.py) - leaving it in place but invisible is correct, independent of GeoDrops' own
share/stop toggle which does delete it."""
profile = _get_or_create_profile(db, current_user.id)
if req.share_location_enabled is not None:
profile.share_location_enabled = req.share_location_enabled
if req.allow_direct_messages is not None:
profile.allow_direct_messages = req.allow_direct_messages
db.commit()
db.refresh(profile)
return {
"status": "success",
"privacy": {
"share_location_enabled": profile.share_location_enabled,
"allow_direct_messages": profile.allow_direct_messages,
},
}
......
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import DMMessage, DMThread, SessionLocal, User, UserProfile, get_db
from src.core.security import get_current_user, user_id_from_ws_token
from src.services.dm_manager import dm_manager
router = APIRouter(prefix="/dm", tags=["Direct Messages"])
DM_PAGE_SIZE = 50
class CreateThreadReq(BaseModel):
recipient_id: int
def _canonical_pair(id_a: int, id_b: int) -> tuple[int, int]:
"""DMThread is canonicalized as (min, max) so a pair only ever has one row - callers must
sort before querying/inserting, never insert in caller-supplied order."""
return (id_a, id_b) if id_a < id_b else (id_b, id_a)
def _serialize_thread(thread: DMThread) -> dict:
return {
"id": thread.id,
"user_a_id": thread.user_a_id,
"user_b_id": thread.user_b_id,
"created_at": thread.created_at.isoformat() if thread.created_at else None,
}
def _serialize_message(msg: DMMessage) -> dict:
return {
"type": "chat",
"id": msg.id,
"thread_id": msg.thread_id,
"sender_id": msg.sender_id,
"text": msg.text,
"created_at": msg.created_at.isoformat() if msg.created_at else None,
}
def _require_participant(thread: DMThread, user_id: int):
if user_id not in (thread.user_a_id, thread.user_b_id):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not a participant in this conversation")
@router.post("/threads", status_code=status.HTTP_201_CREATED)
def create_thread(req: CreateThreadReq, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
if req.recipient_id == current_user.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Can't start a DM thread with yourself")
recipient = db.query(User).filter(User.id == req.recipient_id).first()
if not recipient:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
user_a_id, user_b_id = _canonical_pair(current_user.id, req.recipient_id)
existing = db.query(DMThread).filter(DMThread.user_a_id == user_a_id, DMThread.user_b_id == user_b_id).first()
if existing:
# No re-check of the privacy flag - an existing thread survives the recipient later
# opting out, matching how "who can message me" toggles behave everywhere: turning it
# off blocks new contact, not an already-consented-to conversation.
return _serialize_thread(existing)
profile = db.query(UserProfile).filter(UserProfile.user_id == req.recipient_id).first()
if not profile or not profile.allow_direct_messages:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="This person isn't accepting direct messages")
thread = DMThread(user_a_id=user_a_id, user_b_id=user_b_id)
db.add(thread)
db.commit()
db.refresh(thread)
return _serialize_thread(thread)
@router.get("/threads")
def list_threads(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Filtered to threads current_user is actually a participant in - the single most
important line in the whole feature."""
threads = (
db.query(DMThread)
.filter((DMThread.user_a_id == current_user.id) | (DMThread.user_b_id == current_user.id))
.order_by(DMThread.created_at.desc())
.all()
)
return [_serialize_thread(t) for t in threads]
@router.get("/threads/{thread_id}/messages")
def get_thread_messages(
thread_id: int,
before_id: Optional[int] = None,
limit: int = DM_PAGE_SIZE,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
thread = db.query(DMThread).filter(DMThread.id == thread_id).first()
if not thread:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Thread not found")
_require_participant(thread, current_user.id)
query = db.query(DMMessage).filter(DMMessage.thread_id == thread_id)
if before_id is not None:
query = query.filter(DMMessage.id < before_id)
messages = query.order_by(DMMessage.id.desc()).limit(limit).all()
messages.reverse()
return [_serialize_message(m) for m in messages]
def _get_thread_or_none(thread_id: int) -> Optional[DMThread]:
db = SessionLocal()
try:
return db.query(DMThread).filter(DMThread.id == thread_id).first()
finally:
db.close()
def _save_dm_message(thread_id: int, sender_id: int, text: str) -> DMMessage:
db = SessionLocal()
try:
msg = DMMessage(thread_id=thread_id, sender_id=sender_id, text=text)
db.add(msg)
db.commit()
db.refresh(msg)
return msg
finally:
db.close()
@router.websocket("/threads/{thread_id}/ws")
async def dm_websocket(websocket: WebSocket, thread_id: int, token: str):
"""Mirrors social.py's room_websocket exactly - same JWT-over-query-param verification,
same connect/broadcast/disconnect shape, via the shared ConnectionManager (dm_manager)."""
user_id = user_id_from_ws_token(token)
if user_id is None:
await websocket.close(code=4401)
return
thread = _get_thread_or_none(thread_id)
if not thread:
await websocket.close(code=4404)
return
if user_id not in (thread.user_a_id, thread.user_b_id):
await websocket.close(code=4403)
return
await dm_manager.connect(thread_id, user_id, websocket)
try:
while True:
data = await websocket.receive_json()
msg_type = data.get("type")
if msg_type == "chat":
text = str(data.get("text", ""))[:500]
if not text.strip():
continue
saved = _save_dm_message(thread_id, user_id, text)
# A no-op for whoever's offline right now - no push-notification-on-offline in
# this pass, they'll see it via GET /threads/{id}/messages next time they open it.
await dm_manager.broadcast(thread_id, _serialize_message(saved))
else:
await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"})
except WebSocketDisconnect:
pass
finally:
dm_manager.disconnect(thread_id, user_id)
......@@ -6,8 +6,8 @@ from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisco
from fastapi.responses import FileResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom
from src.core.security import get_current_user, get_current_user_for_stream, decode_token
from src.core.database import get_db, SessionLocal, User, Post, LiveLocation, LibrarySong, LiveRoom, RoomMessage, UserProfile
from src.core.security import get_current_user, get_current_user_for_stream, user_id_from_ws_token
from src.services.room_manager import room_manager
from datetime import datetime, timedelta, timezone
import math
......@@ -158,13 +158,29 @@ LIVE_LOCATION_STALE_AFTER = timedelta(minutes=5) # heartbeats (see the frontend
# server with an authenticated request.
def _visible_live_locations_query(db: Session):
"""Only rows for users who've opted in via UserProfile.share_location_enabled. An outer
join means a LiveLocation row with no UserProfile at all - the actual shape of every row
that existed before this feature - is naturally excluded, since NULL isn't True."""
return (
db.query(LiveLocation)
.outerjoin(UserProfile, UserProfile.user_id == LiveLocation.user_id)
.filter(UserProfile.share_location_enabled.is_(True))
)
@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)."""
periodic heartbeat while sharing is on (see LIVE_LOCATION_STALE_AFTER). Requires the caller
to have opted in via PATCH /auth/privacy first - DELETE (stop sharing) stays ungated below,
since stopping must always work regardless of the flag."""
profile = db.query(UserProfile).filter(UserProfile.user_id == current_user.id).first()
if not profile or not profile.share_location_enabled:
raise HTTPException(status_code=403, detail="Enable location sharing in Settings first")
if data.song_id is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == data.song_id).first()
if not song:
......@@ -197,7 +213,7 @@ def get_nearby_listeners(
):
cutoff = datetime.now(timezone.utc) - LIVE_LOCATION_STALE_AFTER
all_locations = (
db.query(LiveLocation)
_visible_live_locations_query(db)
.filter(LiveLocation.user_id != current_user.id, LiveLocation.updated_at >= cutoff)
.all()
)
......@@ -224,8 +240,10 @@ def get_nearby_listeners(
@router.get("/live-location/{user_id}/stream")
def stream_live_location_song(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_for_stream)):
"""Streams whatever a nearby user is currently playing, regardless of who uploaded it -
same not-scoped-to-caller reasoning as the other social stream endpoints."""
loc = db.query(LiveLocation).filter(LiveLocation.user_id == user_id).first()
same not-scoped-to-caller reasoning as the other social stream endpoints. 404s the same
way for "not sharing at all" and "sharing but opted out of visibility" - not leaking a
distinct "exists but opted out" signal."""
loc = _visible_live_locations_query(db).filter(LiveLocation.user_id == user_id).first()
if not loc:
raise HTTPException(status_code=404, detail="This person isn't sharing their location")
if not loc.song_id:
......@@ -313,26 +331,74 @@ def _set_room_current_song(room_id: int, song_id):
db.close()
def _user_id_from_ws_token(token: str) -> Optional[int]:
"""Browsers' native WebSocket API can't set an Authorization header, so the access token
travels as a query param instead - this still independently verifies it (signature +
expiry + real user row) rather than trusting a bare user_id, which is what let anyone
connect and act as any user before this."""
ROOM_CHAT_PAGE_SIZE = 50
def _save_room_message(room_id: int, user_id: int, text: str) -> RoomMessage:
"""Persists a room chat message - room chat is durable now (room_messages table),
unlike the in-memory deque this replaced that was thrown away the instant a room's last
connection dropped."""
db = SessionLocal()
try:
payload = decode_token(token, expected_type="access")
except Exception:
return None
msg = RoomMessage(room_id=room_id, user_id=user_id, text=text)
db.add(msg)
db.commit()
db.refresh(msg)
return msg
finally:
db.close()
def _get_room_chat_history(room_id: int, limit: int = ROOM_CHAT_PAGE_SIZE) -> list[dict]:
db = SessionLocal()
try:
user = db.query(User).filter(User.id == int(payload["sub"])).first()
return user.id if user else None
messages = (
db.query(RoomMessage)
.filter(RoomMessage.room_id == room_id)
.order_by(RoomMessage.id.desc())
.limit(limit)
.all()
)
messages.reverse()
return [_serialize_room_message(m) for m in messages]
finally:
db.close()
def _serialize_room_message(msg: RoomMessage) -> dict:
"""created_at must be pre-stringified here, not left as a raw datetime - unlike HTTP
responses (which go through FastAPI's jsonable_encoder), a bare WebSocket.send_json() call
is just stdlib json.dumps under the hood and raises TypeError on a datetime."""
return {
"type": "chat",
"id": msg.id,
"user_id": msg.user_id,
"text": msg.text,
"created_at": msg.created_at.isoformat() if msg.created_at else None,
}
@router.get("/rooms/{room_id}/messages")
def get_room_messages(
room_id: int,
before_id: Optional[int] = None,
limit: int = ROOM_CHAT_PAGE_SIZE,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Scrollback beyond the live socket's join-snapshot cap. No membership check - rooms are
unscoped shared content by existing design, same as Posts."""
query = db.query(RoomMessage).filter(RoomMessage.room_id == room_id)
if before_id is not None:
query = query.filter(RoomMessage.id < before_id)
messages = query.order_by(RoomMessage.id.desc()).limit(limit).all()
messages.reverse()
return [_serialize_room_message(m) for m in messages]
@router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, token: str):
user_id = _user_id_from_ws_token(token)
user_id = user_id_from_ws_token(token)
if user_id is None:
await websocket.close(code=4401)
return
......@@ -354,7 +420,7 @@ async def room_websocket(websocket: WebSocket, room_id: int, token: str):
"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),
"chat_history": list(state.chat_history),
"chat_history": _get_room_chat_history(room_id),
"fire_count": state.fire_count(),
"dj_queue": state.dj_queue,
})
......@@ -369,9 +435,8 @@ async def room_websocket(websocket: WebSocket, room_id: int, token: str):
text = str(data.get("text", ""))[:500]
if not text.strip():
continue
chat_msg = {"type": "chat", "user_id": user_id, "text": text}
state.chat_history.append(chat_msg)
await room_manager.broadcast(room_id, chat_msg)
saved = _save_room_message(room_id, user_id, text)
await room_manager.broadcast(room_id, _serialize_room_message(saved))
elif msg_type == "reaction":
emoji = str(data.get("emoji", "🔥"))[:8]
......
......@@ -135,6 +135,16 @@ class UserProfile(Base):
user_id = Column(Integer, ForeignKey("users.id"), unique=True, index=True)
bio = Column(String)
avatar_url = Column(String)
# Both opt-in (default False): a user must explicitly turn these on before anyone else can
# see their LiveLocation row or open a new DM thread with them. Most users have no
# UserProfile row at all yet (this table was otherwise unused before these two columns) -
# every query gating on these must treat a missing row as "opted out," not error or default
# to visible, since that's the actual shape of every account that existed before this
# feature. See _get_or_create_profile (auth.py) for the read/write side, and
# _visible_live_locations_query (social.py) for the query-side "missing row = opted out"
# handling.
share_location_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
allow_direct_messages = Column(Boolean, default=False, nullable=False, server_default="0")
class Follow(Base):
__tablename__ = "follows"
......@@ -261,6 +271,40 @@ class LiveRoom(Base):
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RoomMessage(Base):
"""Persisted room group chat - replaces what used to be an in-memory-only
deque(maxlen=50) on RoomState (room_manager.py) that was discarded entirely the instant a
room's last connection dropped. Rooms are open/unscoped shared content by existing design
(any authenticated user can join any active room, same as Posts) - there's no membership
check on reading these, only on who's *connected live* right now (room_manager.py)."""
__tablename__ = "room_messages"
id = Column(Integer, primary_key=True, index=True)
room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=False)
text = Column(String, nullable=False)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), index=True)
class DMThread(Base):
"""A 1-on-1 conversation between two users. Canonicalized so a pair only ever has one row:
user_a_id is always the smaller of the two user ids, user_b_id the larger - callers must
sort the pair before querying/inserting (see dm.py's _canonical_pair), never insert in
caller-supplied order. Unlike Rooms, a thread's existence and its messages ARE private -
every read must be scoped to `current_user.id in (user_a_id, user_b_id)`."""
__tablename__ = "dm_threads"
__table_args__ = (UniqueConstraint("user_a_id", "user_b_id", name="uq_dm_thread_pair"),)
id = Column(Integer, primary_key=True, index=True)
user_a_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=False)
user_b_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=False)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DMMessage(Base):
__tablename__ = "dm_messages"
id = Column(Integer, primary_key=True, index=True)
thread_id = Column(Integer, ForeignKey("dm_threads.id"), index=True, nullable=False)
sender_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=False)
text = Column(String, nullable=False)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), index=True)
class IdentifiedTrack(Base):
"""Permanent, user-independent cache of prior identification results, keyed by audio
content fingerprint. Lets a song that's already been tagged once (by anyone) skip
......
......@@ -11,7 +11,7 @@ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from src.core.config import JWT_SECRET
from src.core.database import User, get_db
from src.core.database import SessionLocal, User, get_db
JWT_ALGORITHM = "HS256"
ACCESS_TOKEN_TTL = timedelta(minutes=30)
......@@ -114,6 +114,23 @@ def get_current_user_for_stream(
return user
def user_id_from_ws_token(token: str) -> Optional[int]:
"""Browsers' native WebSocket API can't set an Authorization header, so the access token
travels as a query param instead - this still independently verifies it (signature +
expiry + real user row) rather than trusting a bare user_id. Shared by every websocket
endpoint that needs this (Rooms, DMs) rather than each reimplementing it."""
try:
payload = decode_token(token, expected_type="access")
except Exception:
return None
db = SessionLocal()
try:
user = db.query(User).filter(User.id == int(payload["sub"])).first()
return user.id if user else None
finally:
db.close()
def is_super_admin(user: User) -> bool:
return user.role == "super_admin"
......
from fastapi import WebSocket
class ConnectionManager:
"""Generic live-connection registry keyed by an arbitrary int id (a room id, a DM thread
id, ...). Connect/disconnect/broadcast/presence only - anything feature-specific (chat
history, DJ queues, fire meters) lives in the caller, not here. Extracted from what used
to be Rooms-only logic in room_manager.py so DMs can reuse the exact same connect/broadcast/
disconnect shape instead of a second hand-rolled implementation."""
def __init__(self):
self.groups: dict[int, dict[int, WebSocket]] = {} # key_id -> {user_id: websocket}
async def connect(self, key_id: int, user_id: int, websocket: WebSocket):
await websocket.accept()
self.groups.setdefault(key_id, {})[user_id] = websocket
def disconnect(self, key_id: int, user_id: int):
group = self.groups.get(key_id)
if not group:
return
group.pop(user_id, None)
if not group:
self.groups.pop(key_id, None)
async def broadcast(self, key_id: int, message: dict, exclude_user_id: int = None):
group = self.groups.get(key_id)
if not group:
return
dead = []
for uid, ws in list(group.items()):
if uid == exclude_user_id:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(uid)
for uid in dead:
group.pop(uid, None)
def presence(self, key_id: int) -> list:
group = self.groups.get(key_id)
return list(group.keys()) if group else []
from src.services.connection_manager import ConnectionManager
# DMs need nothing beyond connect/broadcast/presence (keyed by thread id), no wrapper class
# required - unlike Rooms there's no DJ queue/fire meter/other feature-specific state to carry.
dm_manager = ConnectionManager()
......@@ -3,21 +3,23 @@ from collections import deque
from fastapi import WebSocket
MAX_CHAT_HISTORY = 50
from src.services.connection_manager import ConnectionManager
FIRE_DECAY_SECONDS = 30 # a "fire meter" reading is how many 🔥 reactions landed in the
# last N seconds, not a lifetime total - it should visibly cool
# off when the room isn't currently popping.
class RoomState:
"""All in-memory, per-room, ephemeral live-session state. None of this is meant to
survive a process restart - it's the equivalent of "who's in the room right now,"
not a historical record. LiveRoom.dj_id/current_song_id in the DB are the durable
parts, updated alongside this."""
"""Genuinely Rooms-specific live-session state (DJ handoff queue, fire meter). Connection
tracking itself now lives in the shared ConnectionManager - chat is no longer part of this
at all, it's persisted to the room_messages table instead (see social.py's
_save_room_message/_get_room_chat_history), since an in-memory deque was thrown away the
instant a room emptied. None of what's left here is meant to survive a process restart -
it's "who's waiting for the aux right now," not a historical record. LiveRoom.dj_id/
current_song_id in the DB are the durable parts, updated alongside this."""
def __init__(self):
self.connections: dict[int, WebSocket] = {} # user_id -> websocket
self.chat_history: deque = deque(maxlen=MAX_CHAT_HISTORY)
self.dj_queue: list = [] # user_ids waiting to be handed the aux
self.fire_events: deque = deque() # timestamps of recent fire reactions
......@@ -31,6 +33,7 @@ class RoomState:
class RoomConnectionManager:
def __init__(self):
self.rooms: dict[int, RoomState] = {}
self._connections = ConnectionManager()
def get_room(self, room_id: int) -> RoomState:
if room_id not in self.rooms:
......@@ -38,40 +41,27 @@ class RoomConnectionManager:
return self.rooms[room_id]
async def connect(self, room_id: int, user_id: int, websocket: WebSocket):
await websocket.accept()
self.get_room(room_id).connections[user_id] = websocket
self.get_room(room_id)
await self._connections.connect(room_id, user_id, websocket)
def disconnect(self, room_id: int, user_id: int):
self._connections.disconnect(room_id, user_id)
room = self.rooms.get(room_id)
if not room:
return
room.connections.pop(user_id, None)
if user_id in room.dj_queue:
room.dj_queue.remove(user_id)
# An empty room's ephemeral state (chat history, fire meter, queue) is discarded -
# the next person to join starts a fresh session, matching how a live room should
# behave once everyone's left.
if not room.connections:
# An empty room's ephemeral state (fire meter, dj queue) is discarded - the next
# person to join starts a fresh session, matching how a live room should behave once
# everyone's left. Chat history survives this via the DB, unlike this in-memory state.
if not self._connections.presence(room_id):
self.rooms.pop(room_id, None)
async def broadcast(self, room_id: int, message: dict, exclude_user_id: int = None):
room = self.rooms.get(room_id)
if not room:
return
dead = []
for uid, ws in list(room.connections.items()):
if uid == exclude_user_id:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(uid)
for uid in dead:
room.connections.pop(uid, None)
await self._connections.broadcast(room_id, message, exclude_user_id=exclude_user_id)
def presence(self, room_id: int) -> list:
room = self.rooms.get(room_id)
return list(room.connections.keys()) if room else []
return self._connections.presence(room_id)
room_manager = RoomConnectionManager()
import pytest
from starlette.websockets import WebSocketDisconnect
from src.core.database import DMMessage, DMThread, SessionLocal
def _token(headers):
return headers["Authorization"].split(" ", 1)[1]
def _allow_dms(client, headers):
response = client.patch("/auth/privacy", json={"allow_direct_messages": True}, headers=headers)
assert response.status_code == 200
def test_create_thread_403s_when_recipient_has_not_opted_in(client, auth_as):
headers, _ = auth_as()
_, recipient = auth_as()
response = client.post("/dm/threads", json={"recipient_id": recipient.id}, headers=headers)
assert response.status_code == 403
def test_create_thread_succeeds_once_recipient_opts_in(client, auth_as):
headers, sender = auth_as()
recipient_headers, recipient = auth_as()
_allow_dms(client, recipient_headers)
response = client.post("/dm/threads", json={"recipient_id": recipient.id}, headers=headers)
assert response.status_code == 201
body = response.json()
assert sorted([body["user_a_id"], body["user_b_id"]]) == sorted([sender.id, recipient.id])
def test_create_thread_is_idempotent_regardless_of_who_initiates(client, auth_as):
headers, sender = auth_as()
recipient_headers, recipient = auth_as()
_allow_dms(client, recipient_headers)
first = client.post("/dm/threads", json={"recipient_id": recipient.id}, headers=headers)
second = client.post("/dm/threads", json={"recipient_id": sender.id}, headers=recipient_headers)
assert first.json()["id"] == second.json()["id"]
db = SessionLocal()
try:
count = db.query(DMThread).filter(DMThread.id == first.json()["id"]).count()
assert count == 1
finally:
db.close()
def test_create_thread_rejects_self_dm(client, auth_as):
headers, user = auth_as()
response = client.post("/dm/threads", json={"recipient_id": user.id}, headers=headers)
assert response.status_code == 400
def test_create_thread_404s_for_unknown_recipient(client, auth_as):
headers, _ = auth_as()
response = client.post("/dm/threads", json={"recipient_id": 999999}, headers=headers)
assert response.status_code == 404
def test_existing_thread_survives_recipient_opting_out_again(client, auth_as):
headers, sender = auth_as()
recipient_headers, recipient = auth_as()
_allow_dms(client, recipient_headers)
thread = client.post("/dm/threads", json={"recipient_id": recipient.id}, headers=headers).json()
client.patch("/auth/privacy", json={"allow_direct_messages": False}, headers=recipient_headers)
# The idempotent POST still returns the same thread rather than 403ing - no re-check of
# the privacy flag on an already-existing thread.
again = client.post("/dm/threads", json={"recipient_id": recipient.id}, headers=headers)
assert again.status_code == 201
assert again.json()["id"] == thread["id"]
# And the recipient (now opted out) can still send into the existing thread over the socket.
with client.websocket_connect(f"/dm/threads/{thread['id']}/ws?token={_token(recipient_headers)}") as ws:
ws.send_json({"type": "chat", "text": "still allowed to reply here"})
echoed = ws.receive_json()
assert echoed["text"] == "still allowed to reply here"
def test_list_threads_only_shows_threads_you_participate_in(client, auth_as):
a_headers, a = auth_as()
b_headers, b = auth_as()
c_headers, c = auth_as()
_allow_dms(client, b_headers)
_allow_dms(client, c_headers)
thread_ab = client.post("/dm/threads", json={"recipient_id": b.id}, headers=a_headers).json()
client.post("/dm/threads", json={"recipient_id": c.id}, headers=b_headers) # thread_bc, a not in it
a_threads = client.get("/dm/threads", headers=a_headers).json()
assert [t["id"] for t in a_threads] == [thread_ab["id"]]
def test_get_thread_messages_403s_for_non_participant(client, auth_as):
a_headers, a = auth_as()
b_headers, b = auth_as()
c_headers, c = auth_as()
_allow_dms(client, b_headers)
thread = client.post("/dm/threads", json={"recipient_id": b.id}, headers=a_headers).json()
response = client.get(f"/dm/threads/{thread['id']}/messages", headers=c_headers)
assert response.status_code == 403
def test_get_thread_messages_404s_for_unknown_thread(client, auth_as):
headers, _ = auth_as()
response = client.get("/dm/threads/999999/messages", headers=headers)
assert response.status_code == 404
def test_dm_websocket_delivers_and_persists_messages(client, auth_as):
a_headers, a = auth_as()
b_headers, b = auth_as()
_allow_dms(client, b_headers)
thread = client.post("/dm/threads", json={"recipient_id": b.id}, headers=a_headers).json()
with client.websocket_connect(f"/dm/threads/{thread['id']}/ws?token={_token(a_headers)}") as ws_a:
with client.websocket_connect(f"/dm/threads/{thread['id']}/ws?token={_token(b_headers)}") as ws_b:
ws_a.send_json({"type": "chat", "text": "hello b"})
on_a = ws_a.receive_json()
on_b = ws_b.receive_json()
assert on_a == on_b
assert on_a["sender_id"] == a.id
assert on_a["text"] == "hello b"
assert isinstance(on_a["id"], int)
db = SessionLocal()
try:
rows = db.query(DMMessage).filter(DMMessage.thread_id == thread["id"]).all()
assert len(rows) == 1
assert rows[0].text == "hello b"
finally:
db.close()
def test_dm_websocket_rejects_missing_token(client, auth_as):
a_headers, a = auth_as()
b_headers, b = auth_as()
_allow_dms(client, b_headers)
thread = client.post("/dm/threads", json={"recipient_id": b.id}, headers=a_headers).json()
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/dm/threads/{thread['id']}/ws"):
pass
def test_dm_websocket_closes_for_unknown_thread(client, auth_as):
headers, _ = auth_as()
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/dm/threads/999999/ws?token={_token(headers)}"):
pass
def test_dm_websocket_rejects_non_participant(client, auth_as):
a_headers, a = auth_as()
b_headers, b = auth_as()
c_headers, c = auth_as()
_allow_dms(client, b_headers)
thread = client.post("/dm/threads", json={"recipient_id": b.id}, headers=a_headers).json()
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect(f"/dm/threads/{thread['id']}/ws?token={_token(c_headers)}"):
pass
from src.core.database import SessionLocal, UserProfile
def test_auth_me_defaults_to_opted_out_with_no_profile_row(client, auth_as):
headers, user = auth_as()
response = client.get("/auth/me", headers=headers)
assert response.status_code == 200
privacy = response.json()["user"]["privacy"]
assert privacy == {"share_location_enabled": False, "allow_direct_messages": False}
def test_patch_privacy_creates_profile_row_on_first_use(client, auth_as):
headers, user = auth_as()
db = SessionLocal()
try:
assert db.query(UserProfile).filter(UserProfile.user_id == user.id).first() is None
finally:
db.close()
response = client.patch("/auth/privacy", json={"share_location_enabled": True}, headers=headers)
assert response.status_code == 200
assert response.json()["privacy"] == {"share_location_enabled": True, "allow_direct_messages": False}
db = SessionLocal()
try:
profile = db.query(UserProfile).filter(UserProfile.user_id == user.id).first()
assert profile is not None
assert profile.share_location_enabled is True
assert profile.allow_direct_messages is False
finally:
db.close()
def test_patch_privacy_partial_update_leaves_other_field_untouched(client, auth_as):
headers, user = auth_as()
client.patch("/auth/privacy", json={"share_location_enabled": True, "allow_direct_messages": True}, headers=headers)
response = client.patch("/auth/privacy", json={"share_location_enabled": False}, headers=headers)
assert response.status_code == 200
assert response.json()["privacy"] == {"share_location_enabled": False, "allow_direct_messages": True}
def test_patch_privacy_empty_body_changes_nothing(client, auth_as):
headers, user = auth_as()
client.patch("/auth/privacy", json={"allow_direct_messages": True}, headers=headers)
response = client.patch("/auth/privacy", json={}, headers=headers)
assert response.status_code == 200
assert response.json()["privacy"] == {"share_location_enabled": False, "allow_direct_messages": True}
import os
import tempfile
from src.core.database import LibrarySong, LiveRoom, SessionLocal
from src.core.database import LibrarySong, LiveRoom, RoomMessage, SessionLocal
def _make_room(dj_id, name="Test Room"):
......@@ -104,7 +104,11 @@ def test_websocket_broadcasts_chat_between_clients(client, auth_as):
ws2.send_json({"type": "chat", "text": "hey everyone"})
chat_on_ws1 = ws1.receive_json()
assert chat_on_ws1 == {"type": "chat", "user_id": user2.id, "text": "hey everyone"}
assert chat_on_ws1["type"] == "chat"
assert chat_on_ws1["user_id"] == user2.id
assert chat_on_ws1["text"] == "hey everyone"
assert isinstance(chat_on_ws1["id"], int)
assert chat_on_ws1["created_at"]
# Broadcasts (chat/reactions) intentionally include the sender too - simpler,
# more predictable than an asymmetric "everyone except me" rule, and clients
......@@ -112,7 +116,66 @@ def test_websocket_broadcasts_chat_between_clients(client, auth_as):
# This bit a manual live-server test script during development (it assumed
# sender exclusion and read messages out of order) - locking it in explicitly.
chat_echoed_to_sender = ws2.receive_json()
assert chat_echoed_to_sender == {"type": "chat", "user_id": user2.id, "text": "hey everyone"}
assert chat_echoed_to_sender == chat_on_ws1 # same canonical row, same id, to both
def test_websocket_chat_persists_a_room_message_row(client, auth_as):
headers, user = auth_as()
room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "chat", "text": "persist me"})
ws.receive_json() # broadcast echo
db = SessionLocal()
try:
rows = db.query(RoomMessage).filter(RoomMessage.room_id == room_id).all()
assert len(rows) == 1
assert rows[0].user_id == user.id
assert rows[0].text == "persist me"
finally:
db.close()
def test_room_chat_history_survives_room_going_empty(client, auth_as):
# The literal regression test for the whole point of persisting chat: the old in-memory
# deque was thrown away the instant a room's last connection dropped, so a reconnect after
# a fully empty room saw nothing. Now it's in the DB.
headers, user = auth_as()
room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "chat", "text": "still here later?"})
ws.receive_json() # broadcast echo
# Room is now fully empty - room_manager discards its in-memory RoomState entirely.
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
snapshot = ws.receive_json()
assert len(snapshot["chat_history"]) == 1
assert snapshot["chat_history"][0]["text"] == "still here later?"
def test_get_room_messages_pagination(client, auth_as):
headers, user = auth_as()
room_id = _make_room(dj_id=user.id)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?token={_token(headers)}") as ws:
ws.receive_json() # snapshot
for i in range(5):
ws.send_json({"type": "chat", "text": f"msg {i}"})
ws.receive_json() # broadcast echo
first_page = client.get(f"/social/rooms/{room_id}/messages?limit=2", headers=headers)
assert first_page.status_code == 200
first_texts = [m["text"] for m in first_page.json()]
assert first_texts == ["msg 3", "msg 4"]
oldest_id_on_page = first_page.json()[0]["id"]
second_page = client.get(
f"/social/rooms/{room_id}/messages?limit=2&before_id={oldest_id_on_page}", headers=headers
)
assert second_page.status_code == 200
second_texts = [m["text"] for m in second_page.json()]
assert second_texts == ["msg 1", "msg 2"]
def test_websocket_reaction_increments_fire_count(client, auth_as):
......
......@@ -2,7 +2,15 @@ import os
import tempfile
from datetime import datetime, timedelta, timezone
from src.core.database import LibrarySong, LiveLocation, SessionLocal
from src.core.database import LibrarySong, LiveLocation, SessionLocal, UserProfile
def _enable_location_sharing(client, headers):
"""PUT /live-location 403s unless the caller has opted in - most of these tests care about
something downstream of sharing succeeding, not the opt-in gate itself (which has its own
dedicated tests below), so they call this first."""
response = client.patch("/auth/privacy", json={"share_location_enabled": True}, headers=headers)
assert response.status_code == 200
def _make_library_song(**overrides):
......@@ -100,6 +108,7 @@ def test_list_posts_returns_only_top_level_ones_with_remix_counts(client, auth_a
def test_share_live_location_creates_then_upserts_a_single_row(client, auth_as):
headers, user = auth_as()
_enable_location_sharing(client, headers)
song_id = _make_library_song(title="First Song")
first = client.put(
......@@ -134,6 +143,7 @@ def test_share_live_location_creates_then_upserts_a_single_row(client, auth_as):
def test_share_live_location_allows_no_song(client, auth_as):
headers, _ = auth_as()
_enable_location_sharing(client, headers)
response = client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
assert response.status_code == 200
assert response.json()["song"] is None
......@@ -141,14 +151,32 @@ def test_share_live_location_allows_no_song(client, auth_as):
def test_share_live_location_requires_a_real_song_if_given(client, auth_as):
headers, _ = auth_as()
_enable_location_sharing(client, headers)
response = client.put(
"/social/live-location", json={"latitude": 0, "longitude": 0, "song_id": 999999}, headers=headers
)
assert response.status_code == 404
def test_share_live_location_403s_until_opted_in(client, auth_as):
headers, user = auth_as()
denied = client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
assert denied.status_code == 403
db = SessionLocal()
try:
assert db.query(LiveLocation).filter(LiveLocation.user_id == user.id).first() is None
finally:
db.close()
_enable_location_sharing(client, headers)
allowed = client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
assert allowed.status_code == 200
def test_stop_sharing_removes_the_row(client, auth_as):
headers, user = auth_as()
_enable_location_sharing(client, headers)
client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
response = client.delete("/social/live-location", headers=headers)
......@@ -173,6 +201,7 @@ def test_get_nearby_listeners_excludes_self(client, auth_as):
# specific id - need deliberately unique, far-apart coordinates per test to avoid picking
# up other tests' rows within the query radius.
headers, _ = auth_as()
_enable_location_sharing(client, headers)
song_id = _make_library_song()
client.put(
"/social/live-location", json={"latitude": 10.0, "longitude": 10.0, "song_id": song_id}, headers=headers
......@@ -186,6 +215,7 @@ def test_get_nearby_listeners_excludes_self(client, auth_as):
def test_get_nearby_listeners_includes_song_info_and_distance(client, auth_as):
mine_headers, _ = auth_as()
other_headers, other = auth_as()
_enable_location_sharing(client, other_headers)
song_id = _make_library_song(title="Close By")
client.put(
"/social/live-location",
......@@ -202,9 +232,52 @@ def test_get_nearby_listeners_includes_song_info_and_distance(client, auth_as):
assert "distance_km" in body[0]
def test_get_nearby_listeners_excludes_users_who_never_opted_in(client, auth_as):
"""The write-side gate (test above) means this shouldn't be reachable through the normal
API anymore, but a direct DB insert also has to be excluded - that's the actual shape of
every LiveLocation row that existed before this feature (no UserProfile row at all)."""
mine_headers, _ = auth_as()
_, other = auth_as()
db = SessionLocal()
try:
db.add(LiveLocation(user_id=other.id, latitude=25.0, longitude=25.0))
db.commit()
finally:
db.close()
response = client.get("/social/live-location/nearby?lat=25.0&lon=25.0&radius_km=1", headers=mine_headers)
assert response.status_code == 200
assert response.json() == []
def test_get_nearby_listeners_disappears_the_instant_sharer_opts_out(client, auth_as):
mine_headers, _ = auth_as()
other_headers, other = auth_as()
_enable_location_sharing(client, other_headers)
song_id = _make_library_song(title="Still Sharing")
client.put(
"/social/live-location", json={"latitude": 40.0, "longitude": 40.0, "song_id": song_id}, headers=other_headers
)
visible = client.get("/social/live-location/nearby?lat=40.0&lon=40.0&radius_km=1", headers=mine_headers)
assert len(visible.json()) == 1
stream_visible = client.get(f"/social/live-location/{other.id}/stream", headers=mine_headers)
assert stream_visible.status_code == 200
client.patch("/auth/privacy", json={"share_location_enabled": False}, headers=other_headers)
gone_from_nearby = client.get("/social/live-location/nearby?lat=40.0&lon=40.0&radius_km=1", headers=mine_headers)
assert gone_from_nearby.json() == []
gone_from_stream = client.get(f"/social/live-location/{other.id}/stream", headers=mine_headers)
assert gone_from_stream.status_code == 404
def test_get_nearby_listeners_excludes_stale_entries(client, auth_as):
mine_headers, _ = auth_as()
other_headers, other = auth_as()
_enable_location_sharing(client, other_headers)
client.put("/social/live-location", json={"latitude": 30.0, "longitude": 30.0}, headers=other_headers)
db = SessionLocal()
......@@ -223,6 +296,7 @@ def test_get_nearby_listeners_excludes_stale_entries(client, auth_as):
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
headers, user = auth_as()
_enable_location_sharing(client, headers)
client.put(
"/social/live-location", json={"latitude": 0, "longitude": 0, "song_id": song_id}, headers=headers
)
......@@ -240,6 +314,7 @@ def test_stream_live_location_404s_when_not_sharing(client, auth_as):
def test_stream_live_location_404s_when_nothing_playing(client, auth_as):
headers, user = auth_as()
_enable_location_sharing(client, headers)
client.put("/social/live-location", json={"latitude": 0, "longitude": 0}, headers=headers)
response = client.get(f"/social/live-location/{user.id}/stream", headers=headers)
......
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