Commit a7124fc6 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Connect every backend feature area, not just auth + library

Adds Upload (direct file tag), Discovery (listen/history/swipe), Rooms
(list/create + a live WebSocket room view with chat, fire reactions, and
DJ-handoff requests), Channels (list/create/follow, user_id filled in
client-side via jwt.ts since /channels takes it in the body rather than
deriving it from the token like every other router), and Remix (multi-file
upload + prompt, polls job status with a stage progress bar until done).

jwt.ts decodes (never verifies - that's the server's job) the access
token's `sub` claim locally, since /channels needs a real user id and
nothing in the login response returns one directly.

Typechecks clean, production build succeeds.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent c49f36ae
Pipeline #1027 failed with stages
import { Navigate, Route, Routes } from 'react-router-dom'
import { Login } from './pages/Login'
import { Library } from './pages/Library'
import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery'
import { Rooms } from './pages/Rooms'
import { Channels } from './pages/Channels'
import { Remix } from './pages/Remix'
import { ProtectedRoute } from './components/ProtectedRoute'
function protect(element: React.ReactElement) {
return <ProtectedRoute>{element}</ProtectedRoute>
}
export function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/library"
element={
<ProtectedRoute>
<Library />
</ProtectedRoute>
}
/>
<Route path="/library" element={protect(<Library />)} />
<Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/rooms" element={protect(<Rooms />)} />
<Route path="/channels" element={protect(<Channels />)} />
<Route path="/remix" element={protect(<Remix />)} />
<Route path="*" element={<Navigate to="/library" replace />} />
</Routes>
)
......
import { apiFetch } from './client'
// Unlike every other router, /channels takes user_id explicitly in request bodies instead of
// deriving it from the auth token server-side - see getCurrentUserId() in jwt.ts, used by the
// pages calling these to fill it in automatically.
export interface Channel {
id: number
owner_id: number
name: string
description: string | null
avatar_url: string | null
created_at: string
}
export function listChannels() {
return apiFetch<Channel[]>('/channels')
}
export function createChannel(ownerId: number, name: string, description?: string) {
return apiFetch<Channel>('/channels', {
method: 'POST',
json: { owner_id: ownerId, name, description: description ?? null },
})
}
export function getChannel(channelId: number) {
return apiFetch<{ channel: Channel; follower_count: number }>(`/channels/${channelId}`)
}
export function followChannel(channelId: number, userId: number) {
return apiFetch(`/channels/${channelId}/follow`, { method: 'POST', json: { user_id: userId } })
}
export function unfollowChannel(channelId: number, userId: number) {
return apiFetch(`/channels/${channelId}/unfollow`, { method: 'POST', json: { user_id: userId } })
}
export interface VibeSet {
id: number
channel_id: number
title: string
description: string | null
created_at: string
}
export function listVibeSets(channelId: number) {
return apiFetch<VibeSet[]>(`/channels/${channelId}/vibe-sets`)
}
export function createVibeSet(channelId: number, userId: number, title: string, songIds: number[]) {
return apiFetch<VibeSet>(`/channels/${channelId}/vibe-sets`, {
method: 'POST',
json: { user_id: userId, title, song_ids: songIds },
})
}
export interface AudioStory {
id: number
channel_id: number
song_id: number
caption: string | null
created_at: string
expires_at: string
}
export function listStories(channelId: number) {
return apiFetch<AudioStory[]>(`/channels/${channelId}/stories`)
}
export function createStory(channelId: number, userId: number, songId: number, caption?: string) {
return apiFetch<AudioStory>(`/channels/${channelId}/stories`, {
method: 'POST',
json: { user_id: userId, song_id: songId, caption: caption ?? null },
})
}
import { apiFetch, API_BASE_URL, getAccessToken } from './client'
export interface DiscoveredSong {
id: number
user_id: number
title: string
artist: string
genre: string | null
coverart: string | null
detected_at: string
liked: boolean | null
}
export function getDiscoveryHistory() {
return apiFetch<{ status: string; history: DiscoveredSong[] }>('/discovery/history')
}
export function swipe(songId: number, liked: boolean) {
return apiFetch<{ status: string; message: string }>(`/discovery/${songId}/swipe`, {
method: 'POST',
form: { liked },
})
}
/** Multipart upload - apiFetch's json/form helpers don't cover files, so this one builds the
* request directly. */
export async function listen(file: File) {
const token = getAccessToken()
const body = new FormData()
body.append('file', file)
const res = await fetch(`${API_BASE_URL}/discovery/listen`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
body,
})
return res.json() as Promise<
| { status: 'success'; detected: Record<string, unknown>; discovery_id: number }
| { status: 'error'; message: string }
>
}
import { getAccessToken } from './client'
/** Decodes (never verifies - that's the server's job) the access token's payload to read
* the current user id out of the `sub` claim, so screens that need it (channels endpoints
* take user_id in the body instead of deriving it from the token server-side) don't have to
* ask the user to type their own id in. */
export function getCurrentUserId(): number | null {
const token = getAccessToken()
if (!token) return null
try {
const payload = token.split('.')[1]
const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/'))
const decoded = JSON.parse(json) as { sub: string }
return parseInt(decoded.sub, 10)
} catch {
return null
}
}
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
export interface TagMetadata {
library_song_id: number
title: string
artist: string
album: string
genre: string
year: string
has_lyrics: boolean
lyrics: string | null
cover_art: string | null
}
export interface TagResponse {
status: string
download_url: string
metadata: TagMetadata
}
export function tagFromChat(chatId: number, messageId: number, languagePreference: 'native' | 'finglish' = 'native') {
return apiFetch<TagResponse>('/music/tag', {
method: 'POST',
json: { chat_id: chatId, message_id: messageId, language_preference: languagePreference },
})
}
export async function uploadDirect(file: File) {
const token = getAccessToken()
const body = new FormData()
body.append('file', file)
const res = await fetch(`${API_BASE_URL}/music/upload`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
body,
})
if (!res.ok) {
const detail = await res.json().catch(() => null)
throw new Error(detail?.detail ?? `Upload failed (${res.status})`)
}
return res.json() as Promise<TagResponse>
}
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
export interface RemixStatus {
job_id: number
status: 'queued' | 'planning' | 'separating' | 'mixing' | 'mastering' | 'tagging' | 'done' | 'error'
stage_detail: string | null
remix_name: string | null
plan?: Record<string, unknown>
download_url?: string
library_song_id?: number
post_id?: number
error?: string
}
export async function createRemix(files: File[], prompt: string, libraryIds: number[] = []) {
const token = getAccessToken()
const body = new FormData()
body.append('prompt', prompt)
for (const f of files) body.append('files', f)
if (libraryIds.length) body.append('library_song_ids', libraryIds.join(','))
const res = await fetch(`${API_BASE_URL}/remix`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
body,
})
if (!res.ok) throw new Error(`Remix request failed (${res.status})`)
return res.json() as Promise<{ job_id: number; status: string; status_url: string }>
}
export function getRemixStatus(jobId: number) {
return apiFetch<RemixStatus>(`/remix/${jobId}`)
}
import { API_BASE_URL } from './client'
export interface ChatMessage {
type: 'chat'
user_id: number
text: string
}
export type RoomEvent =
| { type: 'snapshot'; dj_id: number; current_song_id: number | null; presence: number[]; chat_history: ChatMessage[]; fire_count: number; dj_queue: number[] }
| ChatMessage
| { type: 'reaction'; user_id: number; emoji: string; fire_count: number }
| { type: 'user_joined'; user_id: number }
| { type: 'user_left'; user_id: number }
| { type: 'queue_updated'; dj_queue: number[] }
| { type: 'dj_changed'; dj_id: number; dj_queue: number[] }
| { type: 'now_playing_changed'; song_id: number; dj_id: number }
| { type: 'error'; detail: string }
/** Raw WebSocket wrapper for /social/rooms/{id}/ws - auth here is just a user_id query param
* (matching the backend, which doesn't check the JWT on this route), not a Bearer header. */
export function connectToRoom(roomId: number, userId: number, onEvent: (e: RoomEvent) => void): WebSocket {
const wsBase = API_BASE_URL.replace(/^http/, 'ws')
const ws = new WebSocket(`${wsBase}/social/rooms/${roomId}/ws?user_id=${userId}`)
ws.onmessage = (msg) => {
try {
onEvent(JSON.parse(msg.data) as RoomEvent)
} catch {
// ignore malformed frames
}
}
return ws
}
export function sendChat(ws: WebSocket, text: string) {
ws.send(JSON.stringify({ type: 'chat', text }))
}
export function sendReaction(ws: WebSocket, emoji = '🔥') {
ws.send(JSON.stringify({ type: 'reaction', emoji }))
}
export function requestAux(ws: WebSocket) {
ws.send(JSON.stringify({ type: 'request_aux' }))
}
export function passAux(ws: WebSocket, toUserId?: number) {
ws.send(JSON.stringify({ type: 'pass_aux', to_user_id: toUserId }))
}
import { apiFetch } from './client'
export interface Post {
id: number
user_id: number
song_id: number
parent_post_id: number | null
caption: string
created_at: string
}
export interface PostTree {
post: Post
children: PostTree[]
}
export function createPost(songId: number, caption: string, parentPostId?: number) {
return apiFetch<Post>('/social/posts', {
method: 'POST',
json: { song_id: songId, caption, parent_post_id: parentPostId ?? null },
})
}
export function getPostTree(postId: number) {
return apiFetch<PostTree>(`/social/posts/${postId}/tree`)
}
export interface GeoDrop {
id: number
user_id: number
song_id: number
latitude: number
longitude: number
dropped_at: string
}
export function createGeoDrop(songId: number, latitude: number, longitude: number) {
return apiFetch<GeoDrop>('/social/geo-drop', {
method: 'POST',
json: { song_id: songId, latitude, longitude },
})
}
export function getNearbyDrops(lat: number, lon: number, radiusKm = 5) {
return apiFetch<{ drop: GeoDrop; distance_km: number }[]>(
`/social/geo-drop/nearby?lat=${lat}&lon=${lon}&radius_km=${radiusKm}`,
)
}
export interface LiveRoom {
id: number
dj_id: number
current_song_id: number | null
name: string
is_active: boolean
created_at: string
}
export function getActiveRooms() {
return apiFetch<LiveRoom[]>('/social/rooms')
}
export function createRoom(name: string) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name } })
}
import type { ReactNode } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
const NAV_ITEMS = [
{ to: '/library', label: 'Library' },
{ to: '/upload', label: 'Upload' },
{ to: '/discovery', label: 'Discovery' },
{ to: '/rooms', label: 'Rooms' },
{ to: '/channels', label: 'Channels' },
{ to: '/remix', label: 'Remix' },
]
export function Layout({ title, children }: { title: string; children: ReactNode }) {
const { logout } = useAuth()
const navigate = useNavigate()
const location = useLocation()
async function handleLogout() {
await logout()
......@@ -13,17 +23,29 @@ export function Layout({ title, children }: { title: string; children: ReactNode
return (
<div className="min-h-screen bg-neutral-950 text-white">
<header className="flex items-center justify-between border-b border-neutral-800 px-6 py-4">
<header className="border-b border-neutral-800 px-6 py-4">
<div className="mb-3 flex items-center justify-between">
<Link to="/library" className="text-lg font-semibold">
🎧 Stax
</Link>
<nav className="flex items-center gap-4 text-sm text-neutral-400">
<Link to="/library" className="hover:text-white">
Library
</Link>
<button onClick={handleLogout} className="hover:text-white">
<button onClick={handleLogout} className="text-sm text-neutral-400 hover:text-white">
Log out
</button>
</div>
<nav className="flex gap-4 overflow-x-auto text-sm">
{NAV_ITEMS.map((item) => (
<Link
key={item.to}
to={item.to}
className={`whitespace-nowrap pb-1 ${
location.pathname === item.to
? 'border-b-2 border-emerald-500 text-white'
: 'text-neutral-400 hover:text-white'
}`}
>
{item.label}
</Link>
))}
</nav>
</header>
<main className="mx-auto max-w-2xl px-6 py-8">
......
import { useEffect, useRef, useState } from 'react'
import { getCurrentUserId } from '../api/jwt'
import { connectToRoom, sendChat, sendReaction, requestAux, type ChatMessage } from '../api/roomSocket'
export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => void }) {
const userId = getCurrentUserId()
const [messages, setMessages] = useState<ChatMessage[]>([])
const [fireCount, setFireCount] = useState(0)
const [djId, setDjId] = useState<number | null>(null)
const [djQueue, setDjQueue] = useState<number[]>([])
const [text, setText] = useState('')
const wsRef = useRef<WebSocket | null>(null)
useEffect(() => {
if (userId === null) return
const ws = connectToRoom(roomId, userId, (event) => {
switch (event.type) {
case 'snapshot':
setMessages(event.chat_history)
setFireCount(event.fire_count)
setDjId(event.dj_id)
setDjQueue(event.dj_queue)
break
case 'chat':
setMessages((m) => [...m, event])
break
case 'reaction':
setFireCount(event.fire_count)
break
case 'queue_updated':
setDjQueue(event.dj_queue)
break
case 'dj_changed':
setDjId(event.dj_id)
setDjQueue(event.dj_queue)
break
}
})
wsRef.current = ws
return () => ws.close()
}, [roomId, userId])
function handleSend(e: React.FormEvent) {
e.preventDefault()
if (!text.trim() || !wsRef.current) return
sendChat(wsRef.current, text.trim())
setText('')
}
return (
<div className="flex min-h-screen flex-col bg-neutral-950 text-white">
<header className="flex items-center justify-between border-b border-neutral-800 px-6 py-4">
<button onClick={onLeave} className="text-sm text-neutral-400 hover:text-white">
← Leave room
</button>
<div className="text-sm text-neutral-400">
DJ #{djId} {fireCount > 0 && <span className="ml-2">🔥 {fireCount}</span>}
</div>
</header>
<div className="flex-1 overflow-y-auto px-6 py-4">
<ul className="space-y-2">
{messages.map((m, i) => (
<li key={i} className="text-sm">
<span className="text-neutral-500">#{m.user_id}:</span> {m.text}
</li>
))}
</ul>
</div>
<div className="border-t border-neutral-800 px-6 py-4">
<div className="mb-3 flex gap-2">
<button
onClick={() => wsRef.current && sendReaction(wsRef.current)}
className="rounded-full bg-neutral-800 px-3 py-1.5 text-sm hover:bg-neutral-700"
>
🔥 React
</button>
{djId !== userId && (
<button
onClick={() => wsRef.current && requestAux(wsRef.current)}
className="rounded-full bg-neutral-800 px-3 py-1.5 text-sm hover:bg-neutral-700"
>
🙋 Request aux {djQueue.includes(userId ?? -1) ? '(queued)' : ''}
</button>
)}
</div>
<form onSubmit={handleSend} className="flex gap-2">
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Say something…"
className="flex-1 rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
<button className="rounded-lg bg-emerald-500 px-4 py-2 font-medium text-neutral-950 hover:bg-emerald-400">
Send
</button>
</form>
</div>
</div>
)
}
import { useEffect, useState } from 'react'
import { Layout } from '../components/Layout'
import { createChannel, followChannel, getChannel, listChannels, unfollowChannel, type Channel } from '../api/channels'
import { getCurrentUserId } from '../api/jwt'
export function Channels() {
const userId = getCurrentUserId()
const [channels, setChannels] = useState<Channel[]>([])
const [followerCounts, setFollowerCounts] = useState<Record<number, number>>({})
const [followedIds, setFollowedIds] = useState<Set<number>>(new Set())
const [newName, setNewName] = useState('')
async function refresh() {
const list = await listChannels()
setChannels(list)
const counts: Record<number, number> = {}
await Promise.all(
list.map(async (c) => {
const detail = await getChannel(c.id)
counts[c.id] = detail.follower_count
}),
)
setFollowerCounts(counts)
}
useEffect(() => {
refresh()
}, [])
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newName.trim() || userId === null) return
await createChannel(userId, newName.trim())
setNewName('')
refresh()
}
async function toggleFollow(channelId: number) {
if (userId === null) return
if (followedIds.has(channelId)) {
await unfollowChannel(channelId, userId)
setFollowedIds((s) => new Set([...s].filter((id) => id !== channelId)))
setFollowerCounts((c) => ({ ...c, [channelId]: Math.max(0, c[channelId] - 1) }))
} else {
await followChannel(channelId, userId)
setFollowedIds((s) => new Set(s).add(channelId))
setFollowerCounts((c) => ({ ...c, [channelId]: (c[channelId] ?? 0) + 1 }))
}
}
return (
<Layout title="Channels">
<form onSubmit={handleCreate} className="mb-6 flex gap-2">
<input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="New channel name"
className="flex-1 rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
<button className="rounded-lg bg-emerald-500 px-4 py-2 font-medium text-neutral-950 hover:bg-emerald-400">
Create
</button>
</form>
<ul className="space-y-2">
{channels.map((channel) => (
<li
key={channel.id}
className="flex items-center justify-between rounded-lg border border-neutral-800 bg-neutral-900 px-4 py-3"
>
<div>
<p className="font-medium text-white">{channel.name}</p>
<p className="text-xs text-neutral-500">
{followerCounts[channel.id] ?? 0} followers · owner #{channel.owner_id}
</p>
</div>
{channel.owner_id !== userId && (
<button
onClick={() => toggleFollow(channel.id)}
className="rounded-full bg-neutral-800 px-4 py-1.5 text-sm text-white hover:bg-neutral-700"
>
{followedIds.has(channel.id) ? 'Unfollow' : 'Follow'}
</button>
)}
</li>
))}
{channels.length === 0 && <p className="text-neutral-500">No channels yet.</p>}
</ul>
</Layout>
)
}
import { useEffect, useState } from 'react'
import { Layout } from '../components/Layout'
import { getDiscoveryHistory, listen, swipe, type DiscoveredSong } from '../api/discovery'
export function Discovery() {
const [history, setHistory] = useState<DiscoveredSong[]>([])
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
function refresh() {
getDiscoveryHistory().then((res) => setHistory(res.history))
}
useEffect(refresh, [])
async function handleListen(file: File) {
setBusy(true)
setMessage(null)
try {
const res = await listen(file)
if (res.status === 'success') {
setMessage(`Detected: ${res.detected.title ?? 'unknown'} - ${res.detected.artist ?? ''}`)
refresh()
} else {
setMessage(res.message)
}
} catch {
setMessage('Could not identify that clip.')
} finally {
setBusy(false)
}
}
async function handleSwipe(songId: number, liked: boolean) {
await swipe(songId, liked)
setHistory((h) => h.map((s) => (s.id === songId ? { ...s, liked } : s)))
}
return (
<Layout title="Discovery">
<div className="mb-6 rounded-xl border border-dashed border-neutral-700 p-6 text-center">
<p className="mb-3 text-sm text-neutral-400">Drop a short clip of what's playing to identify it</p>
<input
type="file"
accept="audio/*"
disabled={busy}
onChange={(e) => e.target.files?.[0] && handleListen(e.target.files[0])}
className="block w-full text-sm text-neutral-300 file:mr-3 file:rounded-full file:border-0 file:bg-neutral-800 file:px-4 file:py-2 file:text-white hover:file:bg-neutral-700"
/>
{message && <p className="mt-3 text-sm text-emerald-400">{message}</p>}
</div>
<h2 className="mb-3 text-sm font-medium uppercase tracking-wide text-neutral-500">
Last 24 hours
</h2>
<ul className="divide-y divide-neutral-800">
{history.map((song) => (
<li key={song.id} className="flex items-center gap-4 py-3">
{song.coverart ? (
<img src={song.coverart} alt="" className="h-10 w-10 rounded-md object-cover" />
) : (
<div className="h-10 w-10 rounded-md bg-neutral-800" />
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{song.title}</p>
<p className="truncate text-sm text-neutral-400">{song.artist}</p>
</div>
<button
onClick={() => handleSwipe(song.id, true)}
className={`rounded-full px-2 py-1 text-lg ${song.liked === true ? 'opacity-100' : 'opacity-40 hover:opacity-100'}`}
>
❤️
</button>
<button
onClick={() => handleSwipe(song.id, false)}
className={`rounded-full px-2 py-1 text-lg ${song.liked === false ? 'opacity-100' : 'opacity-40 hover:opacity-100'}`}
>
✖️
</button>
</li>
))}
</ul>
</Layout>
)
}
import { useEffect, useRef, useState } from 'react'
import { Layout } from '../components/Layout'
import { createRemix, getRemixStatus, type RemixStatus } from '../api/remix'
const STAGES: RemixStatus['status'][] = ['queued', 'planning', 'separating', 'mixing', 'mastering', 'tagging', 'done']
export function Remix() {
const [files, setFiles] = useState<File[]>([])
const [prompt, setPrompt] = useState('')
const [status, setStatus] = useState<RemixStatus | null>(null)
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const pollRef = useRef<number | null>(null)
useEffect(() => {
return () => {
if (pollRef.current) window.clearInterval(pollRef.current)
}
}, [])
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (files.length === 0 || !prompt.trim()) return
setSubmitting(true)
setError(null)
setStatus(null)
try {
const { job_id } = await createRemix(files, prompt.trim())
pollRef.current = window.setInterval(async () => {
const s = await getRemixStatus(job_id)
setStatus(s)
if (s.status === 'done' || s.status === 'error') {
if (pollRef.current) window.clearInterval(pollRef.current)
}
}, 2000)
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not start the remix')
} finally {
setSubmitting(false)
}
}
const stageIndex = status ? STAGES.indexOf(status.status) : -1
return (
<Layout title="AI Remix">
<p className="mb-6 text-sm text-neutral-400">
Upload 1-5 songs and describe the remix in plain language. Gemini directs the arrangement,
Demucs does the stem separation.
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="file"
accept="audio/*"
multiple
onChange={(e) => setFiles(Array.from(e.target.files ?? []).slice(0, 5))}
className="block w-full text-sm text-neutral-300 file:mr-3 file:rounded-full file:border-0 file:bg-neutral-800 file:px-4 file:py-2 file:text-white hover:file:bg-neutral-700"
/>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={2}
placeholder="e.g. Blend the vocals of the first song over the drums of the second, slowed down with heavy reverb"
className="w-full rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
<button
disabled={submitting || files.length === 0 || !prompt.trim()}
className="rounded-lg bg-emerald-500 px-5 py-2 font-medium text-neutral-950 transition hover:bg-emerald-400 disabled:opacity-40"
>
{submitting ? 'Starting…' : 'Create Remix'}
</button>
</form>
{error && <p className="mt-4 text-sm text-red-400">{error}</p>}
{status && (
<div className="mt-6 rounded-xl border border-neutral-800 bg-neutral-900 p-4">
<div className="mb-3 flex gap-1">
{STAGES.slice(0, -1).map((stage, i) => (
<div
key={stage}
className={`h-1.5 flex-1 rounded-full ${i <= stageIndex ? 'bg-emerald-500' : 'bg-neutral-800'}`}
/>
))}
</div>
<p className="text-sm text-neutral-300">
{status.status === 'error' ? `Error: ${status.error}` : status.stage_detail ?? status.status}
</p>
{status.status === 'done' && status.download_url && (
<a
href={status.download_url}
target="_blank"
rel="noreferrer"
className="mt-2 inline-block text-sm text-emerald-400 hover:underline"
>
Download {status.remix_name}
</a>
)}
</div>
)}
</Layout>
)
}
import { useEffect, useState } from 'react'
import { Layout } from '../components/Layout'
import { createRoom, getActiveRooms, type LiveRoom } from '../api/social'
import { RoomView } from '../components/RoomView'
export function Rooms() {
const [rooms, setRooms] = useState<LiveRoom[]>([])
const [newRoomName, setNewRoomName] = useState('')
const [activeRoomId, setActiveRoomId] = useState<number | null>(null)
function refresh() {
getActiveRooms().then(setRooms)
}
useEffect(refresh, [])
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newRoomName.trim()) return
const room = await createRoom(newRoomName.trim())
setNewRoomName('')
setRooms((r) => [room, ...r])
setActiveRoomId(room.id)
}
if (activeRoomId !== null) {
return <RoomView roomId={activeRoomId} onLeave={() => setActiveRoomId(null)} />
}
return (
<Layout title="Pass-the-Aux Rooms">
<form onSubmit={handleCreate} className="mb-6 flex gap-2">
<input
value={newRoomName}
onChange={(e) => setNewRoomName(e.target.value)}
placeholder="Room name"
className="flex-1 rounded-lg border border-neutral-700 bg-neutral-800 px-3 py-2 text-white placeholder-neutral-500 outline-none focus:border-emerald-500"
/>
<button className="rounded-lg bg-emerald-500 px-4 py-2 font-medium text-neutral-950 hover:bg-emerald-400">
Start
</button>
</form>
<ul className="space-y-2">
{rooms.map((room) => (
<li key={room.id}>
<button
onClick={() => setActiveRoomId(room.id)}
className="flex w-full items-center justify-between rounded-lg border border-neutral-800 bg-neutral-900 px-4 py-3 text-left hover:border-neutral-700"
>
<span className="font-medium text-white">{room.name}</span>
<span className="text-xs text-neutral-500">DJ #{room.dj_id}</span>
</button>
</li>
))}
{rooms.length === 0 && <p className="text-neutral-500">No active rooms right now.</p>}
</ul>
</Layout>
)
}
import { useState } from 'react'
import { Layout } from '../components/Layout'
import { uploadDirect, type TagResponse } from '../api/music'
export function Upload() {
const [file, setFile] = useState<File | null>(null)
const [busy, setBusy] = useState(false)
const [result, setResult] = useState<TagResponse | null>(null)
const [error, setError] = useState<string | null>(null)
async function handleUpload() {
if (!file) return
setBusy(true)
setError(null)
setResult(null)
try {
const res = await uploadDirect(file)
setResult(res)
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
} finally {
setBusy(false)
}
}
return (
<Layout title="Upload &amp; Tag">
<p className="mb-6 text-sm text-neutral-400">
Upload an untagged track - it's fingerprinted, tagged with title/artist/album/art/lyrics, and
added to your library.
</p>
<div className="rounded-xl border border-dashed border-neutral-700 p-8 text-center">
<input
type="file"
accept="audio/*"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
className="mb-4 block w-full text-sm text-neutral-300 file:mr-3 file:rounded-full file:border-0 file:bg-neutral-800 file:px-4 file:py-2 file:text-white hover:file:bg-neutral-700"
/>
<button
onClick={handleUpload}
disabled={!file || busy}
className="rounded-lg bg-emerald-500 px-5 py-2 font-medium text-neutral-950 transition hover:bg-emerald-400 disabled:opacity-40"
>
{busy ? 'Identifying & tagging…' : 'Upload'}
</button>
</div>
{error && <p className="mt-4 text-sm text-red-400">{error}</p>}
{result && (
<div className="mt-6 flex gap-4 rounded-xl border border-neutral-800 bg-neutral-900 p-4">
{result.metadata.cover_art && (
<img src={result.metadata.cover_art} alt="" className="h-20 w-20 rounded-lg object-cover" />
)}
<div>
<p className="font-semibold text-white">{result.metadata.title}</p>
<p className="text-sm text-neutral-400">
{result.metadata.artist} · {result.metadata.album} · {result.metadata.genre}
</p>
<a
href={result.download_url}
target="_blank"
rel="noreferrer"
className="mt-2 inline-block text-sm text-emerald-400 hover:underline"
>
Download tagged file
</a>
</div>
</div>
)}
</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