Commit 93237997 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add GeoDrops: build a UI for the previously-unused drop-a-song feature

GeoDrop had full backend support but zero UI anywhere - like a StreetPass
drop, not a Soundmark: a one-off song pin left at your exact GPS
position, no owner, no moderation, no persistent place to attach to
(distinct from Soundmarks' community tier, which is about a named,
persistent location accumulating votes over time).

New page at /drops: request geolocation (same pattern as Nearby), drop
a song at your exact position via the existing SongPicker, and see/play
nearby drops sorted by distance through the shared player.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent d9a22bf3
Pipeline #1074 canceled with stage
...@@ -4,6 +4,7 @@ import { Upload } from './pages/Upload' ...@@ -4,6 +4,7 @@ import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery' import { Discovery } from './pages/Discovery'
import { Rooms } from './pages/Rooms' import { Rooms } from './pages/Rooms'
import { Channels } from './pages/Channels' import { Channels } from './pages/Channels'
import { GeoDrops } from './pages/GeoDrops'
import { Remix } from './pages/Remix' import { Remix } from './pages/Remix'
import { Nearby } from './pages/Nearby' import { Nearby } from './pages/Nearby'
import { BusinessPanel } from './pages/BusinessPanel' import { BusinessPanel } from './pages/BusinessPanel'
...@@ -23,6 +24,7 @@ export function App() { ...@@ -23,6 +24,7 @@ export function App() {
<Route path="/discovery" element={protect(<Discovery />)} /> <Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/rooms" element={protect(<Rooms />)} /> <Route path="/rooms" element={protect(<Rooms />)} />
<Route path="/channels" element={protect(<Channels />)} /> <Route path="/channels" element={protect(<Channels />)} />
<Route path="/drops" element={protect(<GeoDrops />)} />
<Route path="/remix" element={protect(<Remix />)} /> <Route path="/remix" element={protect(<Remix />)} />
<Route path="/nearby" element={protect(<Nearby />)} /> <Route path="/nearby" element={protect(<Nearby />)} />
<Route <Route
......
import { API_BASE_URL, apiFetch, getAccessToken } from './client' import { API_BASE_URL, apiFetch, getAccessToken } from './client'
export interface SocialSong {
id: number
title: string
artist: string
album: string | null
coverart: string | null
}
export interface Post { export interface Post {
id: number id: number
user_id: number user_id: number
song_id: number username: string | null
song: SocialSong | null
parent_post_id: number | null parent_post_id: number | null
caption: string caption: string
created_at: string created_at: string
/** Only present on entries from listPosts() - how many remixes this post has. */
remix_count?: number
} }
export interface PostTree { export interface PostTree {
...@@ -14,6 +25,12 @@ export interface PostTree { ...@@ -14,6 +25,12 @@ export interface PostTree {
children: PostTree[] children: PostTree[]
} }
/** Recent top-level posts (not remixes - those show up nested under their parent via
* getPostTree instead of cluttering the main feed). */
export function listPosts() {
return apiFetch<Post[]>('/social/posts')
}
export function createPost(songId: number, caption: string, parentPostId?: number) { export function createPost(songId: number, caption: string, parentPostId?: number) {
return apiFetch<Post>('/social/posts', { return apiFetch<Post>('/social/posts', {
method: 'POST', method: 'POST',
...@@ -28,7 +45,8 @@ export function getPostTree(postId: number) { ...@@ -28,7 +45,8 @@ export function getPostTree(postId: number) {
export interface GeoDrop { export interface GeoDrop {
id: number id: number
user_id: number user_id: number
song_id: number username: string | null
song: SocialSong | null
latitude: number latitude: number
longitude: number longitude: number
dropped_at: string dropped_at: string
...@@ -47,6 +65,21 @@ export function getNearbyDrops(lat: number, lon: number, radiusKm = 5) { ...@@ -47,6 +65,21 @@ export function getNearbyDrops(lat: number, lon: number, radiusKm = 5) {
) )
} }
/** For PlayerContext's `streamUrl` override - fetches a dropped song as an authenticated blob,
* regardless of who uploaded it (mirrors fetchRoomStreamUrl/fetchSoundmarkStreamUrl against the
* analogous drop-scoped endpoint). Caller is responsible for calling URL.revokeObjectURL(). */
export async function fetchGeoDropStreamUrl(dropId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/geo-drop/${dropId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
}
export interface LiveRoom { export interface LiveRoom {
id: number id: number
dj_id: number dj_id: number
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
Library, Library,
LogOut, LogOut,
MapPin, MapPin,
MapPinned,
Radio, Radio,
Rss, Rss,
ShieldCheck, ShieldCheck,
...@@ -29,6 +30,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [ ...@@ -29,6 +30,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/channels', label: 'Channels', icon: Rss }, { to: '/channels', label: 'Channels', icon: Rss },
{ to: '/remix', label: 'Remix', icon: Wand2 }, { to: '/remix', label: 'Remix', icon: Wand2 },
{ to: '/nearby', label: 'Soundmarks', icon: MapPin }, { to: '/nearby', label: 'Soundmarks', icon: MapPin },
{ to: '/drops', label: 'Drops', icon: MapPinned },
] ]
export function Layout({ title, children }: { title: string; children: ReactNode }) { export function Layout({ title, children }: { title: string; children: ReactNode }) {
......
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { GeoDrops } from './GeoDrops'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as socialApi from '../api/social'
import * as libraryApi from '../api/library'
const NEARBY_DROP: { drop: socialApi.GeoDrop; distance_km: number } = {
drop: {
id: 1,
user_id: 5,
username: 'someone',
song: { id: 42, title: 'Dropped Anthem', artist: 'Local Band', album: null, coverart: null },
latitude: 37.7749,
longitude: -122.4194,
dropped_at: '2026-01-01T00:00:00Z',
},
distance_km: 0.12,
}
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition
const geolocation = {
getCurrentPosition: vi.fn((success: PositionCallback, error?: PositionErrorCallback) => {
if (succeed) success(position)
else error?.({ code, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 } as GeolocationPositionError)
}),
watchPosition: vi.fn(() => 1),
clearWatch: vi.fn(),
}
vi.stubGlobal('navigator', { ...navigator, geolocation })
return geolocation
}
function renderGeoDrops() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<GeoDrops />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('GeoDrops', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.stubGlobal('isSecureContext', true)
})
afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('shows a prompt before location has been requested', () => {
renderGeoDrops()
expect(screen.getByRole('button', { name: 'Find drops near me' })).toBeInTheDocument()
})
it('finds and displays a nearby drop with its distance and who dropped it', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([NEARBY_DROP])
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
await waitFor(() => expect(screen.getByText('Dropped Anthem')).toBeInTheDocument())
expect(screen.getByText('Local Band')).toBeInTheDocument()
expect(screen.getByText(/120m away · dropped by someone/)).toBeInTheDocument()
expect(socialApi.getNearbyDrops).toHaveBeenCalledWith(37.7749, -122.4194)
})
it('shows an empty state when no drops are nearby', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([])
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
expect(await screen.findByText(/No drops nearby yet/)).toBeInTheDocument()
})
it('shows a clear message when location permission is denied', async () => {
mockGeolocation({ succeed: false, code: 1 })
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
})
it('shows a clear, accurate message on an insecure origin', async () => {
vi.stubGlobal('isSecureContext', false)
const geolocation = mockGeolocation({ succeed: true })
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
expect(await screen.findByText(/requires a secure \(https:\/\/\) connection/)).toBeInTheDocument()
expect(geolocation.getCurrentPosition).not.toHaveBeenCalled()
})
it('drops a song via the song picker and refreshes the nearby list', async () => {
mockGeolocation({ succeed: true })
const getNearbyDrops = vi.spyOn(socialApi, 'getNearbyDrops')
getNearbyDrops.mockResolvedValueOnce([])
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
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,
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',
})
getNearbyDrops.mockResolvedValueOnce([
{ 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()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
await screen.findByText(/No drops nearby yet/)
await userEvent.click(screen.getByRole('button', { name: 'Drop a song here' }))
await userEvent.click(await screen.findByText('My Track'))
await waitFor(() => expect(create).toHaveBeenCalledWith(55, 37.7749, -122.4194))
expect(await screen.findByText('My Track')).toBeInTheDocument()
})
it('plays a nearby drop through the shared player when tapped', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyDrops').mockResolvedValue([NEARBY_DROP])
vi.spyOn(socialApi, 'fetchGeoDropStreamUrl').mockResolvedValue('blob:fake-url')
renderGeoDrops()
await userEvent.click(screen.getByRole('button', { name: 'Find drops near me' }))
await waitFor(() => expect(screen.getByText('Dropped Anthem')).toBeInTheDocument())
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(socialApi.fetchGeoDropStreamUrl).toHaveBeenCalledWith(NEARBY_DROP.drop.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')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
})
import { useEffect, useRef, useState } from 'react'
import { MapPinned, Music2, Pause, Play, Plus } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState'
import { SongPicker } from '../components/SongPicker'
import { ApiError } from '../api/client'
import { createGeoDrop, fetchGeoDropStreamUrl, getNearbyDrops, type GeoDrop } from '../api/social'
import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error'
type NearbyDrop = { drop: GeoDrop; distance_km: number }
function formatDistance(km: number): string {
return km < 1 ? `${Math.round(km * 1000)}m away` : `${km.toFixed(1)}km away`
}
function toPlayable(drop: GeoDrop) {
return {
// Negative to avoid colliding with a real LibrarySong id - see PlayableSong's `streamUrl`
// doc (same convention Nearby/RoomView use for their own not-a-real-library-song ids).
id: -drop.id,
title: drop.song!.title,
artist: drop.song!.artist,
album: drop.song!.album,
coverart: drop.song!.coverart,
streamUrl: () => fetchGeoDropStreamUrl(drop.id),
}
}
export function GeoDrops() {
const [status, setStatus] = useState<Status>('idle')
const [error, setError] = useState<string | null>(null)
const [drops, setDrops] = useState<NearbyDrop[]>([])
const [userLocation, setUserLocation] = useState<{ lat: number; lon: number } | null>(null)
const [showSongPicker, setShowSongPicker] = useState(false)
const [dropping, setDropping] = useState(false)
const watchIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function handlePosition(position: GeolocationPosition) {
setStatus('ready')
setError(null)
const loc = { lat: position.coords.latitude, lon: position.coords.longitude }
setUserLocation(loc)
getNearbyDrops(loc.lat, loc.lon)
.then(setDrops)
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby drops'))
}
function handlePositionError(err: GeolocationPositionError) {
setStatus('error')
setError(
err.code === err.PERMISSION_DENIED
? 'Location access was denied - allow it in your browser settings to find drops near you.'
: "Couldn't determine your location. Please try again.",
)
}
function start() {
if (!navigator.geolocation) {
setStatus('error')
setError("Your browser doesn't support location services.")
return
}
// See Nearby.tsx's identical guard - the Geolocation API refuses to run at all on a plain
// http:// origin that isn't localhost, failing with the same code a real user decline
// would, so this fails fast with an accurate reason instead.
if (!window.isSecureContext) {
setStatus('error')
setError('Location access requires a secure (https://) connection - this page was loaded over an insecure one.')
return
}
setStatus('locating')
setError(null)
navigator.geolocation.getCurrentPosition(handlePosition, handlePositionError, {
enableHighAccuracy: true,
timeout: 15000,
})
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
watchIdRef.current = navigator.geolocation.watchPosition(handlePosition, handlePositionError, {
enableHighAccuracy: true,
})
}
useEffect(() => {
return () => {
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
}
}, [])
async function handleDrop(song: { id: number }) {
if (!userLocation) return
setShowSongPicker(false)
setDropping(true)
try {
await createGeoDrop(song.id, userLocation.lat, userLocation.lon)
const refreshed = await getNearbyDrops(userLocation.lat, userLocation.lon)
setDrops(refreshed)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to drop that song')
} finally {
setDropping(false)
}
}
return (
<Layout title="Drops">
<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,
not tied to a place like Soundmarks. Anyone nearby can find and play it.
</p>
{status === 'idle' && (
<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" />
<p className="text-sm text-neutral-400">Use your location to find and leave drops near you.</p>
<Button onClick={start}>Find drops near me</Button>
</div>
)}
{status === 'locating' && (
<div className="flex flex-col items-center gap-3 py-16 text-neutral-500">
<span
className="h-6 w-6 animate-spin rounded-full border-2 border-neutral-700 border-t-emerald-400"
aria-hidden="true"
/>
<p className="text-sm">Getting your location…</p>
</div>
)}
{status === 'error' && (
<div className="rounded-xl border border-red-900/50 bg-neutral-900 p-4">
<p className="text-sm text-red-400">{error}</p>
<Button variant="secondary" size="sm" onClick={start} className="mt-3">
Try again
</Button>
</div>
)}
{status === 'ready' && (
<>
<Button onClick={() => setShowSongPicker(true)} disabled={dropping} className="mb-4 gap-1.5">
<Plus size={16} strokeWidth={2.5} />
{dropping ? 'Dropping…' : 'Drop a song here'}
</Button>
{error && <p className="mb-4 text-sm text-red-400">{error}</p>}
{drops.length === 0 && (
<EmptyState icon={MapPinned} message="No drops nearby yet - be the first to leave one." />
)}
<ul className="space-y-2">
{drops.map(({ drop, distance_km }) => {
const active = drop.song ? toPlayable(drop) : null
const isCurrent = !!active && currentSong?.id === active.id
return (
<li key={drop.id} className="rounded-xl border border-neutral-800 bg-neutral-900 p-3">
{active ? (
<button
onClick={() => toggle(active)}
disabled={isCurrent && streamLoading}
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"
>
{drop.song!.coverart ? (
<img src={drop.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">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{drop.song!.title}</p>
<p className="truncate text-xs text-neutral-400">{drop.song!.artist}</p>
<p className="mt-0.5 text-xs text-neutral-500">
{formatDistance(distance_km)} · dropped by {drop.username ?? `user #${drop.user_id}`}
</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
) : (
<p className="p-1 text-sm text-neutral-500">A dropped song is no longer available.</p>
)}
</li>
)
})}
</ul>
</>
)}
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handleDrop} />}
</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