import { createPortal } from 'react-dom' import { useEffect, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type ImportPreview, type JobStatus } from '../api' import { useCaps } from '../lib/capabilities' import { placedAudioSummary } from '../lib/platformCopy' import { FolderPicker } from './FolderPicker' import { useServerImportFolder } from './AddFilesDialog' /** * 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() // The BASE folder, and whether to put this device's audio in its own // subfolder of it. Kept apart rather than as one path because they are two // different decisions: where your music lives, and how one import is filed // inside it. Joining them for display would make the toggle look like it was // editing the folder you picked. // The LIBRARY's capabilities (mounted outside the browsed device's context). // One that places its own audio — a stick — needs no destination. const caps = useCaps() const places = caps.tracks.places_audio // A library held by a server: the audio is uploaded into one of ITS folders. const uploads = !places && caps.tracks.audio_destination === 'library' const remote = useServerImportFolder(uploads) const [baseFolder, setBaseFolder] = useState('') const [useSubfolder, setUseSubfolder] = useState(true) const [browsing, setBrowsing] = useState(false) const [job, setJob] = useState(null) const [starting, setStarting] = useState(false) const pollRef = useRef(null) // Both come from prefs, so the choice survives the dialog closing. `~` is // expanded server-side, so the default needs no knowledge of the home path. const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const prefsLoaded = prefs.isSuccess useEffect(() => { if (!prefsLoaded || baseFolder) return const p = prefs.data as { importFolder?: string; importSubfolder?: boolean } if (uploads) { if (remote.folder) setBaseFolder(remote.folder) } else { setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports') } if (typeof p?.importSubfolder === 'boolean') setUseSubfolder(p.importSubfolder) }, [prefsLoaded, prefs.data, baseFolder, uploads, remote.folder]) const remember = (patch: Record) => { api.patchPrefs(patch).catch(() => { /* best-effort: a failed pref write must not block an import */ }) } const destination = useSubfolder && baseFolder ? `${baseFolder}/${deviceLabel}` : baseFolder 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 createPortal( <> {browsing && ( { setBaseFolder(path) if (uploads) remote.remember(path) else remember({ importFolder: path }) }} onClose={() => setBrowsing(false)} /> )}

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

{!job && ( <> {places && p && (
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
)} {!places && (
{uploads ? `Upload audio to ${remote.serverName}, into` : 'Copy audio into'}
{baseFolder || 'Loading…'}
{/* The resolved path, always visible: the toggle changes where files actually land, and that should never have to be inferred from a checkbox. */}
{destination}
)} {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'}`} {p.total_bytes > 0 && · {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 {places ? caps.save.app_name : '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 && ( )} )}
, document.body, ) }