Commit b3b12fe9 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add invite code, PIN, and nearby-map UI for Rooms

Create form gains an optional PIN and a location toggle (via LocationPicker);
a join-by-code form and a "near me" map (new RoomsNearbyMap.tsx) cover the
other two discovery paths. A shared attemptJoin() backs all three entry
points and opens a PIN-entry screen on a 403, distinguishing "wrong PIN" from
other failures. The room's own DJ sees their invite code and PIN status in
RoomView's header; nobody else does.
parent 39411c79
......@@ -50,10 +50,12 @@ export type RoomEvent =
/** Raw WebSocket wrapper for /social/rooms/{id}/ws. Browsers' native WebSocket API can't set
* an Authorization header, so the access token travels as a query param instead - the server
* independently verifies it (signature, expiry, and that the user still exists) rather than
* trusting a client-supplied id. */
export function connectToRoom(roomId: number, accessToken: string, onEvent: (e: RoomEvent) => void): WebSocket {
* trusting a client-supplied id. `pin` is omitted entirely for a room with none set - only
* needed when the room's has_pin is true, same query-param convention as the token itself. */
export function connectToRoom(roomId: number, accessToken: string, pin: string | undefined, onEvent: (e: RoomEvent) => void): WebSocket {
const wsBase = resolveWsBase()
const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?token=${encodeURIComponent(accessToken)}`)
const pinSuffix = pin ? `&pin=${encodeURIComponent(pin)}` : ''
const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?token=${encodeURIComponent(accessToken)}${pinSuffix}`)
ws.onmessage = (msg) => {
try {
onEvent(JSON.parse(msg.data) as RoomEvent)
......
......@@ -97,6 +97,11 @@ export interface LiveRoom {
current_song_id: number | null
name: string
is_active: boolean
has_pin: boolean
/** Only ever populated for the room's own creator - everyone else gets null (see has_pin). */
invite_code: string | null
latitude: number | null
longitude: number | null
created_at: string
}
......@@ -104,13 +109,38 @@ export function getActiveRooms() {
return apiFetch<LiveRoom[]>('/social/rooms')
}
export function createRoom(name: string) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name } })
export function createRoom(name: string, opts?: { pin?: string; latitude?: number; longitude?: number }) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name, ...opts } })
}
export function updateRoom(roomId: number, opts: { name?: string; pin?: string; latitude?: number; longitude?: number }) {
return apiFetch<LiveRoom>(`/social/rooms/${roomId}`, { method: 'PATCH', json: opts })
}
export function getRoomByCode(inviteCode: string) {
return apiFetch<LiveRoom>(`/social/rooms/by-code/${encodeURIComponent(inviteCode)}`)
}
/** The real join gate - verifies the PIN (if any) before handing back the room. Both
* GET .../stream and the websocket enforce this same check independently, so this call isn't
* the only thing standing between a PIN and the room - it's just the UI's first chance to
* surface "wrong PIN" before attempting to actually connect. */
export function joinRoom(opts: { roomId?: number; inviteCode?: string; pin?: string }) {
return apiFetch<LiveRoom>('/social/rooms/join', {
method: 'POST',
json: { room_id: opts.roomId, invite_code: opts.inviteCode, pin: opts.pin },
})
}
export function getNearbyRooms(lat: number, lon: number, radiusKm = 5) {
const params = new URLSearchParams({ lat: String(lat), lon: String(lon), radius_km: String(radiusKm) })
return apiFetch<{ room: LiveRoom; distance_km: number }[]>(`/social/rooms/nearby?${params}`)
}
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for whatever's
* currently playing in a room, regardless of who uploaded the underlying song (mirrors
* api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint). */
export async function fetchRoomStreamUrl(roomId: number): Promise<string> {
return buildStreamUrl(`/social/rooms/${roomId}/stream`)
export async function fetchRoomStreamUrl(roomId: number, pin?: string): Promise<string> {
const suffix = pin ? `?pin=${encodeURIComponent(pin)}` : ''
return buildStreamUrl(`/social/rooms/${roomId}/stream${suffix}`)
}
......@@ -7,6 +7,7 @@ import { clearTokens, setTokens } from '../api/client'
import * as roomSocketApi from '../api/roomSocket'
import type { RoomEvent } from '../api/roomSocket'
import * as socialApi from '../api/social'
import { type LiveRoom } from '../api/social'
import * as libraryApi from '../api/library'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
......@@ -19,10 +20,26 @@ function fakeJwt(payload: object): string {
const SONG = { id: 42, title: 'Now Playing Track', artist: 'The Band', album: null, coverart: null }
function renderRoom(roomId = 1, onLeave = vi.fn()) {
function makeRoom(overrides: Partial<LiveRoom> = {}): LiveRoom {
return {
id: 1,
dj_id: 2,
current_song_id: null,
name: 'Test Room',
is_active: true,
has_pin: false,
invite_code: null,
latitude: null,
longitude: null,
created_at: '2026-01-01T00:00:00Z',
...overrides,
}
}
function renderRoom(roomId = 1, onLeave = vi.fn(), roomOverrides: Partial<LiveRoom> = {}, pin?: string) {
return render(
<PlayerProvider>
<RoomView roomId={roomId} onLeave={onLeave} />
<RoomView room={makeRoom({ id: roomId, ...roomOverrides })} pin={pin} onLeave={onLeave} />
</PlayerProvider>,
)
}
......@@ -35,7 +52,7 @@ describe('RoomView', () => {
clearTokens()
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
fakeWs = { close: vi.fn(), send: vi.fn() }
vi.spyOn(roomSocketApi, 'connectToRoom').mockImplementation((_roomId, _accessToken, onEvent) => {
vi.spyOn(roomSocketApi, 'connectToRoom').mockImplementation((_roomId, _accessToken, _pin, onEvent) => {
emit = onEvent
return fakeWs as unknown as WebSocket
})
......@@ -181,7 +198,7 @@ describe('RoomView', () => {
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => expect(socialApi.fetchRoomStreamUrl).toHaveBeenCalledWith(7))
await waitFor(() => expect(socialApi.fetchRoomStreamUrl).toHaveBeenCalledWith(7, undefined))
expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
......@@ -219,6 +236,31 @@ describe('RoomView', () => {
expect(fakeWs.close).toHaveBeenCalled()
})
it("shows the DJ their own invite code and PIN status, hidden from a listener", () => {
renderRoom(1, vi.fn(), { dj_id: 1, invite_code: 'ABC1234', has_pin: true })
snapshot({ dj_id: 1 })
expect(screen.getByText('ABC1234')).toBeInTheDocument()
expect(screen.getByText('PIN required to join')).toBeInTheDocument()
})
it('does not show the invite code banner to a non-DJ listener', () => {
renderRoom(1, vi.fn(), { dj_id: 2, invite_code: 'ABC1234', has_pin: true })
snapshot({ dj_id: 2 })
expect(screen.queryByText('ABC1234')).not.toBeInTheDocument()
expect(screen.queryByText('PIN required to join')).not.toBeInTheDocument()
})
it('passes the pin through to the stream URL and the websocket connection', async () => {
vi.spyOn(socialApi, 'fetchRoomStreamUrl').mockResolvedValue('blob:fake-room-stream')
renderRoom(7, vi.fn(), { has_pin: true }, '1234')
snapshot({ dj_id: 2, current_song_id: SONG.id, current_song: SONG })
expect(roomSocketApi.connectToRoom).toHaveBeenCalledWith(7, expect.any(String), '1234', expect.any(Function))
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => expect(socialApi.fetchRoomStreamUrl).toHaveBeenCalledWith(7, '1234'))
})
it('calls onLeave when the Leave button is clicked', async () => {
const onLeave = vi.fn()
renderRoom(1, onLeave)
......
import { useEffect, useRef, useState } from 'react'
import { ArrowLeft, Flame, Hand, Music2, Pause, Play, Send, SkipForward } from 'lucide-react'
import { ArrowLeft, Copy, Flame, Hand, Lock, Music2, Pause, Play, Send, SkipForward } from 'lucide-react'
import { getCurrentUserId } from '../api/jwt'
import { getAccessToken } from '../api/client'
import { fetchRoomStreamUrl } from '../api/social'
import { fetchRoomStreamUrl, type LiveRoom } from '../api/social'
import {
connectToRoom,
passAux,
......@@ -18,7 +18,7 @@ import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { SongPicker } from './SongPicker'
function toPlayable(roomId: number, song: RoomSong) {
function toPlayable(roomId: number, song: RoomSong, pin: string | undefined) {
return {
// Negative to avoid colliding with a real LibrarySong id (see PlayableSong's `streamUrl`
// doc) - keyed off the room, not the song, so the play/pause glyph stays correctly tied
......@@ -28,11 +28,12 @@ function toPlayable(roomId: number, song: RoomSong) {
artist: song.artist,
album: song.album,
coverart: song.coverart,
streamUrl: () => fetchRoomStreamUrl(roomId),
streamUrl: () => fetchRoomStreamUrl(roomId, pin),
}
}
export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => void }) {
export function RoomView({ room, pin, onLeave }: { room: LiveRoom; pin?: string; onLeave: () => void }) {
const roomId = room.id
const userId = getCurrentUserId()
const [messages, setMessages] = useState<ChatMessage[]>([])
const [fireCount, setFireCount] = useState(0)
......@@ -56,7 +57,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
useEffect(() => {
const accessToken = getAccessToken()
if (accessToken === null) return
const ws = connectToRoom(roomId, accessToken, (event) => {
const ws = connectToRoom(roomId, accessToken, pin, (event) => {
switch (event.type) {
case 'snapshot':
setMessages(event.chat_history)
......@@ -111,7 +112,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
}
const isDj = djId !== null && userId === djId
const active = currentSong ? toPlayable(roomId, currentSong) : null
const active = currentSong ? toPlayable(roomId, currentSong, pin) : null
const isCurrent = !!active && playerSong?.id === active.id
return (
......@@ -138,6 +139,27 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
</div>
</header>
{userId === room.dj_id && (room.invite_code || room.has_pin) && (
<div className="flex shrink-0 flex-wrap items-center gap-3 border-b border-outline-variant/80 bg-surface-container/60 px-4 py-2 text-xs text-on-surface-variant">
{room.invite_code && (
<button
onClick={() => navigator.clipboard?.writeText(room.invite_code!)}
className="flex items-center gap-1.5 transition-colors hover:text-on-surface"
aria-label={`Copy invite code ${room.invite_code}`}
>
Invite code: <span className="font-mono font-medium text-on-surface">{room.invite_code}</span>
<Copy size={12} strokeWidth={2} />
</button>
)}
{room.has_pin && (
<span className="flex items-center gap-1">
<Lock size={12} strokeWidth={2} />
PIN required to join
</span>
)}
</div>
)}
<div className="shrink-0 border-b border-outline-variant/80 px-4 py-3">
{currentSong && active ? (
<button
......
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { RoomsNearbyMap } from './RoomsNearbyMap'
import type { LiveRoom } from '../api/social'
const ROOM: LiveRoom = {
id: 1,
dj_id: 5,
current_song_id: null,
name: 'Friday Night Vibes',
is_active: true,
has_pin: false,
invite_code: null,
latitude: 37.7749,
longitude: -122.4194,
created_at: '2026-01-01T00:00:00Z',
}
function renderMap(props: Partial<React.ComponentProps<typeof RoomsNearbyMap>> = {}) {
return render(
<RoomsNearbyMap
userLocation={{ lat: 37.7749, lon: -122.4194 }}
rooms={[{ room: ROOM, distance_km: 0.3 }]}
onSelectRoom={vi.fn()}
{...props}
/>,
)
}
describe('RoomsNearbyMap', () => {
it('renders without crashing given a nearby room', () => {
renderMap()
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('renders with an empty rooms list (just the live location dot)', () => {
renderMap({ rooms: [] })
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('the "Center on me" button is clickable without throwing', async () => {
renderMap()
await userEvent.click(screen.getByRole('button', { name: 'Center on me' }))
})
})
import { useEffect, useState } from 'react'
import { CircleMarker, MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
import type { Map as LeafletMap } from 'leaflet'
import { LocateFixed } from 'lucide-react'
import type { LiveRoom } from '../api/social'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, soundmarkIcon } from '../lib/mapTheme'
const INITIAL_ZOOM = 14
interface RoomsNearbyMapProps {
userLocation: { lat: number; lon: number }
rooms: { room: LiveRoom; distance_km: number }[]
onSelectRoom: (room: LiveRoom) => void
}
/** Same CenterOnMount/centerOnMe pattern as SoundmarkMap.tsx - pans to the user's position once
* on mount, with an explicit "center on me" button for afterward rather than fighting anyone
* panning around to look at nearby rooms. */
function CenterOnMount({ lat, lon }: { lat: number; lon: number }) {
const map = useMap()
useEffect(() => {
map.setView([lat, lon], INITIAL_ZOOM)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return null
}
export function RoomsNearbyMap({ userLocation, rooms, onSelectRoom }: RoomsNearbyMapProps) {
const [map, setMap] = useState<LeafletMap | null>(null)
function centerOnMe() {
map?.setView([userLocation.lat, userLocation.lon], INITIAL_ZOOM)
}
return (
<div className="relative h-64 overflow-hidden rounded-xl border border-outline-variant">
<MapContainer
ref={setMap}
center={[userLocation.lat, userLocation.lon]}
zoom={INITIAL_ZOOM}
className="h-full w-full"
scrollWheelZoom={false}
>
<TileLayer attribution={DARK_TILE_ATTRIBUTION} url={DARK_TILE_URL} />
<CenterOnMount lat={userLocation.lat} lon={userLocation.lon} />
<CircleMarker
center={[userLocation.lat, userLocation.lon]}
radius={8}
pathOptions={{ color: '#2e5bff', fillColor: '#b8c3ff', fillOpacity: 1, weight: 2 }}
>
<Popup>You are here</Popup>
</CircleMarker>
{rooms.map(({ room, distance_km }) => (
<Marker
key={room.id}
position={[room.latitude!, room.longitude!]}
icon={soundmarkIcon('generic')}
eventHandlers={{ click: () => onSelectRoom(room) }}
>
<Popup>
<span className="font-medium">{room.name}</span>
<br />
{distance_km < 1 ? `${Math.round(distance_km * 1000)}m away` : `${distance_km.toFixed(1)}km away`}
{room.has_pin && (
<>
<br />
PIN required
</>
)}
</Popup>
</Marker>
))}
</MapContainer>
<button
onClick={centerOnMe}
aria-label="Center on me"
className="absolute bottom-3 right-3 z-[1000] flex h-9 w-9 items-center justify-center rounded-full bg-surface-container/90 text-on-surface shadow-lg backdrop-blur transition-colors hover:bg-surface-container-high focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<LocateFixed size={16} strokeWidth={2} />
</button>
</div>
)
}
......@@ -65,6 +65,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Connection requires a verified access token, not a client-supplied user_id',
'Cross-user song streaming - a listener hears what the DJ actually picked',
'Chat is DB-backed now (2026-09-13, RoomMessage table), not a 50-message in-memory deque that used to be thrown away the instant a room\'s last connection dropped - a room emptying and refilling now still has its history. New GET /social/rooms/{id}/messages?before_id=&limit= for scrollback beyond the join snapshot\'s own cap. The websocket connection-registry logic (connect/disconnect/broadcast/presence) was extracted into a generic ConnectionManager (src/services/connection_manager.py) so Direct Messages below could reuse the exact same shape instead of a second hand-rolled implementation; RoomConnectionManager now delegates to it.',
'Real invite code, 4-digit PIN, and location discovery (2026-10-12): rooms used to be open-join-by-id only with no geo features at all, despite that being the intended design - a 7-character unambiguous invite_code is now generated server-side on every create (GET /social/rooms/by-code/{code} looks one up), and an optional PIN (pin_hash, PBKDF2 via the same hash_password used for account passwords) gates both the new POST /social/rooms/join and - since a join-time gate is pointless if the content is reachable around it - the existing stream and websocket endpoints too. PIN guesses are rate-limited per room+user and per room+ip (AuthAttempt gained nullable room_id/user_id columns for this, a third reuse of the same table phone-codes and login brute-force already share). New PATCH /social/rooms/{id} (owner-only, pin: "" clears) and GET /social/rooms/nearby?lat=&lon=&radius_km= (haversine-filtered, sorted by distance - the haversine math itself was pulled out of soundmarks.py into a shared src/services/geo.py once a second caller needed the identical formula). Frontend: PIN input + an optional location picker on create, a join-by-code form, a PIN-entry screen that distinguishes "wrong PIN, retry" from other failures, and a "near me" map (new RoomsNearbyMap.tsx) for finding location-tied rooms visually; the invite code and PIN status are shown to the room\'s own DJ once inside, nobody else.',
],
},
{
......
This diff is collapsed.
This diff is collapsed.
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