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 = ...@@ -50,10 +50,12 @@ export type RoomEvent =
/** Raw WebSocket wrapper for /social/rooms/{id}/ws. Browsers' native WebSocket API can't set /** 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 * 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 * independently verifies it (signature, expiry, and that the user still exists) rather than
* trusting a client-supplied id. */ * trusting a client-supplied id. `pin` is omitted entirely for a room with none set - only
export function connectToRoom(roomId: number, accessToken: string, onEvent: (e: RoomEvent) => void): WebSocket { * 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 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) => { ws.onmessage = (msg) => {
try { try {
onEvent(JSON.parse(msg.data) as RoomEvent) onEvent(JSON.parse(msg.data) as RoomEvent)
......
...@@ -97,6 +97,11 @@ export interface LiveRoom { ...@@ -97,6 +97,11 @@ export interface LiveRoom {
current_song_id: number | null current_song_id: number | null
name: string name: string
is_active: boolean 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 created_at: string
} }
...@@ -104,13 +109,38 @@ export function getActiveRooms() { ...@@ -104,13 +109,38 @@ export function getActiveRooms() {
return apiFetch<LiveRoom[]>('/social/rooms') return apiFetch<LiveRoom[]>('/social/rooms')
} }
export function createRoom(name: string) { export function createRoom(name: string, opts?: { pin?: string; latitude?: number; longitude?: number }) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name } }) 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 /** 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 * currently playing in a room, regardless of who uploaded the underlying song (mirrors
* api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint). */ * api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint). */
export async function fetchRoomStreamUrl(roomId: number): Promise<string> { export async function fetchRoomStreamUrl(roomId: number, pin?: string): Promise<string> {
return buildStreamUrl(`/social/rooms/${roomId}/stream`) const suffix = pin ? `?pin=${encodeURIComponent(pin)}` : ''
return buildStreamUrl(`/social/rooms/${roomId}/stream${suffix}`)
} }
...@@ -7,6 +7,7 @@ import { clearTokens, setTokens } from '../api/client' ...@@ -7,6 +7,7 @@ import { clearTokens, setTokens } from '../api/client'
import * as roomSocketApi from '../api/roomSocket' import * as roomSocketApi from '../api/roomSocket'
import type { RoomEvent } from '../api/roomSocket' import type { RoomEvent } from '../api/roomSocket'
import * as socialApi from '../api/social' import * as socialApi from '../api/social'
import { type LiveRoom } from '../api/social'
import * as libraryApi from '../api/library' import * as libraryApi from '../api/library'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies, /** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
...@@ -19,10 +20,26 @@ function fakeJwt(payload: object): string { ...@@ -19,10 +20,26 @@ function fakeJwt(payload: object): string {
const SONG = { id: 42, title: 'Now Playing Track', artist: 'The Band', album: null, coverart: null } 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( return render(
<PlayerProvider> <PlayerProvider>
<RoomView roomId={roomId} onLeave={onLeave} /> <RoomView room={makeRoom({ id: roomId, ...roomOverrides })} pin={pin} onLeave={onLeave} />
</PlayerProvider>, </PlayerProvider>,
) )
} }
...@@ -35,7 +52,7 @@ describe('RoomView', () => { ...@@ -35,7 +52,7 @@ describe('RoomView', () => {
clearTokens() clearTokens()
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused') setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
fakeWs = { close: vi.fn(), send: vi.fn() } 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 emit = onEvent
return fakeWs as unknown as WebSocket return fakeWs as unknown as WebSocket
}) })
...@@ -181,7 +198,7 @@ describe('RoomView', () => { ...@@ -181,7 +198,7 @@ describe('RoomView', () => {
await userEvent.click(screen.getByRole('button', { name: 'Play' })) 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() expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
}) })
...@@ -219,6 +236,31 @@ describe('RoomView', () => { ...@@ -219,6 +236,31 @@ describe('RoomView', () => {
expect(fakeWs.close).toHaveBeenCalled() 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 () => { it('calls onLeave when the Leave button is clicked', async () => {
const onLeave = vi.fn() const onLeave = vi.fn()
renderRoom(1, onLeave) renderRoom(1, onLeave)
......
import { useEffect, useRef, useState } from 'react' 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 { getCurrentUserId } from '../api/jwt'
import { getAccessToken } from '../api/client' import { getAccessToken } from '../api/client'
import { fetchRoomStreamUrl } from '../api/social' import { fetchRoomStreamUrl, type LiveRoom } from '../api/social'
import { import {
connectToRoom, connectToRoom,
passAux, passAux,
...@@ -18,7 +18,7 @@ import { Button } from './ui/Button' ...@@ -18,7 +18,7 @@ import { Button } from './ui/Button'
import { Input } from './ui/Input' import { Input } from './ui/Input'
import { SongPicker } from './SongPicker' import { SongPicker } from './SongPicker'
function toPlayable(roomId: number, song: RoomSong) { function toPlayable(roomId: number, song: RoomSong, pin: string | undefined) {
return { return {
// Negative to avoid colliding with a real LibrarySong id (see PlayableSong's `streamUrl` // 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 // 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) { ...@@ -28,11 +28,12 @@ function toPlayable(roomId: number, song: RoomSong) {
artist: song.artist, artist: song.artist,
album: song.album, album: song.album,
coverart: song.coverart, 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 userId = getCurrentUserId()
const [messages, setMessages] = useState<ChatMessage[]>([]) const [messages, setMessages] = useState<ChatMessage[]>([])
const [fireCount, setFireCount] = useState(0) const [fireCount, setFireCount] = useState(0)
...@@ -56,7 +57,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v ...@@ -56,7 +57,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
useEffect(() => { useEffect(() => {
const accessToken = getAccessToken() const accessToken = getAccessToken()
if (accessToken === null) return if (accessToken === null) return
const ws = connectToRoom(roomId, accessToken, (event) => { const ws = connectToRoom(roomId, accessToken, pin, (event) => {
switch (event.type) { switch (event.type) {
case 'snapshot': case 'snapshot':
setMessages(event.chat_history) setMessages(event.chat_history)
...@@ -111,7 +112,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v ...@@ -111,7 +112,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
} }
const isDj = djId !== null && userId === djId 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 const isCurrent = !!active && playerSong?.id === active.id
return ( return (
...@@ -138,6 +139,27 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v ...@@ -138,6 +139,27 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
</div> </div>
</header> </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"> <div className="shrink-0 border-b border-outline-variant/80 px-4 py-3">
{currentSong && active ? ( {currentSong && active ? (
<button <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[] = [ ...@@ -65,6 +65,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Connection requires a verified access token, not a client-supplied user_id', 'Connection requires a verified access token, not a client-supplied user_id',
'Cross-user song streaming - a listener hears what the DJ actually picked', '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.', '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.',
], ],
}, },
{ {
......
...@@ -5,28 +5,61 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' ...@@ -5,28 +5,61 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Rooms } from './Rooms' import { Rooms } from './Rooms'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as socialApi from '../api/social' import * as socialApi from '../api/social'
// RoomView renders a real WebSocket-backed chat UI, fully covered by its own test file - here // RoomView renders a real WebSocket-backed chat UI, fully covered by its own test file - here
// it's stubbed down to its essential contract: show which room it's in and call onLeave. // it's stubbed down to its essential contract: show which room it's in and call onLeave.
vi.mock('../components/RoomView', () => ({ vi.mock('../components/RoomView', () => ({
RoomView: ({ roomId, onLeave }: { roomId: number; onLeave: () => void }) => ( RoomView: ({ room, onLeave }: { room: socialApi.LiveRoom; onLeave: () => void }) => (
<div> <div>
<p>In room {roomId}</p> <p>In room {room.id}</p>
<button onClick={onLeave}>Leave</button> <button onClick={onLeave}>Leave</button>
</div> </div>
), ),
})) }))
const ROOM: socialApi.LiveRoom = { // LocationPicker renders a real Leaflet map, which doesn't render meaningfully in jsdom - its
// own test file covers it directly, so here it's stubbed to its essential contract.
vi.mock('../components/LocationPicker', () => ({
LocationPicker: ({ onChange }: { onChange: (lat: number, lon: number) => void }) => (
<button type="button" onClick={() => onChange(12.5, 45.5)}>
Set location (mock)
</button>
),
}))
vi.mock('../components/RoomsNearbyMap', () => ({
RoomsNearbyMap: ({ rooms, onSelectRoom }: { rooms: { room: socialApi.LiveRoom }[]; onSelectRoom: (r: socialApi.LiveRoom) => void }) => (
<div>
<p>Nearby map ({rooms.length} rooms)</p>
{rooms.map(({ room }) => (
<button key={room.id} onClick={() => onSelectRoom(room)}>
Map pin: {room.name}
</button>
))}
</div>
),
}))
function makeRoom(overrides: Partial<socialApi.LiveRoom> = {}): socialApi.LiveRoom {
return {
id: 1, id: 1,
dj_id: 5, dj_id: 5,
current_song_id: null, current_song_id: null,
name: 'Friday Night Vibes', name: 'Friday Night Vibes',
is_active: true, is_active: true,
has_pin: false,
invite_code: null,
latitude: null,
longitude: null,
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
...overrides,
}
} }
const ROOM = makeRoom()
function renderRooms() { function renderRooms() {
return render( return render(
<MemoryRouter> <MemoryRouter>
...@@ -63,11 +96,13 @@ describe('Rooms', () => { ...@@ -63,11 +96,13 @@ describe('Rooms', () => {
expect(screen.getByText('DJ #5')).toBeInTheDocument() expect(screen.getByText('DJ #5')).toBeInTheDocument()
}) })
it('joins a room when clicked, and leaving returns to the list', async () => { it('joins a room with no PIN when clicked, and leaving returns to the list', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([ROOM]) vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([ROOM])
const join = vi.spyOn(socialApi, 'joinRoom').mockResolvedValue(ROOM)
renderRooms() renderRooms()
await userEvent.click(await screen.findByText('Friday Night Vibes')) await userEvent.click(await screen.findByText('Friday Night Vibes'))
expect(join).toHaveBeenCalledWith({ roomId: 1 })
expect(await screen.findByText('In room 1')).toBeInTheDocument() expect(await screen.findByText('In room 1')).toBeInTheDocument()
expect(screen.queryByText('Friday Night Vibes')).not.toBeInTheDocument() expect(screen.queryByText('Friday Night Vibes')).not.toBeInTheDocument()
...@@ -77,14 +112,7 @@ describe('Rooms', () => { ...@@ -77,14 +112,7 @@ describe('Rooms', () => {
it('creates a room and jumps straight into it', async () => { it('creates a room and jumps straight into it', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([]) vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom').mockResolvedValue({ const create = vi.spyOn(socialApi, 'createRoom').mockResolvedValue(makeRoom({ id: 9, dj_id: 1, name: 'New Room' }))
id: 9,
dj_id: 1,
current_song_id: null,
name: 'New Room',
is_active: true,
created_at: '2026-01-01T00:00:00Z',
})
renderRooms() renderRooms()
await screen.findByText(/No active rooms right now/) await screen.findByText(/No active rooms right now/)
...@@ -92,10 +120,37 @@ describe('Rooms', () => { ...@@ -92,10 +120,37 @@ describe('Rooms', () => {
await userEvent.type(screen.getByPlaceholderText('Room name'), 'New Room') await userEvent.type(screen.getByPlaceholderText('Room name'), 'New Room')
await userEvent.click(screen.getByRole('button', { name: 'Start' })) await userEvent.click(screen.getByRole('button', { name: 'Start' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('New Room')) await waitFor(() => expect(create).toHaveBeenCalledWith('New Room', { pin: undefined, latitude: undefined, longitude: undefined }))
expect(await screen.findByText('In room 9')).toBeInTheDocument() expect(await screen.findByText('In room 9')).toBeInTheDocument()
}) })
it('creates a room with a PIN', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom').mockResolvedValue(makeRoom({ id: 9, dj_id: 1, has_pin: true }))
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.type(screen.getByPlaceholderText('Room name'), 'Secret Room')
await userEvent.type(screen.getByPlaceholderText('PIN (optional)'), '1234')
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('Secret Room', { pin: '1234', latitude: undefined, longitude: undefined }))
})
it('creates a room tied to a location', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom').mockResolvedValue(makeRoom({ id: 9, dj_id: 1 }))
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.type(screen.getByPlaceholderText('Room name'), 'Pinned Room')
await userEvent.click(screen.getByText(/Tie to a real-world location/))
await userEvent.click(screen.getByText('Set location (mock)'))
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('Pinned Room', { pin: undefined, latitude: 12.5, longitude: 45.5 }))
})
it('does not create a room from a blank name', async () => { it('does not create a room from a blank name', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([]) vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom') const create = vi.spyOn(socialApi, 'createRoom')
...@@ -106,4 +161,96 @@ describe('Rooms', () => { ...@@ -106,4 +161,96 @@ describe('Rooms', () => {
expect(create).not.toHaveBeenCalled() expect(create).not.toHaveBeenCalled()
}) })
it('shows a lock icon next to a PIN-protected room in the list', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([makeRoom({ has_pin: true })])
renderRooms()
const row = await screen.findByText('Friday Night Vibes')
expect(row.parentElement?.querySelector('svg')).toBeInTheDocument()
})
it('prompts for a PIN when clicking a PIN-protected room, then joins on success', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([makeRoom({ has_pin: true })])
const join = vi.spyOn(socialApi, 'joinRoom').mockResolvedValue(ROOM)
renderRooms()
await userEvent.click(await screen.findByText('Friday Night Vibes'))
expect(join).not.toHaveBeenCalled()
expect(await screen.findByPlaceholderText('PIN')).toBeInTheDocument()
await userEvent.type(screen.getByPlaceholderText('PIN'), '1234')
await userEvent.click(screen.getByRole('button', { name: 'Join' }))
expect(join).toHaveBeenCalledWith({ roomId: 1, inviteCode: undefined, pin: '1234' })
expect(await screen.findByText('In room 1')).toBeInTheDocument()
})
it('shows an error and lets you retry after an incorrect PIN', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([makeRoom({ has_pin: true })])
const join = vi
.spyOn(socialApi, 'joinRoom')
.mockRejectedValueOnce(new ApiError(403, 'Incorrect PIN', null))
.mockResolvedValueOnce(ROOM)
renderRooms()
await userEvent.click(await screen.findByText('Friday Night Vibes'))
await userEvent.type(screen.getByPlaceholderText('PIN'), '0000')
await userEvent.click(screen.getByRole('button', { name: 'Join' }))
expect(await screen.findByText('Incorrect PIN - try again.')).toBeInTheDocument()
await userEvent.clear(screen.getByPlaceholderText('PIN'))
await userEvent.type(screen.getByPlaceholderText('PIN'), '1234')
await userEvent.click(screen.getByRole('button', { name: 'Join' }))
expect(join).toHaveBeenCalledTimes(2)
expect(await screen.findByText('In room 1')).toBeInTheDocument()
})
it('cancels out of the PIN prompt back to the room list', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([makeRoom({ has_pin: true })])
renderRooms()
await userEvent.click(await screen.findByText('Friday Night Vibes'))
await screen.findByPlaceholderText('PIN')
await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(await screen.findByText('Friday Night Vibes')).toBeInTheDocument()
})
it('joins a room by invite code', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const join = vi.spyOn(socialApi, 'joinRoom').mockResolvedValue(makeRoom({ id: 3 }))
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.type(screen.getByPlaceholderText('Join by invite code'), 'abc1234')
await userEvent.click(screen.getByRole('button', { name: 'Join' }))
expect(join).toHaveBeenCalledWith({ inviteCode: 'ABC1234' })
expect(await screen.findByText('In room 3')).toBeInTheDocument()
})
it('shows "near me" results on a map and joins a room tapped from a pin', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const nearbyRoom = makeRoom({ id: 4, name: 'Nearby Room', latitude: 10, longitude: 20 })
vi.spyOn(socialApi, 'getNearbyRooms').mockResolvedValue([{ room: nearbyRoom, distance_km: 0.5 }])
const join = vi.spyOn(socialApi, 'joinRoom').mockResolvedValue(nearbyRoom)
const getCurrentPosition = vi.fn((success: PositionCallback) => {
success({ coords: { latitude: 10, longitude: 20 } } as GeolocationPosition)
})
vi.stubGlobal('navigator', { ...navigator, geolocation: { getCurrentPosition } })
vi.stubGlobal('isSecureContext', true)
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: /Near me/ }))
expect(await screen.findByText('Nearby map (1 rooms)')).toBeInTheDocument()
await userEvent.click(screen.getByText('Map pin: Nearby Room'))
expect(join).toHaveBeenCalledWith({ roomId: 4 })
expect(await screen.findByText('In room 4')).toBeInTheDocument()
})
}) })
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { ChevronRight, Radio } from 'lucide-react' import { ChevronRight, Lock, MapPin, Radio } from 'lucide-react'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input' import { Input } from '../components/ui/Input'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
import { createRoom, getActiveRooms, type LiveRoom } from '../api/social' import { LocationPicker } from '../components/LocationPicker'
import { RoomsNearbyMap } from '../components/RoomsNearbyMap'
import { ApiError } from '../api/client'
import { createRoom, getActiveRooms, getNearbyRooms, joinRoom, type LiveRoom } from '../api/social'
import { RoomView } from '../components/RoomView' import { RoomView } from '../components/RoomView'
/** Which room (by id or invite code) a PIN prompt is currently being collected for - set
* whenever a join attempt comes back 403 without one, or when picking a room already known to
* have a PIN from either list. Cleared on success or cancel. */
interface PendingJoin {
roomId?: number
inviteCode?: string
label: string
}
export function Rooms() { export function Rooms() {
const [rooms, setRooms] = useState<LiveRoom[]>([]) const [rooms, setRooms] = useState<LiveRoom[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [newRoomName, setNewRoomName] = useState('') const [newRoomName, setNewRoomName] = useState('')
const [activeRoomId, setActiveRoomId] = useState<number | null>(null) const [newRoomPin, setNewRoomPin] = useState('')
const [tieToLocation, setTieToLocation] = useState(false)
const [newLat, setNewLat] = useState<number | null>(null)
const [newLon, setNewLon] = useState<number | null>(null)
const [joinCode, setJoinCode] = useState('')
const [pendingJoin, setPendingJoin] = useState<PendingJoin | null>(null)
const [pinInput, setPinInput] = useState('')
const [joinError, setJoinError] = useState<string | null>(null)
const [activeRoom, setActiveRoom] = useState<{ room: LiveRoom; pin?: string } | null>(null)
const [showNearby, setShowNearby] = useState(false)
const [nearbyRooms, setNearbyRooms] = useState<{ room: LiveRoom; distance_km: number }[]>([])
const [nearbyStatus, setNearbyStatus] = useState<'idle' | 'locating' | 'ready' | 'error'>('idle')
const [nearbyError, setNearbyError] = useState<string | null>(null)
function refresh() { function refresh() {
getActiveRooms() getActiveRooms()
...@@ -23,27 +50,204 @@ export function Rooms() { ...@@ -23,27 +50,204 @@ export function Rooms() {
async function handleCreate(e: React.FormEvent) { async function handleCreate(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
if (!newRoomName.trim()) return if (!newRoomName.trim()) return
const room = await createRoom(newRoomName.trim()) const room = await createRoom(newRoomName.trim(), {
pin: newRoomPin || undefined,
latitude: tieToLocation && newLat !== null ? newLat : undefined,
longitude: tieToLocation && newLon !== null ? newLon : undefined,
})
setNewRoomName('') setNewRoomName('')
setNewRoomPin('')
setTieToLocation(false)
setNewLat(null)
setNewLon(null)
setRooms((r) => [room, ...r]) setRooms((r) => [room, ...r])
setActiveRoomId(room.id) // The creator's own invite code/PIN status is shown in RoomView's header once inside -
// no separate banner needed here.
setActiveRoom({ room })
}
/** Shared by every join path (list click, join-by-code, nearby-map pin) - tries the join,
* and if it comes back 403 with no PIN supplied yet, opens the PIN prompt remembering which
* room/code to retry against rather than failing outright. */
async function attemptJoin(opts: { roomId?: number; inviteCode?: string; pin?: string }, label: string) {
setJoinError(null)
try {
const room = await joinRoom(opts)
setPendingJoin(null)
setPinInput('')
setActiveRoom({ room, pin: opts.pin })
} catch (err) {
if (err instanceof ApiError && err.status === 403) {
setPendingJoin({ roomId: opts.roomId, inviteCode: opts.inviteCode, label })
setJoinError(opts.pin ? 'Incorrect PIN - try again.' : null)
} else if (err instanceof ApiError && err.status === 429) {
setJoinError(err.message || 'Too many attempts - try again later.')
} else if (err instanceof ApiError && err.status === 404) {
setJoinError('Room not found.')
} else {
setJoinError('Could not join this room.')
}
}
}
function handlePickRoom(room: LiveRoom) {
if (room.has_pin) {
setPendingJoin({ roomId: room.id, label: room.name })
setJoinError(null)
return
}
attemptJoin({ roomId: room.id }, room.name)
}
function handleJoinByCode(e: React.FormEvent) {
e.preventDefault()
if (!joinCode.trim()) return
attemptJoin({ inviteCode: joinCode.trim() }, joinCode.trim())
}
function handleSubmitPin(e: React.FormEvent) {
e.preventDefault()
if (!pendingJoin) return
attemptJoin({ roomId: pendingJoin.roomId, inviteCode: pendingJoin.inviteCode, pin: pinInput }, pendingJoin.label)
}
function startNearbySearch() {
setShowNearby(true)
if (!navigator.geolocation) {
setNearbyStatus('error')
setNearbyError("Your browser doesn't support location services.")
return
}
if (!window.isSecureContext) {
setNearbyStatus('error')
setNearbyError('Location access requires a secure (https://) connection.')
return
}
setNearbyStatus('locating')
setNearbyError(null)
navigator.geolocation.getCurrentPosition(
(pos) => {
getNearbyRooms(pos.coords.latitude, pos.coords.longitude)
.then((results) => {
setNearbyRooms(results)
setNearbyStatus('ready')
})
.catch(() => {
setNearbyStatus('error')
setNearbyError('Could not load nearby rooms.')
})
},
(err) => {
setNearbyStatus('error')
setNearbyError(
err.code === err.PERMISSION_DENIED
? 'Location access was denied - allow it in your browser settings to find rooms near you.'
: "Couldn't determine your location. Please try again.",
)
},
{ enableHighAccuracy: true, timeout: 15000 },
)
} }
if (activeRoomId !== null) { if (activeRoom !== null) {
return <RoomView roomId={activeRoomId} onLeave={() => setActiveRoomId(null)} /> return <RoomView room={activeRoom.room} pin={activeRoom.pin} onLeave={() => setActiveRoom(null)} />
}
if (pendingJoin) {
return (
<div className="mx-auto max-w-sm">
<h2 className="mb-1 text-lg font-semibold text-on-surface">{pendingJoin.label}</h2>
<p className="mb-4 text-sm text-on-surface-variant">This room needs a 4-digit PIN to join.</p>
<form onSubmit={handleSubmitPin} className="space-y-3">
<Input
value={pinInput}
onChange={(e) => setPinInput(e.target.value.replace(/\D/g, '').slice(0, 4))}
placeholder="PIN"
inputMode="numeric"
autoFocus
/>
{joinError && <p className="text-sm text-error">{joinError}</p>}
<div className="flex gap-2">
<Button type="submit" disabled={pinInput.length !== 4}>
Join
</Button>
<Button
type="button"
variant="secondary"
onClick={() => {
setPendingJoin(null)
setPinInput('')
setJoinError(null)
}}
>
Cancel
</Button>
</div>
</form>
</div>
)
} }
return ( return (
<> <>
<form onSubmit={handleCreate} className="mb-6 flex gap-2"> <form onSubmit={handleCreate} className="mb-4 space-y-2">
<div className="flex gap-2">
<Input value={newRoomName} onChange={(e) => setNewRoomName(e.target.value)} placeholder="Room name" />
<Input <Input
value={newRoomName} value={newRoomPin}
onChange={(e) => setNewRoomName(e.target.value)} onChange={(e) => setNewRoomPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
placeholder="Room name" placeholder="PIN (optional)"
inputMode="numeric"
className="w-32"
/> />
<Button type="submit">Start</Button> </div>
<label className="flex items-center gap-2 text-sm text-on-surface-variant">
<input type="checkbox" checked={tieToLocation} onChange={(e) => setTieToLocation(e.target.checked)} />
Tie to a real-world location (lets others find it on the map)
</label>
{tieToLocation && <LocationPicker latitude={newLat} longitude={newLon} onChange={(lat, lon) => { setNewLat(lat); setNewLon(lon) }} />}
<Button type="submit" className="w-full">
Start
</Button>
</form> </form>
<form onSubmit={handleJoinByCode} className="mb-4 flex gap-2">
<Input
value={joinCode}
onChange={(e) => setJoinCode(e.target.value.toUpperCase())}
placeholder="Join by invite code"
/>
<Button type="submit" variant="secondary" disabled={!joinCode.trim()}>
Join
</Button>
</form>
{joinError && !pendingJoin && <p className="mb-4 text-sm text-error">{joinError}</p>}
<div className="mb-4 flex items-center justify-between">
<h2 className="text-sm font-semibold text-on-surface">Active rooms</h2>
<Button variant="ghost" size="sm" onClick={startNearbySearch} className="gap-1.5">
<MapPin size={14} strokeWidth={2} />
Near me
</Button>
</div>
{showNearby && (
<div className="mb-4">
{nearbyStatus === 'locating' && <p className="text-sm text-on-surface-variant">Finding your location…</p>}
{nearbyStatus === 'error' && <p className="text-sm text-error">{nearbyError}</p>}
{nearbyStatus === 'ready' && nearbyRooms.length === 0 && (
<p className="text-sm text-on-surface-variant">No rooms tied to a location nearby.</p>
)}
{nearbyStatus === 'ready' && nearbyRooms.length > 0 && (
<RoomsNearbyMap
userLocation={{ lat: nearbyRooms[0].room.latitude!, lon: nearbyRooms[0].room.longitude! }}
rooms={nearbyRooms}
onSelectRoom={handlePickRoom}
/>
)}
</div>
)}
{!loading && rooms.length === 0 && ( {!loading && rooms.length === 0 && (
<EmptyState icon={Radio} message="No active rooms right now - start one to get the aux passing." /> <EmptyState icon={Radio} message="No active rooms right now - start one to get the aux passing." />
)} )}
...@@ -52,7 +256,7 @@ export function Rooms() { ...@@ -52,7 +256,7 @@ export function Rooms() {
{rooms.map((room) => ( {rooms.map((room) => (
<li key={room.id}> <li key={room.id}>
<button <button
onClick={() => setActiveRoomId(room.id)} onClick={() => handlePickRoom(room)}
className="flex min-h-[52px] w-full items-center justify-between gap-3 rounded-lg border border-outline-variant bg-surface-container px-4 py-3 text-left transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/70" className="flex min-h-[52px] w-full items-center justify-between gap-3 rounded-lg border border-outline-variant bg-surface-container px-4 py-3 text-left transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/70"
> >
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
...@@ -61,7 +265,10 @@ export function Rooms() { ...@@ -61,7 +265,10 @@ export function Rooms() {
<span className="relative inline-flex h-2 w-2 rounded-full bg-primary" /> <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />
</span> </span>
<div> <div>
<p className="font-medium text-on-surface">{room.name}</p> <p className="flex items-center gap-1.5 font-medium text-on-surface">
{room.name}
{room.has_pin && <Lock size={12} strokeWidth={2} className="text-on-surface-variant" />}
</p>
<p className="text-xs text-outline">DJ #{room.dj_id}</p> <p className="text-xs text-outline">DJ #{room.dj_id}</p>
</div> </div>
</div> </div>
......
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