Commit 558c6513 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Redesign GeoDrops into live location sharing (was: one-off song pins)

Replaces the "drop a specific song at this exact point, once" model
with a live broadcast: share your position and whatever you're
currently playing, updated automatically as you move or switch songs,
visible to anyone nearby while you're sharing. Matches the backend's
GeoDrop -> LiveLocation redesign.

- "Share my live location" toggle: starts watchPosition, pushes an
  update on every meaningful location/song change, plus a periodic
  heartbeat (keeps the row from expiring server-side while nothing's
  changed) - matching the backend's staleness-expiry approach, since a
  closing tab can't reliably notify the server with an authenticated
  request on unload.
- Nearby list now live-updates on a short poll, not just on demand.
- New: "Play my geo playlist" - shuffles everyone nearby's current song
  into the shared player's queue (Fisher-Yates, not the common biased
  Array.sort(() => Math.random() - 0.5) shuffle) and starts playing.
- Only broadcasts a song when it's a real LibrarySong reference
  (Soundmarks/Rooms/Posts-sourced playback uses synthetic negative ids
  for player identity, not something safe to send as song_id).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent dd72364f
Pipeline #1078 failed with stage
...@@ -57,35 +57,48 @@ export async function fetchPostStreamUrl(postId: number): Promise<string> { ...@@ -57,35 +57,48 @@ export async function fetchPostStreamUrl(postId: number): Promise<string> {
return URL.createObjectURL(blob) return URL.createObjectURL(blob)
} }
export interface GeoDrop { export interface LiveListener {
id: number
user_id: number user_id: number
username: string | null username: string | null
/** Null if they're sharing their location but not currently playing anything. */
song: SocialSong | null song: SocialSong | null
latitude: number latitude: number
longitude: number longitude: number
dropped_at: string updated_at: string
} }
export function createGeoDrop(songId: number, latitude: number, longitude: number) { /** Upserts the caller's live position and what they're currently playing - call this on every
return apiFetch<GeoDrop>('/social/geo-drop', { * meaningful location/song change, plus periodically as a heartbeat, while sharing is on.
method: 'POST', * songId is only meaningful when it's a real LibrarySong id (playback sourced from Soundmarks/
json: { song_id: songId, latitude, longitude }, * Rooms/Posts/other live locations uses synthetic negative ids for player identity, not a real
* library reference - pass null for those instead of a bogus id). */
export function shareLiveLocation(latitude: number, longitude: number, songId: number | null) {
return apiFetch<LiveListener>('/social/live-location', {
method: 'PUT',
json: { latitude, longitude, song_id: songId },
}) })
} }
export function getNearbyDrops(lat: number, lon: number, radiusKm = 5) { export function stopSharingLiveLocation() {
return apiFetch<{ drop: GeoDrop; distance_km: number }[]>( return apiFetch<{ status: string }>('/social/live-location', { method: 'DELETE' })
`/social/geo-drop/nearby?lat=${lat}&lon=${lon}&radius_km=${radiusKm}`, }
/** Other nearby users currently sharing their location, self-excluded, sorted by distance.
* Anyone who's gone quiet for a while (closed the tab, lost connection) drops out on their
* own server-side - see LIVE_LOCATION_STALE_AFTER in the backend. */
export function getNearbyLiveListeners(lat: number, lon: number, radiusKm = 5) {
return apiFetch<{ listener: LiveListener; distance_km: number }[]>(
`/social/live-location/nearby?lat=${lat}&lon=${lon}&radius_km=${radiusKm}`,
) )
} }
/** For PlayerContext's `streamUrl` override - fetches a dropped song as an authenticated blob, /** For PlayerContext's `streamUrl` override - fetches whatever a nearby user is currently
* regardless of who uploaded it (mirrors fetchRoomStreamUrl/fetchSoundmarkStreamUrl against the * playing as an authenticated blob, regardless of who uploaded it (mirrors
* analogous drop-scoped endpoint). Caller is responsible for calling URL.revokeObjectURL(). */ * fetchRoomStreamUrl/fetchSoundmarkStreamUrl against the analogous endpoint). Caller is
export async function fetchGeoDropStreamUrl(dropId: number): Promise<string> { * responsible for calling URL.revokeObjectURL(). */
export async function fetchLiveLocationStreamUrl(userId: number): Promise<string> {
const token = getAccessToken() const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/geo-drop/${dropId}/stream`, { const res = await fetch(`${API_BASE_URL}/social/live-location/${userId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined, headers: token ? { Authorization: `Bearer ${token}` } : undefined,
}) })
if (!res.ok) { if (!res.ok) {
......
...@@ -4,23 +4,33 @@ import { MemoryRouter } from 'react-router-dom' ...@@ -4,23 +4,33 @@ import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { GeoDrops } from './GeoDrops' import { GeoDrops } from './GeoDrops'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider, usePlayer } from '../context/PlayerContext'
import * as socialApi from '../api/social' import * as socialApi from '../api/social'
import * as libraryApi from '../api/library'
const NEARBY_DROP: { drop: socialApi.GeoDrop; distance_km: number } = { const LISTENER_A: { listener: socialApi.LiveListener; distance_km: number } = {
drop: { listener: {
id: 1,
user_id: 5, user_id: 5,
username: 'someone', username: 'someone',
song: { id: 42, title: 'Dropped Anthem', artist: 'Local Band', album: null, coverart: null }, song: { id: 42, title: 'Their Track', artist: 'Local Band', album: null, coverart: null },
latitude: 37.7749, latitude: 37.7749,
longitude: -122.4194, longitude: -122.4194,
dropped_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
}, },
distance_km: 0.12, distance_km: 0.12,
} }
const LISTENER_NO_SONG: { listener: socialApi.LiveListener; distance_km: number } = {
listener: {
user_id: 6,
username: 'quiet-one',
song: null,
latitude: 37.7749,
longitude: -122.4194,
updated_at: '2026-01-01T00:00:00Z',
},
distance_km: 0.5,
}
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) { function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition
const geolocation = { const geolocation = {
...@@ -47,7 +57,36 @@ function renderGeoDrops() { ...@@ -47,7 +57,36 @@ function renderGeoDrops() {
) )
} }
describe('GeoDrops', () => { /** Pre-loads a "currently playing" real library song into the shared player before GeoDrops
* mounts, to test that sharing broadcasts whatever's already playing. */
function StartWithSongPlaying() {
const { toggle } = usePlayer()
return (
<button
data-testid="start-playing"
onClick={() =>
toggle({ id: 99, title: 'Already Playing', artist: 'Me', album: null, coverart: null, streamUrl: async () => 'blob:pre' })
}
>
start
</button>
)
}
function renderGeoDropsWithSongAlreadyPlaying() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<StartWithSongPlaying />
<GeoDrops />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('GeoDrops (live location)', () => {
beforeEach(() => { beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '') vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '') vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
...@@ -62,37 +101,48 @@ describe('GeoDrops', () => { ...@@ -62,37 +101,48 @@ describe('GeoDrops', () => {
it('shows a prompt before location has been requested', () => { it('shows a prompt before location has been requested', () => {
renderGeoDrops() renderGeoDrops()
expect(screen.getByRole('button', { name: 'Find drops near me' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Find nearby listeners' })).toBeInTheDocument()
}) })
it('finds and displays a nearby drop with its distance and who dropped it', async () => { it('finds and displays a nearby listener with distance and who they are', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([NEARBY_DROP]) vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_A])
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await waitFor(() => expect(screen.getByText('Dropped Anthem')).toBeInTheDocument()) await waitFor(() => expect(screen.getByText('Their Track')).toBeInTheDocument())
expect(screen.getByText('Local Band')).toBeInTheDocument() expect(screen.getByText('Local Band')).toBeInTheDocument()
expect(screen.getByText(/120m away · dropped by someone/)).toBeInTheDocument() expect(screen.getByText(/120m away · someone/)).toBeInTheDocument()
expect(socialApi.getNearbyDrops).toHaveBeenCalledWith(37.7749, -122.4194) expect(socialApi.getNearbyLiveListeners).toHaveBeenCalledWith(37.7749, -122.4194)
})
it('shows a listener sharing location but not playing anything', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_NO_SONG])
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
expect(await screen.findByText('quiet-one')).toBeInTheDocument()
expect(screen.getByText(/not playing anything/)).toBeInTheDocument()
}) })
it('shows an empty state when no drops are nearby', async () => { it('shows an empty state when no one nearby is sharing', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([]) vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([])
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
expect(await screen.findByText(/No drops nearby yet/)).toBeInTheDocument() expect(await screen.findByText(/No one nearby is sharing/)).toBeInTheDocument()
}) })
it('shows a clear message when location permission is denied', async () => { it('shows a clear message when location permission is denied', async () => {
mockGeolocation({ succeed: false, code: 1 }) mockGeolocation({ succeed: false, code: 1 })
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument() expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
...@@ -103,73 +153,111 @@ describe('GeoDrops', () => { ...@@ -103,73 +153,111 @@ describe('GeoDrops', () => {
const geolocation = mockGeolocation({ succeed: true }) const geolocation = mockGeolocation({ succeed: true })
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
expect(await screen.findByText(/requires a secure \(https:\/\/\) connection/)).toBeInTheDocument() expect(await screen.findByText(/requires a secure \(https:\/\/\) connection/)).toBeInTheDocument()
expect(geolocation.getCurrentPosition).not.toHaveBeenCalled() expect(geolocation.getCurrentPosition).not.toHaveBeenCalled()
}) })
it('drops a song via the song picker and refreshes the nearby list', async () => { it('shares live location with no song when nothing is playing', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([])
const share = vi.spyOn(socialApi, 'shareLiveLocation').mockResolvedValue({
user_id: 1, username: 'me', song: null, latitude: 37.7749, longitude: -122.4194, updated_at: '2026-01-01T00:00:00Z',
})
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText(/No one nearby is sharing/)
await userEvent.click(screen.getByRole('button', { name: 'Share my live location' }))
await waitFor(() => expect(share).toHaveBeenCalledWith(37.7749, -122.4194, null))
expect(screen.getByRole('button', { name: 'Stop sharing' })).toBeInTheDocument()
expect(screen.getByText(/no song right now/)).toBeInTheDocument()
})
it('shares whatever real library song is already playing', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
const getNearbyDrops = vi.spyOn(socialApi, 'getNearbyDrops') vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([])
getNearbyDrops.mockResolvedValueOnce([]) const share = vi.spyOn(socialApi, 'shareLiveLocation').mockResolvedValue({
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ user_id: 1, username: 'me', song: null, latitude: 37.7749, longitude: -122.4194, updated_at: '2026-01-01T00:00:00Z',
status: 'success',
library: [
{
id: 55,
user_id: 1,
title: 'My Track',
artist: 'Me',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
},
],
}) })
const create = vi.spyOn(socialApi, 'createGeoDrop').mockResolvedValue({
id: 2, renderGeoDropsWithSongAlreadyPlaying()
user_id: 1, await userEvent.click(screen.getByTestId('start-playing'))
username: 'me', await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
song: { id: 55, title: 'My Track', artist: 'Me', album: null, coverart: null }, await screen.findByRole('button', { name: 'Share my live location' })
latitude: 37.7749,
longitude: -122.4194, await userEvent.click(screen.getByRole('button', { name: 'Share my live location' }))
dropped_at: '2026-01-01T00:00:00Z',
await waitFor(() => expect(share).toHaveBeenCalledWith(37.7749, -122.4194, 99))
expect(screen.getByText(/"Already Playing"/)).toBeInTheDocument()
})
it('stops sharing', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([])
vi.spyOn(socialApi, 'shareLiveLocation').mockResolvedValue({
user_id: 1, username: 'me', song: null, latitude: 37.7749, longitude: -122.4194, updated_at: '2026-01-01T00:00:00Z',
}) })
getNearbyDrops.mockResolvedValueOnce([ const stop = vi.spyOn(socialApi, 'stopSharingLiveLocation').mockResolvedValue({ status: 'ok' })
{ drop: { id: 2, user_id: 1, username: 'me', song: { id: 55, title: 'My Track', artist: 'Me', album: null, coverart: null }, latitude: 37.7749, longitude: -122.4194, dropped_at: '2026-01-01T00:00:00Z' }, distance_km: 0 },
])
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText(/No drops nearby yet/) await screen.findByRole('button', { name: 'Share my live location' })
await userEvent.click(screen.getByRole('button', { name: 'Share my live location' }))
await screen.findByRole('button', { name: 'Stop sharing' })
await userEvent.click(screen.getByRole('button', { name: 'Drop a song here' })) await userEvent.click(screen.getByRole('button', { name: 'Stop sharing' }))
await userEvent.click(await screen.findByText('My Track'))
await waitFor(() => expect(create).toHaveBeenCalledWith(55, 37.7749, -122.4194)) expect(stop).toHaveBeenCalled()
expect(await screen.findByText('My Track')).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Share my live location' })).toBeInTheDocument()
}) })
it('plays a nearby drop through the shared player when tapped', async () => { it('plays a nearby listener through the shared player when tapped', async () => {
mockGeolocation({ succeed: true }) mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([NEARBY_DROP]) vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_A])
vi.spyOn(socialApi, 'fetchGeoDropStreamUrl').mockResolvedValue('blob:fake-url') vi.spyOn(socialApi, 'fetchLiveLocationStreamUrl').mockResolvedValue('blob:fake-url')
renderGeoDrops() renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' })) await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await waitFor(() => expect(screen.getByText('Dropped Anthem')).toBeInTheDocument()) await waitFor(() => expect(screen.getByText('Their Track')).toBeInTheDocument())
await userEvent.click(screen.getByRole('button', { name: 'Play' })) await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => { await waitFor(() => {
expect(socialApi.fetchGeoDropStreamUrl).toHaveBeenCalledWith(NEARBY_DROP.drop.id) expect(socialApi.fetchLiveLocationStreamUrl).toHaveBeenCalledWith(LISTENER_A.listener.user_id)
})
const card = screen.getByText(/120m away/).closest('li')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('disables the geo playlist button when no one nearby has a song', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_NO_SONG])
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText('quiet-one')
expect(screen.getByRole('button', { name: /Play my geo playlist/ })).toBeDisabled()
})
it('shuffles nearby songs into a queue and starts playing on "Play my geo playlist"', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_A])
vi.spyOn(socialApi, 'fetchLiveLocationStreamUrl').mockResolvedValue('blob:fake-url')
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText('Their Track')
await userEvent.click(screen.getByRole('button', { name: /Play my geo playlist/ }))
await waitFor(() => {
expect(socialApi.fetchLiveLocationStreamUrl).toHaveBeenCalledWith(LISTENER_A.listener.user_id)
}) })
// NowPlayingBar duplicates the song title once playback starts, so scope via the
// distance text instead (unique to this list item) to disambiguate the two Pause buttons.
const card = screen.getByText(/120m away/).closest('li')! const card = screen.getByText(/120m away/).closest('li')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument() expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
}) })
......
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { MapPinned, Music2, Pause, Play, Plus } from 'lucide-react' import { MapPinned, Music2, Pause, Play, Radio, Shuffle } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
import { SongPicker } from '../components/SongPicker'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { createGeoDrop, fetchGeoDropStreamUrl, getNearbyDrops, type GeoDrop } from '../api/social' import {
fetchLiveLocationStreamUrl,
getNearbyLiveListeners,
shareLiveLocation,
stopSharingLiveLocation,
type LiveListener,
} from '../api/social'
import { usePlayer } from '../context/PlayerContext' import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error' type Status = 'idle' | 'locating' | 'ready' | 'error'
type NearbyDrop = { drop: GeoDrop; distance_km: number } type NearbyListener = { listener: LiveListener; distance_km: number }
const HEARTBEAT_MS = 30_000
const NEARBY_REFRESH_MS = 15_000
function formatDistance(km: number): string { function formatDistance(km: number): string {
return km < 1 ? `${Math.round(km * 1000)}m away` : `${km.toFixed(1)}km away` return km < 1 ? `${Math.round(km * 1000)}m away` : `${km.toFixed(1)}km away`
} }
function toPlayable(drop: GeoDrop) { function toPlayable(listener: LiveListener) {
return { return {
// Negative to avoid colliding with a real LibrarySong id - see PlayableSong's `streamUrl` // Negative and keyed by user_id, not a real LibrarySong id - see PlayableSong's
// doc (same convention Nearby/RoomView use for their own not-a-real-library-song ids). // `streamUrl` doc (same convention every other social feature's play button uses).
id: -drop.id, id: -listener.user_id,
title: drop.song!.title, title: listener.song!.title,
artist: drop.song!.artist, artist: listener.song!.artist,
album: drop.song!.album, album: listener.song!.album,
coverart: drop.song!.coverart, coverart: listener.song!.coverart,
streamUrl: () => fetchGeoDropStreamUrl(drop.id), streamUrl: () => fetchLiveLocationStreamUrl(listener.user_id),
}
}
/** Fisher-Yates - Array.sort(() => Math.random() - 0.5) is a well-known biased shuffle, this
* isn't (every permutation is genuinely equally likely). */
function shuffle<T>(items: T[]): T[] {
const result = [...items]
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[result[i], result[j]] = [result[j], result[i]]
} }
return result
} }
export function GeoDrops() { export function GeoDrops() {
const [status, setStatus] = useState<Status>('idle') const [status, setStatus] = useState<Status>('idle')
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [drops, setDrops] = useState<NearbyDrop[]>([]) const [nearby, setNearby] = useState<NearbyListener[]>([])
const [userLocation, setUserLocation] = useState<{ lat: number; lon: number } | null>(null) const [sharing, setSharing] = useState(false)
const [showSongPicker, setShowSongPicker] = useState(false)
const [dropping, setDropping] = useState(false)
const watchIdRef = useRef<number | null>(null) const watchIdRef = useRef<number | null>(null)
const heartbeatRef = useRef<ReturnType<typeof setInterval> | null>(null)
const nearbyRefreshRef = useRef<ReturnType<typeof setInterval> | null>(null)
// Refs mirror the state above so callbacks registered once (watchPosition, setInterval)
// always see the latest values instead of the stale ones captured when they were created.
const sharingRef = useRef(false)
const positionRef = useRef<{ lat: number; lon: number } | null>(null)
const currentSongIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function refreshNearby(loc: { lat: number; lon: number }) {
getNearbyLiveListeners(loc.lat, loc.lon)
.then(setNearby)
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby listeners'))
}
function pushPresence() {
const pos = positionRef.current
if (!pos) return
shareLiveLocation(pos.lat, pos.lon, currentSongIdRef.current).catch(() => {})
}
function handlePosition(position: GeolocationPosition) { function handlePosition(position: GeolocationPosition) {
setStatus('ready') setStatus('ready')
setError(null) setError(null)
const loc = { lat: position.coords.latitude, lon: position.coords.longitude } const loc = { lat: position.coords.latitude, lon: position.coords.longitude }
setUserLocation(loc) positionRef.current = loc
getNearbyDrops(loc.lat, loc.lon) refreshNearby(loc)
.then(setDrops) if (sharingRef.current) pushPresence()
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby drops'))
} }
function handlePositionError(err: GeolocationPositionError) { function handlePositionError(err: GeolocationPositionError) {
setStatus('error') setStatus('error')
setError( setError(
err.code === err.PERMISSION_DENIED err.code === err.PERMISSION_DENIED
? 'Location access was denied - allow it in your browser settings to find drops near you.' ? 'Location access was denied - allow it in your browser settings to find listeners near you.'
: "Couldn't determine your location. Please try again.", : "Couldn't determine your location. Please try again.",
) )
} }
...@@ -83,39 +118,74 @@ export function GeoDrops() { ...@@ -83,39 +118,74 @@ export function GeoDrops() {
}) })
} }
// Keeps the "what am I currently playing" ref in sync, and - the actual point of "as they
// switch songs, will also switch" - pushes an update immediately on every song change while
// sharing, rather than waiting for the next GPS fix or heartbeat.
useEffect(() => {
// Playback sourced from Soundmarks/Rooms/Posts/other live locations uses a synthetic
// negative id for player identity, not a real LibrarySong reference - only a positive id
// is safe to broadcast as "the song I'm playing."
currentSongIdRef.current = currentSong && currentSong.id > 0 ? currentSong.id : null
if (sharingRef.current) pushPresence()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentSong])
useEffect(() => { useEffect(() => {
sharingRef.current = sharing
if (nearbyRefreshRef.current) clearInterval(nearbyRefreshRef.current)
if (status === 'ready') {
nearbyRefreshRef.current = setInterval(() => {
if (positionRef.current) refreshNearby(positionRef.current)
}, NEARBY_REFRESH_MS)
}
return () => { return () => {
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current) if (nearbyRefreshRef.current) clearInterval(nearbyRefreshRef.current)
} }
}, []) // eslint-disable-next-line react-hooks/exhaustive-deps
}, [status, sharing])
async function handleDrop(song: { id: number }) { function toggleSharing() {
if (!userLocation) return if (sharing) {
setShowSongPicker(false) setSharing(false)
setDropping(true) if (heartbeatRef.current) clearInterval(heartbeatRef.current)
try { stopSharingLiveLocation().catch(() => {})
await createGeoDrop(song.id, userLocation.lat, userLocation.lon) } else {
const refreshed = await getNearbyDrops(userLocation.lat, userLocation.lon) setSharing(true)
setDrops(refreshed) pushPresence()
} catch (err) { heartbeatRef.current = setInterval(pushPresence, HEARTBEAT_MS)
setError(err instanceof ApiError ? err.message : 'Failed to drop that song')
} finally {
setDropping(false)
} }
} }
function playGeoPlaylist() {
const playable = shuffle(nearby.filter((n) => n.listener.song)).map((n) => toPlayable(n.listener))
if (playable.length === 0) return
toggle(playable[0], playable)
}
useEffect(() => {
return () => {
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
if (heartbeatRef.current) clearInterval(heartbeatRef.current)
if (nearbyRefreshRef.current) clearInterval(nearbyRefreshRef.current)
if (sharingRef.current) stopSharingLiveLocation().catch(() => {})
}
}, [])
const canPlayPlaylist = nearby.some((n) => n.listener.song)
return ( return (
<Layout title="Drops"> <Layout title="Live Nearby">
<p className="mb-6 text-sm leading-relaxed text-neutral-400"> <p className="mb-6 text-sm leading-relaxed text-neutral-400">
Drop a song at exactly where you're standing for someone else to stumble on later - a one-off pin, Share your live location and whatever you're currently playing - as you switch songs, so does what
not tied to a place like Soundmarks. Anyone nearby can find and play it. people nearby see. Or just browse: play a shuffled mix of what everyone around you is listening to
right now.
</p> </p>
{status === 'idle' && ( {status === 'idle' && (
<div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-neutral-700 p-10 text-center"> <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-neutral-700 p-10 text-center">
<MapPinned size={28} strokeWidth={1.5} className="text-neutral-500" /> <MapPinned size={28} strokeWidth={1.5} className="text-neutral-500" />
<p className="text-sm text-neutral-400">Use your location to find and leave drops near you.</p> <p className="text-sm text-neutral-400">Use your location to find live listeners near you.</p>
<Button onClick={start}>Find drops near me</Button> <Button onClick={start}>Find nearby listeners</Button>
</div> </div>
)} )}
...@@ -140,23 +210,40 @@ export function GeoDrops() { ...@@ -140,23 +210,40 @@ export function GeoDrops() {
{status === 'ready' && ( {status === 'ready' && (
<> <>
<Button onClick={() => setShowSongPicker(true)} disabled={dropping} className="mb-4 gap-1.5"> <div className="mb-4 flex flex-wrap items-center gap-2">
<Plus size={16} strokeWidth={2.5} /> <Button
{dropping ? 'Dropping…' : 'Drop a song here'} variant={sharing ? 'secondary' : 'primary'}
</Button> onClick={toggleSharing}
className="gap-1.5"
aria-pressed={sharing}
>
<Radio size={16} strokeWidth={2} className={sharing ? 'text-emerald-400' : ''} />
{sharing ? 'Stop sharing' : 'Share my live location'}
</Button>
<Button variant="secondary" onClick={playGeoPlaylist} disabled={!canPlayPlaylist} className="gap-1.5">
<Shuffle size={16} strokeWidth={2} />
Play my geo playlist
</Button>
</div>
{sharing && (
<p className="mb-4 text-xs text-neutral-500">
Sharing live · broadcasting{' '}
{currentSong && currentSong.id > 0 ? `"${currentSong.title}"` : 'no song right now'}
</p>
)}
{error && <p className="mb-4 text-sm text-red-400">{error}</p>} {error && <p className="mb-4 text-sm text-red-400">{error}</p>}
{drops.length === 0 && ( {nearby.length === 0 && (
<EmptyState icon={MapPinned} message="No drops nearby yet - be the first to leave one." /> <EmptyState icon={MapPinned} message="No one nearby is sharing their location right now." />
)} )}
<ul className="space-y-2"> <ul className="space-y-2">
{drops.map(({ drop, distance_km }) => { {nearby.map(({ listener, distance_km }) => {
const active = drop.song ? toPlayable(drop) : null const active = listener.song ? toPlayable(listener) : null
const isCurrent = !!active && currentSong?.id === active.id const isCurrent = !!active && currentSong?.id === active.id
return ( return (
<li key={drop.id} className="rounded-xl border border-neutral-800 bg-neutral-900 p-3"> <li key={listener.user_id} className="rounded-xl border border-neutral-800 bg-neutral-900 p-3">
{active ? ( {active ? (
<button <button
onClick={() => toggle(active)} onClick={() => toggle(active)}
...@@ -164,18 +251,18 @@ export function GeoDrops() { ...@@ -164,18 +251,18 @@ export function GeoDrops() {
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'} aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex w-full items-center gap-3 rounded-lg p-1 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed" className="flex w-full items-center gap-3 rounded-lg p-1 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
> >
{drop.song!.coverart ? ( {listener.song!.coverart ? (
<img src={drop.song!.coverart} alt="" className="h-12 w-12 shrink-0 rounded-lg object-cover" /> <img src={listener.song!.coverart} alt="" className="h-12 w-12 shrink-0 rounded-lg object-cover" />
) : ( ) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600"> <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} /> <Music2 size={18} strokeWidth={1.75} />
</div> </div>
)} )}
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{drop.song!.title}</p> <p className="truncate text-sm font-medium text-white">{listener.song!.title}</p>
<p className="truncate text-xs text-neutral-400">{drop.song!.artist}</p> <p className="truncate text-xs text-neutral-400">{listener.song!.artist}</p>
<p className="mt-0.5 text-xs text-neutral-500"> <p className="mt-0.5 text-xs text-neutral-500">
{formatDistance(distance_km)} · dropped by {drop.username ?? `user #${drop.user_id}`} {formatDistance(distance_km)} · {listener.username ?? `user #${listener.user_id}`}
</p> </p>
</div> </div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white"> <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
...@@ -189,7 +276,15 @@ export function GeoDrops() { ...@@ -189,7 +276,15 @@ export function GeoDrops() {
</span> </span>
</button> </button>
) : ( ) : (
<p className="p-1 text-sm text-neutral-500">A dropped song is no longer available.</p> <div className="flex items-center gap-3 p-1">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
<div className="min-w-0 flex-1">
<p className="text-sm text-neutral-400">{listener.username ?? `user #${listener.user_id}`}</p>
<p className="text-xs text-neutral-500">{formatDistance(distance_km)} · not playing anything</p>
</div>
</div>
)} )}
</li> </li>
) )
...@@ -197,8 +292,6 @@ export function GeoDrops() { ...@@ -197,8 +292,6 @@ export function GeoDrops() {
</ul> </ul>
</> </>
)} )}
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handleDrop} />}
</Layout> </Layout>
) )
} }
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