From 36cfb96c05677bac6086716254c68b1d2d11b550 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Tue, 22 Sep 2026 21:27:33 +0200 Subject: [PATCH] Added OneLibrary USB loading --- frontend/src/App.tsx | 166 ++++++++++++- frontend/src/components/DevicesSection.tsx | 204 ++++++++++++++++ frontend/src/components/ImportDialog.tsx | 263 +++++++++++++++++++++ frontend/src/components/PrepStrip.tsx | 18 +- frontend/src/components/Sidebar.tsx | 27 ++- 5 files changed, 659 insertions(+), 19 deletions(-) create mode 100644 frontend/src/components/DevicesSection.tsx create mode 100644 frontend/src/components/ImportDialog.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 854d9ac..6070fe1 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -20,6 +20,7 @@ import { EditTagsDialog } from './components/EditTagsDialog' import { PathMappingDialog } from './components/PathMappingDialog' import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' +import { ImportDialog } from './components/ImportDialog' function applyFilters(tracks: Track[], f: Filters): Track[] { const q = f.search.trim().toLowerCase() @@ -55,6 +56,7 @@ export default function App() { const [showHistory, setShowHistory] = useState(false) const [prepTrack, setPrepTrack] = useState(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays + const [importing, setImporting] = useState(false) const playTrack = useCallback((t: Track) => { setPrepTrack(t) @@ -172,9 +174,72 @@ export default function App() { enabled: loaded && source.kind === 'playlist', }) + // A browsed device. Separate queries and separate cache keys from the + // collection's: the two libraries can hold tracks with identical ids, and one + // shared key would serve a stick's track as if it were a collection track. + const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist' + const deviceTracks = useQuery({ + queryKey: ['source-tracks', 'all'], + queryFn: () => api.sourceTracks({ limit: 20000, sort: 'artist' }), + enabled: viewingDevice && source.kind === 'device', + }) + const devicePlaylistTracks = useQuery({ + queryKey: ['source-tracks', source.kind === 'device-playlist' ? source.id : null], + queryFn: () => api.sourcePlaylistTracks((source as { id: string }).id), + enabled: source.kind === 'device-playlist', + }) + // The device's own capabilities — read-only — provided to the browsing half of + // the UI below. That is what makes every existing gate correct here without a + // single component asking whether it is looking at a device: inline editing, + // Edit Tags, the rating stars and all twelve deck edit handlers already gate + // on capabilities, and a device's say `writable: false`. + const deviceCaps = useQuery({ + queryKey: ['source-capabilities'], + queryFn: api.sourceCapabilities, + enabled: viewingDevice, + staleTime: Infinity, + }) + const openDevice = useQuery({ queryKey: ['source'], queryFn: api.source }) + + // What the VIEW can do, as opposed to what the loaded collection can do. While + // a device is being browsed these are its read-only capabilities, so the + // browsing half of the UI gates itself correctly with no new conditions. + // Falls back to the collection's until the device's resolve, so no frame + // renders without capabilities at all. + const viewCaps = viewingDevice + ? (deviceCaps.data ?? + // Until the device's own capabilities arrive, assume READ-ONLY rather + // than falling back to the collection's. The fallback is the safe + // direction on purpose: guessing "writable" for one frame would offer an + // edit that, if taken, would be sent to the wrong library entirely. + { ...capabilities.data!, writable: false, readonly_cause: 'platform_incomplete' as const }) + : capabilities.data! + + const deviceLabel = openDevice.data?.label ?? 'device' + // One name for whatever is on screen, so the header and the status bar cannot + // disagree about what the user is looking at. + const viewName = + source.kind === 'all' + ? 'All Tracks' + : source.kind === 'device' + ? deviceLabel + : source.name + const isAll = source.kind === 'all' - const tracks: Track[] = isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? []) - const loading = isAll ? allTracks.isLoading : playlistTracks.isLoading + const tracks: Track[] = viewingDevice + ? source.kind === 'device' + ? (deviceTracks.data?.items ?? []) + : (devicePlaylistTracks.data ?? []) + : isAll + ? (allTracks.data?.items ?? []) + : (playlistTracks.data ?? []) + const loading = viewingDevice + ? source.kind === 'device' + ? deviceTracks.isLoading + : devicePlaylistTracks.isLoading + : isAll + ? allTracks.isLoading + : playlistTracks.isLoading // Search / filters apply to both the library and playlists (the toolbar is // always visible). In a playlist a filtered view disables drag-reorder — see // `canReorder` below — so a partial order can't overwrite the full entry list. @@ -301,8 +366,29 @@ export default function App() { /> )} + {importing && ( + setImporting(false)} + onDone={(msg) => { + setImporting(false) + notify('success', msg) + }} + onError={onError} + /> + )} + {/* Prep strip spans the top of the window; the library sits below it. */} - + + +
setShowHistory(true)} + onImport={() => setImporting(true)} /> +
{/* Search / filters / column settings — always visible. */} setShowPaths(true)} /> - {!isAll && ( + {(!isAll || viewingDevice) && (
- ♫ - {source.name} - - {filtersActive - ? `${filtered.length} of ${tracks.length} tracks · × to remove · clear the filter to reorder` - : `${tracks.length} tracks · drag ⠿ to reorder · × to remove`} + + {viewingDevice ? '⬒' : '♫'} + {viewName} + {viewingDevice ? ( + <> + + {filtersActive + ? `${filtered.length} of ${tracks.length} tracks` + : `${tracks.length} tracks`} + + + + Device · read-only + + + + + ) : ( + + {filtersActive + ? `${filtered.length} of ${tracks.length} tracks · × to remove · clear the filter to reorder` + : `${tracks.length} tracks · drag ⠿ to reorder · × to remove`} + + )}
)}
{loading ? (
Loading…
+ ) : viewingDevice ? ( + /* A device uses the plain table, not the playlist one: a stick's + playlists cannot be reordered or have entries removed, so the + drag handle and the × would exist only to be inert. Selection is + omitted for the same reason — SelectionBar adds to the loaded + COLLECTION's playlists, and these ids belong to the device. */ + filtered.length === 0 ? ( +
+
+ {tracks.length === 0 ? 'Nothing here' : 'No tracks match'} +
+
+ {tracks.length === 0 + ? 'This device has no tracks in view.' + : 'Try clearing some filters.'} +
+
+ ) : ( + setMenu({ track, x, y })} + onPlay={playTrack} + activeTrackId={prepTrack?.id ?? null} + columnVisibility={columnVisibility} + columnOrder={columnOrder} + columnSizing={columnSizing} + onColumnOrderChange={setColumnOrder} + onColumnSizingChange={setColumnSizing} + /> + ) ) : isAll ? ( filtered.length === 0 ? (
@@ -409,12 +552,13 @@ export default function App() { setForcePicker(true)} />
+
diff --git a/frontend/src/components/DevicesSection.tsx b/frontend/src/components/DevicesSection.tsx new file mode 100644 index 0000000..ceb301d --- /dev/null +++ b/frontend/src/components/DevicesSection.tsx @@ -0,0 +1,204 @@ +import { useEffect } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type PlaylistNode } from '../api' +import type { Source } from './Sidebar' + +/** + * Plugged-in libraries, in the sidebar, the way rekordbox and Traktor show them. + * + * The list genuinely changes while the app is open — a device is whatever stick + * is mounted — so unlike everything else in the sidebar this POLLS. It is a + * directory stat per mount point, which is cheap enough to do every few seconds + * and the only way a drive can appear without the user reloading. + * + * Browsing a device reuses the ordinary track table and deck: the adapter + * projects a drive into the same generic model the collection uses, so there is + * nothing here that needs its own table, its own row or its own player. + */ + +const POLL_MS = 4000 + +interface Props { + source: Source + onSelect: (s: Source) => void + onError: (msg: string) => void + onImport: () => void +} + +export function DevicesSection({ source, onSelect, onError, onImport }: Props) { + const qc = useQueryClient() + + const devices = useQuery({ + queryKey: ['sources'], + queryFn: api.sources, + refetchInterval: POLL_MS, + }) + const open = useQuery({ queryKey: ['source'], queryFn: api.source }) + const openPath = open.data?.loaded ? open.data.path : null + + const playlists = useQuery({ + queryKey: ['source-playlists'], + queryFn: api.sourcePlaylists, + enabled: !!openPath, + }) + + const openDevice = useMutation({ + mutationFn: (path: string) => api.openSource(path), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['source'] }) + qc.invalidateQueries({ queryKey: ['source-playlists'] }) + onSelect({ kind: 'device' }) + }, + onError: (e: Error) => onError(e.message), + }) + + const eject = useMutation({ + mutationFn: () => api.closeSource(), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['source'] }) + qc.removeQueries({ queryKey: ['source-tracks'] }) + qc.removeQueries({ queryKey: ['source-playlists'] }) + onSelect({ kind: 'all' }) + }, + onError: (e: Error) => onError(e.message), + }) + + // A drive can be physically unplugged while it is open. Nothing crashes — the + // routes just start failing — but leaving it selected would show a library + // that is not there, so fall back to the collection. + const stillPresent = + !openPath || (devices.data ?? []).some((d) => d.path === openPath) + useEffect(() => { + if (!openPath || stillPresent || eject.isPending) return + eject.mutate() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [openPath, stillPresent]) + + const list = devices.data ?? [] + if (list.length === 0 && !openPath) return null + + const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist' + + return ( + <> +
+ + Devices + + {openPath && ( + + )} +
+ +
+ {list.map((d) => { + const isOpen = d.path === openPath + return ( +
+ + + {isOpen && + (playlists.data ?? []).map((n) => ( + + ))} +
+ ) + })} + + {openDevice.isPending && ( +
Opening…
+ )} + {viewingDevice && openPath && ( + + )} +
+ + ) +} + +/** + * A playlist on the device. Deliberately NOT `NodeRow`: that one carries rename + * and delete, and every one of a device's nodes reports those as false, so + * reusing it would mean rendering controls that exist only to be disabled. + */ +function DevicePlaylistRow({ + node, + depth, + source, + onSelect, +}: { + node: PlaylistNode + depth: number + source: Source + onSelect: (s: Source) => void +}) { + const selected = source.kind === 'device-playlist' && source.id === node.id + const isFolder = node.kind === 'folder' + return ( + <> + + {(node.children ?? []).map((c) => ( + + ))} + + ) +} diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsx new file mode 100644 index 0000000..176f0c7 --- /dev/null +++ b/frontend/src/components/ImportDialog.tsx @@ -0,0 +1,263 @@ +import { useEffect, useRef, useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type ImportPreview, type JobStatus } from '../api' + +/** + * Import a browsed device into the loaded collection. + * + * Two phases in one dialog, because they are one decision: a confirm step that + * says what is about to happen, and a progress step that shows it happening. + * + * The preview is fetched fresh every time this opens and whenever the + * destination changes. It is never cached: a stick can be re-exported between + * looking and importing, and a stale preview is worse than none. + */ + +const POLL_MS = 300 + +function gb(bytes: number): string { + if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB` + if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB` + return `${(bytes / 1e3).toFixed(0)} kB` +} + +interface Props { + /** Playlist to import, or null for the whole device. */ + playlistId: string | null + deviceLabel: string + onClose: () => void + onDone: (msg: string) => void + onError: (msg: string) => void +} + +export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError }: Props) { + const qc = useQueryClient() + const [destination, setDestination] = useState('') + const [job, setJob] = useState(null) + const [starting, setStarting] = useState(false) + const pollRef = useRef(null) + + // A sensible default the user can override. `~` is expanded server-side. + useEffect(() => { + if (!destination) setDestination(`~/Music/Konduktor Imports/${deviceLabel}`) + }, [deviceLabel, destination]) + + const body = { + destination, + playlist_ids: playlistId ? [playlistId] : [], + track_ids: [], + folder_name: deviceLabel, + } + + const preview = useQuery({ + queryKey: ['import-preview', destination, playlistId], + queryFn: () => api.importPreview(body), + enabled: !!destination && !job, + staleTime: 0, + gcTime: 0, + }) + + // Poll while the job runs. Cleared on unmount so closing mid-import does not + // leave a timer firing at a dead component — the import itself keeps going, + // which is the point of it being a job. + useEffect(() => { + if (!job || job.state !== 'running') return + pollRef.current = window.setInterval(async () => { + try { + const next = await api.job(job.id) + setJob(next) + if (next.state !== 'running') { + if (pollRef.current) window.clearInterval(pollRef.current) + if (next.state === 'done') { + const r = next.result as { tracks?: number; playlists?: number } | null + // The collection changed underneath every cached view of it. + qc.invalidateQueries({ queryKey: ['tracks'] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['collection'] }) + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['facets'] }) + onDone( + `Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` + + (r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''), + ) + } else if (next.state === 'failed') { + onError(next.error || 'Import failed') + } + } + } catch (e) { + onError((e as Error).message) + if (pollRef.current) window.clearInterval(pollRef.current) + } + }, POLL_MS) + return () => { + if (pollRef.current) window.clearInterval(pollRef.current) + } + }, [job, qc, onDone, onError]) + + const start = async () => { + setStarting(true) + try { + setJob(await api.startImport(body)) + } catch (e) { + onError((e as Error).message) + } finally { + setStarting(false) + } + } + + const cancel = async () => { + if (!job) return + try { + await api.cancelJob(job.id) + } catch (e) { + onError((e as Error).message) + } + } + + const p = preview.data + const running = job?.state === 'running' + const finished = job != null && job.state !== 'running' + const pct = job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null + + return ( +
+
+
+

+ Import from {deviceLabel} + {playlistId ? '' : ' — everything'} +

+
+ +
+ {!job && ( + <> + + + {preview.isLoading &&
Checking…
} + {preview.isError && ( +
{(preview.error as Error).message}
+ )} + + {p && ( +
+
+ {p.importable} track{p.importable === 1 ? '' : 's'} + {p.playlists.length > 0 && + ` · ${p.playlists.length} playlist${p.playlists.length === 1 ? '' : 's'}`} + · {gb(p.total_bytes)} to copy +
+ + {p.free_bytes != null && ( +
+ {gb(p.free_bytes)} free + {p.enough_space === false && ' — not enough space'} +
+ )} + + {/* Reported and then skipped, rather than failing the whole + import halfway through a multi-minute copy. */} + {p.missing.length > 0 && ( +
+ {p.missing.length} track{p.missing.length === 1 ? '' : 's'} will be skipped — + the audio file is not on the drive: +
{p.missing.slice(0, 4).join(', ')}
+
+ )} + + {/* A warning, not a block: everything is imported as a new + entry, so a re-import legitimately duplicates. */} + {p.duplicates.length > 0 && ( +
+ {p.duplicates.length} of these look like tracks your collection already has. + They will be added again as new entries. +
+ )} + +
+ Playlists land in a folder called “{deviceLabel}”. +
+
+ )} + + )} + + {job && ( +
+
{job.message || 'Working…'}
+
+
+
+ {pct != null && running && ( +
+ {gb(job.done)} of {gb(job.total)} +
+ )} + {job.state === 'cancelled' && ( +
+ Cancelled. Nothing was added, and the copied files were removed. +
+ )} + {job.state === 'failed' &&
{job.error}
} + {job.state === 'done' && ( +
Done — the tracks are in your collection.
+ )} +
+ )} +
+ +
+ {running ? ( + <> + + + + ) : ( + <> + + {!finished && ( + + )} + + )} +
+
+
+ ) +} diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 5455d45..67d62b9 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -23,6 +23,13 @@ interface Props { onError?: (msg: string) => void /** Neutral/success feedback (e.g. Auto Hotcues result). */ onNotify?: (kind: 'success' | 'error', msg: string) => void + /** + * The track came from a browsed DEVICE, not the loaded library, so its audio + * and cues must be read from the source endpoints. Every EDIT control is + * already inert here — a device's capabilities say `writable: false`, and the + * deck gates on those — so this only needs to redirect the two READS. + */ + fromDevice?: boolean } function fmt(secs: number): string { @@ -57,7 +64,7 @@ const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32] * Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the * scratch engine and both waveform views. */ -export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) { +export function PrepStrip({ track, playRequest = 0, onError, onNotify, fromDevice = false }: Props) { const qc = useQueryClient() const [playing, setPlaying] = useState(false) const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active @@ -214,7 +221,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) let cancelled = false setCols(null) setWaveStatus('loading') - analyzeWaveform(api.audioUrl(trackId)) + analyzeWaveform(fromDevice ? api.sourceAudioUrl(trackId) : api.audioUrl(trackId)) .then((res) => { if (cancelled) return setCols(res.cols) @@ -245,7 +252,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) return () => { cancelled = true } - }, [trackId]) + }, [trackId, fromDevice]) // Fetch beatgrid + cue markers for the loaded track. useEffect(() => { @@ -255,8 +262,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } let cancelled = false setCueData(null) - api - .trackCues(trackId) + ;(fromDevice ? api.sourceTrackCues(trackId) : api.trackCues(trackId)) .then((d) => { if (cancelled) return setCueData(d) @@ -271,7 +277,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) return () => { cancelled = true } - }, [trackId]) + }, [trackId, fromDevice]) const toggle = () => { const eng = playbackRef.current diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index a5f6c3b..6b5f261 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -3,14 +3,30 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type PlaylistKind, type PlaylistNode } from '../api' import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' +import { DevicesSection } from './DevicesSection' -export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string } +/** + * Which view the main table is showing. + * + * `device*` variants are a browsed import SOURCE — a plugged-in stick — rather + * than the loaded collection. They are a view like any other, so the table, the + * toolbar and the deck need no special case; what differs is that a device is + * read-only, and that is carried by its CAPABILITIES rather than by this type, + * so no component has to ask "am I looking at a device?" before deciding what to + * offer. + */ +export type Source = + | { kind: 'all' } + | { kind: 'playlist'; id: string; name: string } + | { kind: 'device' } + | { kind: 'device-playlist'; id: string; name: string } interface Props { source: Source onSelect: (s: Source) => void onError: (msg: string) => void onOpenHistory: () => void + onImport: () => void } // Kind picks the icon; every behavioural question is answered by the node's own @@ -170,7 +186,7 @@ function NodeRow({ ) } -export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { +export function Sidebar({ source, onSelect, onError, onOpenHistory, onImport }: Props) { const qc = useQueryClient() // There is no per-node flag for "you may create a NEW playlist" — the node // flags describe existing nodes — so this is the library-level gate. @@ -263,6 +279,13 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { ))}
+ +