Implemented local export system

This commit is contained in:
patben8 committed 2026-10-20 11:49:20 +02:00
1 parent 17c177e34e
commit 23a5cd72f4
27 files changed
+2695 -97

No files matched your search

+81 -3
View File
@@ -828,6 +828,13 @@ export interface SourceStatus {
export interface ExportSet {
id: string
name: string
/** 'folder': exported into `destination`. 'computer': PUSHED into the DJ
* apps' own libraries on this computer (`targets` names the apps, there is
* no destination), `mode` saying how. */
kind: 'folder' | 'computer'
/** A push: 'merge' adds and updates only what this set put there;
* 'overwrite' replaces the whole library with this set. */
mode: 'merge' | 'overwrite'
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
* empty. They share one destination and ONE copy of the audio. */
targets: string[]
@@ -896,6 +903,64 @@ export interface ExportPreview {
to_measure: number
}
/** One DJ app's library on this computer, as a push target. */
export interface LocalLibrary {
platform: string
name: string
path: string | null
/** Found by the platform's own detection (false: the user's setting). */
detected: boolean
/** A FACT; the UI words it. */
blocked: 'not_found' | 'open_in_konduktor' | 'cloud_synced' | 'unreadable' | null
running: boolean
}
export interface LocalLibraries {
libraries: LocalLibrary[]
/** The shared folder pushed audio lives in, and its default. */
audio_root: string
audio_root_default: string
/** The shared folder's Normalise level; null = off. */
level: NormalizeOptions | null
}
export interface PushTarget {
platform: string
name: string
path: string | null
blocked: LocalLibrary['blocked']
running: boolean
/** Tracks this set has not pushed here before. */
add: number
/** Tracks it has: kept, or brought up to date where changed. */
already: number
/** Tracks that left the set since the last push. */
remove: number
/** Overwrite: the other sets pushed here, which it removes. */
wipes_sets: string[]
}
/** What a push would do now. Computed fresh every time. */
export interface PushPreview {
mode: 'merge' | 'overwrite'
tracks: number
pushable: number
/** Copies in the shared folder kept rather than copied again. */
unchanged: number
missing: string[]
playlists: string[]
total_bytes: number
audio_root: string
free_bytes: number | null
enough_space: boolean | null
normalised: number
level_counts: Record<string, number>
to_measure: number
targets: PushTarget[]
/** A FACT, not a sentence. Null when the push can run. */
blocked: 'no_target' | 'nothing_to_push' | 'target_unavailable' | 'app_running' | null
}
/** The run dialog's options; each is remembered on the set. Omitted = the
* set's own answer. */
export interface ExportRunOptions {
@@ -1098,11 +1163,16 @@ export const api = {
// All scoped to the LOADED library on the server, by its stable id, so
// nothing here has to carry which collection it means.
exports: () => getJSON<ExportSet[]>('/api/exports'),
createExport: (body: { name: string; targets: string[]; destination: string }) =>
send<ExportSet>('POST', '/api/exports', body),
createExport: (body: {
name: string
targets: string[]
destination: string
kind?: ExportSet['kind']
mode?: ExportSet['mode']
}) => send<ExportSet>('POST', '/api/exports', body),
updateExport: (
id: string,
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids'>>,
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids' | 'mode'>>,
) =>
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
deleteExport: (id: string) =>
@@ -1138,6 +1208,14 @@ export const api = {
// The run dialog's options travel with the click; the set remembers them.
runExport: (id: string, body: ExportRunOptions = {}) =>
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
// A "computer" set: pushed into this computer's Traktor / rekordbox. Only
// lock_grids and auto_gain apply — Normalise is the shared folder's, set in
// Settings → Local libraries (`localNormalise` / `localLevel` prefs).
localLibraries: () => getJSON<LocalLibraries>('/api/local-libraries'),
pushPreview: (id: string, body: ExportRunOptions = {}) =>
send<PushPreview>('POST', `/api/exports/${encodeURIComponent(id)}/push/preview`, body),
runPush: (id: string, body: ExportRunOptions = {}) =>
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/push`, body),
// ---- path remapping (per-collection OS-path prefix translation) ----
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
+129 -5
View File
@@ -2,6 +2,7 @@ import { createPortal } from 'react-dom'
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api, type ExportSet } from '../api'
import { localLibraryProblem } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
/**
@@ -15,6 +16,13 @@ import { FolderPicker } from './FolderPicker'
* detail deferred to export time. A Traktor `<LOCATION>` is a volume name plus
* a volume-relative path — both derived from where the export is written — so
* the library file genuinely cannot be built until the destination is known.
*
* Or the set goes to THIS COMPUTER: pushed straight into the Traktor collection
* and/or rekordbox library its DJ apps use (`local_push.py`), merging beside
* the user's own tracks or replacing the library. No destination is asked —
* which library each app uses, and the shared audio folder, are this
* computer's settings. The kind is chosen once, at creation: a push leaves
* records of what it put where, which a change of kind would orphan.
*/
interface Props {
@@ -29,6 +37,15 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
const [name, setName] = useState(editing?.name ?? '')
const [chosen, setChosen] = useState<string[]>(editing?.targets ?? ['traktor'])
const [destination, setDestination] = useState(editing?.destination ?? '')
const [kind, setKind] = useState<ExportSet['kind']>(editing?.kind ?? 'folder')
const [mode, setMode] = useState<ExportSet['mode']>(editing?.mode ?? 'merge')
const computer = kind === 'computer'
// A push's targets: this computer's DJ apps, each with why it cannot be used.
const locals = useQuery({
queryKey: ['local-libraries'],
queryFn: api.localLibraries,
enabled: computer,
})
const [browsing, setBrowsing] = useState(false)
const [busy, setBusy] = useState(false)
@@ -68,15 +85,29 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
on ? [...prev.filter((t) => t !== platform), platform] : prev.filter((t) => t !== platform),
)
const valid = name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
const pushable = new Set(
(locals.data?.libraries ?? []).filter((l) => !l.blocked).map((l) => l.platform),
)
const valid = computer
? name.trim() !== '' && chosen.length > 0 && chosen.every((t) => pushable.has(t))
: name.trim() !== '' && destination.trim() !== '' && chosen.length > 0
const chooseKind = (next: ExportSet['kind']) => {
setKind(next)
// The two kinds offer different platforms: start from the obvious one.
setChosen(['traktor'])
}
const save = async () => {
setBusy(true)
try {
const body = { name: name.trim(), targets: chosen, destination: destination.trim() }
const saved = editing
? await api.updateExport(editing.id, body)
: await api.createExport(body)
? await api.updateExport(editing.id, computer
? { name: name.trim(), targets: chosen, mode }
: { name: name.trim(), targets: chosen, destination: destination.trim() })
: await api.createExport(computer
? { name: name.trim(), targets: chosen, destination: '', kind, mode }
: { name: name.trim(), targets: chosen, destination: destination.trim() })
onSaved(saved, !editing)
} catch (e) {
onError((e as Error).message)
@@ -98,7 +129,7 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
<div className="w-full max-w-lg glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">
{editing ? `Edit “${editing.name}”` : 'New export'}
{editing ? `Edit “${editing.name}”` : computer ? 'New push to this computer' : 'New export'}
</h2>
</div>
@@ -117,6 +148,97 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
/>
</div>
{!editing && (
<div>
<span className="mb-1 block text-xs text-muted">Where</span>
<div className="grid grid-cols-2 gap-2">
{([
['folder', 'A folder or drive', 'Writes a library and a copy of the audio there — a USB stick for the gig.'],
['computer', 'This computer', 'Pushes into the Traktor or rekordbox you DJ with here.'],
] as const).map(([value, title, detail]) => (
<button
key={value}
onClick={() => chooseKind(value)}
aria-pressed={kind === value}
className={`rounded-lg px-3 py-2 text-left ${
kind === value ? 'is-selected well' : 'btn-glass'
}`}
>
<span className="block text-sm text-text">{title}</span>
<span className="mt-0.5 block text-[11px] leading-snug text-faint">{detail}</span>
</button>
))}
</div>
</div>
)}
{computer ? (
<>
<div>
<span className="mb-1 block text-xs text-muted">Into</span>
<div className="space-y-1">
{(locals.data?.libraries ?? []).map((lib) => {
const problem = localLibraryProblem(lib)
return (
<label
key={lib.platform}
className={`flex items-start gap-2 rounded-md px-2 py-1.5 ${
problem ? 'cursor-not-allowed' : 'cursor-pointer hover:bg-ink-850'
}`}
>
<input
type="checkbox"
disabled={!!problem}
checked={chosen.includes(lib.platform)}
onChange={(e) => toggle(lib.platform, e.target.checked)}
className="mt-0.5 accent-accent"
/>
<span className="min-w-0 flex-1">
<span className={problem ? 'text-faint' : 'text-text'}>{lib.name}</span>
<span
title={lib.path ?? undefined}
className="block truncate text-[11px] text-faint"
>
{problem ?? lib.path}
</span>
</span>
</label>
)
})}
</div>
<div className="mt-1 text-[11px] text-faint">
The audio is copied to{' '}
<span className="font-mono">{locals.data?.audio_root ?? '…'}</span>, shared by
every push. Change either in Settings → Local libraries.
</div>
</div>
<div>
<span className="mb-1 block text-xs text-muted">How</span>
<div className="space-y-1">
{([
['merge', 'Merge', 'Adds and updates this set’s tracks, in a folder named after it. Your own tracks and playlists are never touched.'],
['overwrite', 'Overwrite', 'Replaces the WHOLE library with this set. Everything else in it — your own tracks, playlists and other pushes — is removed.'],
] as const).map(([value, title, detail]) => (
<label key={value} className="flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 hover:bg-ink-850">
<input
type="radio"
name="push-mode"
checked={mode === value}
onChange={() => setMode(value)}
className="mt-0.5 accent-accent"
/>
<span>
<span className={value === 'overwrite' ? 'text-pink' : 'text-text'}>{title}</span>
<span className="block text-[11px] leading-snug text-faint">{detail}</span>
</span>
</label>
))}
</div>
</div>
</>
) : (
<>
<div>
<span className="mb-1 block text-xs text-muted">For</span>
<div className="space-y-1">
@@ -187,6 +309,8 @@ export function ExportDialog({ editing, onClose, onSaved, onError }: Props) {
</div>
)}
</div>
</>
)}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
+27 -6
View File
@@ -5,6 +5,7 @@ import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { ExportDialog } from './ExportDialog'
import { ExportRunDialog } from './ExportRunDialog'
import { PushRunDialog } from './PushRunDialog'
import type { Source } from './Sidebar'
import { askConfirm } from '../lib/confirm'
import { Icon } from '../lib/icons'
@@ -74,7 +75,16 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
/>
)}
{running && (
{running?.kind === 'computer' && (
<PushRunDialog
set={running}
onClose={() => setRunning(null)}
onDone={onDone}
onError={onError}
/>
)}
{running && running.kind !== 'computer' && (
<ExportRunDialog
set={running}
onClose={() => setRunning(null)}
@@ -118,7 +128,9 @@ export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign
if (
await askConfirm({
title: `Delete the export “${set.name}”?`,
body: 'Nothing already exported is removed — the files in its folder stay where they are.',
body: set.kind === 'computer'
? 'Nothing already pushed is removed — its tracks and playlists stay in your DJ apps.'
: 'Nothing already exported is removed — the files in its folder stay where they are.',
confirmLabel: 'Delete export',
})
)
@@ -257,8 +269,17 @@ function ExportRow({
onClick={() => onSelect({ kind: 'export', id: set.id, name: set.name })}
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm"
>
<span className="flex w-4 shrink-0 justify-center text-gold"><Icon name="export" size={14} /></span>
<span className="flex-1 truncate" title={set.destination}>
{/* A push into this computer's DJ apps reads differently from a
folder export at a glance: the target is this machine. */}
<span className="flex w-4 shrink-0 justify-center text-gold">
<Icon name={set.kind === 'computer' ? 'desktop' : 'export'} size={14} />
</span>
<span
className="flex-1 truncate"
title={set.kind === 'computer'
? `Pushed into this computer’s ${set.targets.join(' and ')} (${set.mode})`
: set.destination}
>
{set.name}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-faint">
@@ -266,7 +287,7 @@ function ExportRow({
</span>
</button>
<button
title="Edit name, platforms and destination"
title={set.kind === 'computer' ? 'Edit name, apps and how it pushes' : 'Edit name, platforms and destination'}
onClick={onEdit}
className="shrink-0 px-1 text-xs text-faint opacity-0 hover:text-text group-hover:opacity-100"
>
@@ -366,7 +387,7 @@ function ExportRow({
style={{ marginLeft: 24 }}
className="mb-1 mt-1 rounded-full btn-primary px-2 py-1 text-xs font-semibold"
>
Export {data.tracks} track{data.tracks === 1 ? '' : 's'}…
{set.kind === 'computer' ? 'Push' : 'Export'} {data.tracks} track{data.tracks === 1 ? '' : 's'}…
</button>
)}
</>
@@ -0,0 +1,205 @@
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type NormalizeOptions } from '../api'
import { localLibraryProblem } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
import { LevelInput, useAppSetting } from './AppSettings'
/**
* Settings → Local libraries: where a "This computer" set is pushed.
*
* This computer's, not the set's: a remote library's sets are kept on its
* server, but which Traktor collection and rekordbox library a laptop DJs from,
* and where their audio goes, belong to the laptop. So they are prefs —
* `localLibraries` ({platform: path | null}, null = detected), `localAudioRoot`,
* `localNormalise` and `localLevel`.
*
* The audio folder is SHARED by every push, so a file has one level: Normalise
* lives here rather than on a set. A library is chosen by its FOLDER (the
* `Traktor 4.x` folder, rekordbox's), the file in it being the platform's own.
*/
const LIBRARY_FILE: Record<string, string> = { traktor: 'collection.nml', rekordbox: 'master.db' }
export function LocalLibrariesSettings({ onClose }: { onClose: () => void }) {
const qc = useQueryClient()
const locals = useQuery({ queryKey: ['local-libraries'], queryFn: api.localLibraries })
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const defaultMeasure = useAppSetting('levelMeasure')
const defaultTarget = useAppSetting('levelTarget')
const defaultCeiling = useAppSetting('levelCeiling')
const [picking, setPicking] = useState<string | null>(null) // a platform, or 'audio'
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !picking && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose, picking])
const p = prefs.data ?? {}
const overrides = (p.localLibraries as Record<string, string | null> | undefined) ?? {}
const normalise = p.localNormalise === true
const stored = p.localLevel as Partial<NormalizeOptions> | undefined
const level: NormalizeOptions = {
measure: stored?.measure ?? defaultMeasure,
target: stored?.target ?? defaultTarget,
ceiling: stored?.ceiling ?? defaultCeiling,
}
const patch = async (body: Record<string, unknown>) => {
setError(null)
try {
qc.setQueryData(['prefs'], await api.patchPrefs(body))
qc.invalidateQueries({ queryKey: ['local-libraries'] })
qc.invalidateQueries({ queryKey: ['push-preview'] })
} catch (e) {
setError((e as Error).message)
}
}
const choose = (folder: string) => {
if (picking === 'audio') {
patch({ localAudioRoot: folder })
} else if (picking) {
const sep = folder.includes('\\') && !folder.includes('/') ? '\\' : '/'
patch({ localLibraries: { ...overrides, [picking]: `${folder.replace(/[\\/]+$/, '')}${sep}${LIBRARY_FILE[picking]}` } })
}
}
const d = locals.data
const pickerValue =
picking === 'audio'
? d?.audio_root ?? ''
: (d?.libraries.find((l) => l.platform === picking)?.path ?? '').replace(/[\\/][^\\/]*$/, '')
return createPortal(
<>
{picking && (
<FolderPicker value={pickerValue} onChange={choose} onClose={() => setPicking(null)} />
)}
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onClick={onClose}
>
<div className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Local libraries</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
<div className="min-h-0 space-y-5 overflow-y-auto px-5 py-4 text-sm">
<p className="text-muted">
Where an export set made for <span className="text-text">This computer</span> is pushed:
the DJ apps you play from here, and one folder for their audio.
</p>
<section className="space-y-2">
<h3 className="text-[11px] uppercase tracking-wider text-faint">DJ apps</h3>
{(d?.libraries ?? []).map((lib) => {
const problem = lib.blocked === 'open_in_konduktor' ? null : localLibraryProblem(lib)
return (
<div key={lib.platform} className="rounded-md well px-3 py-2">
<div className="flex items-center gap-2">
<span className="text-text">{lib.name}</span>
<span className="text-[11px] text-faint">{lib.detected ? 'found automatically' : 'chosen'}</span>
<span className="ml-auto flex gap-1">
{!lib.detected && (
<button
onClick={() => patch({ localLibraries: { ...overrides, [lib.platform]: null } })}
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
>
Find automatically
</button>
)}
<button
onClick={() => setPicking(lib.platform)}
className="btn-glass rounded-full px-2.5 py-0.5 text-xs text-muted hover:text-text"
>
Change…
</button>
</span>
</div>
<div title={lib.path ?? undefined} className="mt-0.5 truncate font-mono text-[11px] text-faint">
{lib.path ?? '—'}
</div>
{problem && <div className="mt-0.5 text-[11px] text-pink">{problem}</div>}
</div>
)
})}
</section>
<section className="space-y-2">
<h3 className="text-[11px] uppercase tracking-wider text-faint">Audio folder</h3>
<div className="flex items-center gap-2">
<span title={d?.audio_root} dir="rtl"
className="min-w-0 flex-1 truncate rounded-md well px-2 py-1.5 text-left font-mono text-xs text-text">
{d?.audio_root ?? '…'}
</span>
{d && d.audio_root !== d.audio_root_default && (
<button onClick={() => patch({ localAudioRoot: null })}
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
Reset
</button>
)}
<button onClick={() => setPicking('audio')}
className="shrink-0 btn-glass rounded-full px-2.5 py-1 text-xs text-muted hover:text-text">
Change…
</button>
</div>
<p className="text-[11px] text-faint">
Every push copies its tracks here, once each, however many sets or apps use them. A
file no push uses any more is deleted. Changing the folder copies everything again
on the next push.
</p>
</section>
<section className="space-y-2">
<h3 className="text-[11px] uppercase tracking-wider text-faint">Level</h3>
<label className="flex cursor-pointer items-start gap-2.5">
<input type="checkbox" className="mt-0.5" checked={normalise}
onChange={(e) => patch({ localNormalise: e.target.checked })} />
<span>
<span className="block text-text">Normalise audio</span>
<span className="block text-xs text-faint">
Brings the copies to one level. Your own files are never changed.
</span>
</span>
</label>
{normalise && (
<div className="ml-6 space-y-1.5 text-xs">
<div className="flex items-center justify-between gap-3">
<span className="text-muted">Level by</span>
<select
className="rounded-lg well px-2 py-1 text-xs text-text outline-none"
value={level.measure}
onChange={(e) => patch({ localLevel: { ...level, measure: e.target.value } })}
>
<option value="lufs">LUFS</option>
<option value="rms">RMS (loudest sections)</option>
</select>
</div>
<div className="flex items-center justify-between gap-3">
<span className="text-muted">Target</span>
<LevelInput value={level.target} unit={level.measure === 'lufs' ? 'LUFS' : 'dB'} min={-30} max={0}
onCommit={(v) => patch({ localLevel: { ...level, target: v } })} />
</div>
<div className="flex items-center justify-between gap-3">
<span className="text-muted" title="A raise stops here, so nothing clips">Peak ceiling</span>
<LevelInput value={level.ceiling} unit="dBTP" min={-12} max={0}
onCommit={(v) => patch({ localLevel: { ...level, ceiling: v } })} />
</div>
</div>
)}
</section>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
</div>
</div>
</>,
document.body,
)
}
+358
View File
@@ -0,0 +1,358 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ExportRunOptions, type ExportSet, type JobStatus, type PushPreview, type PushTarget } from '../api'
import { askConfirm } from '../lib/confirm'
import { localLibraryProblem } from '../lib/platformCopy'
/**
* Push a "computer" set into this computer's Traktor / rekordbox: confirm what
* is about to happen, then watch it happen. The sibling of `ExportRunDialog`,
* with the same rule — the preview takes the same body as the run, and is
* fetched fresh every time, never cached: the set's references are live.
*
* A running DJ app BLOCKS the push (Traktor writes its collection back when it
* quits, undoing it), and the preview re-checks every two seconds while it does,
* so quitting the app is all it takes. Overwrite is confirmed once more, naming
* the other pushes it removes. Normalise is not here: the pushed files are
* shared by every set, so their level is a setting (Settings → Local libraries).
*/
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`
}
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
interface Props {
set: ExportSet
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
interface TargetResult {
name: string
added: number
updated: number
removed: number
kept: string[]
replaced?: boolean
}
export function PushRunDialog({ set, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false)
// Remembered on the set, sent with the click, as an export's are.
const [lockGrids, setLockGrids] = useState(set.lock_grids ?? true)
const [autoGain, setAutoGain] = useState(set.auto_gain ?? true)
const pollRef = useRef<number | null>(null)
const options: ExportRunOptions = { lock_grids: lockGrids, auto_gain: autoGain }
const overwrite = set.mode === 'overwrite'
const preview = useQuery<PushPreview>({
queryKey: ['push-preview', set.id, options],
queryFn: () => api.pushPreview(set.id, options),
enabled: !job,
staleTime: 0,
gcTime: 0,
// Quitting the DJ app is the fix for the commonest block: notice it.
refetchInterval: (q) => (q.state.data?.blocked === 'app_running' ? 2000 : false),
})
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') {
qc.invalidateQueries({ queryKey: ['local-libraries'] })
onDone(doneMessage(set.name, next.result))
} else if (next.state === 'failed') {
onError(next.error || 'Push 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, set.name, onDone, onError])
const p = preview.data
const blocked = p?.blocked ?? null
const start = async () => {
if (overwrite && p) {
const wiped = p.targets.flatMap((t) => t.wipes_sets)
const ok = await askConfirm({
title: `Replace ${p.targets.map((t) => t.name).join(' and ')}’s library?`,
body:
`Everything in it is replaced by “${set.name}” — your own tracks and playlists too` +
(wiped.length ? `, and the pushes of ${wiped.map((n) => `“${n}”`).join(', ')}` : '') +
'. A backup is kept, but the DJ app will only show this set.',
confirmLabel: 'Replace',
})
if (!ok) return
}
setStarting(true)
try {
setJob(await api.runPush(set.id, options))
qc.invalidateQueries({ queryKey: ['exports'] })
} 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 running = job?.state === 'running'
const finished = job != null && job.state !== 'running'
const pct =
job?.state === 'done' ? 100 : job && job.total > 0 ? Math.min(100, (job.done / job.total) * 100) : null
const results = ((job?.result as { targets?: TargetResult[] } | null)?.targets ?? [])
return createPortal(
<div aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-4">
<div className="w-full max-w-lg glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">
{overwrite ? 'Replace with' : 'Push'} “{set.name}”
</h2>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
{preview.isLoading && <div className="text-faint">Checking…</div>}
{preview.isError && <div className="text-pink">{(preview.error as Error).message}</div>}
{p && (
<div className="space-y-1.5">
{p.targets.map((t) => (
<TargetLine key={t.platform} target={t} overwrite={overwrite} />
))}
</div>
)}
{p && blocked !== 'nothing_to_push' && (
<div className="space-y-2">
<div className="text-text">
{plural(p.pushable, 'track')}
{p.playlists.length > 0 && ` · ${plural(p.playlists.length, 'playlist')}`}
<span className="text-muted">
{p.unchanged > 0 && ` · ${p.unchanged} already copied`} · {gb(p.total_bytes)} to copy
</span>
</div>
<div className="text-xs text-faint">
Into <span className="font-mono">{p.audio_root}</span>
{p.free_bytes != null && (
<span className={p.enough_space === false ? 'text-pink' : ''}>
{' '}· {gb(p.free_bytes)} free{p.enough_space === false && ' — not enough space'}
</span>
)}
</div>
{p.missing.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-pink">
{plural(p.missing.length, 'track')} will be skipped — the audio file is not on this disk:
<div className="mt-1 text-faint">{p.missing.slice(0, 4).join(', ')}</div>
</div>
)}
{overwrite && p.targets.some((t) => t.wipes_sets.length) && (
<div className="rounded well px-3 py-2 text-xs text-gold">
Also removes what{' '}
{[...new Set(p.targets.flatMap((t) => t.wipes_sets))].map((n) => `“${n}”`).join(', ')}{' '}
pushed there, and deletes its files.
</div>
)}
{p.targets.some((t) => t.platform === 'traktor') && (
<label className="flex cursor-pointer items-start gap-2.5">
<input type="checkbox" className="mt-0.5" checked={lockGrids}
onChange={(e) => setLockGrids(e.target.checked)} />
<span className="min-w-0">
<span className="block text-sm text-text">Lock beatgrids</span>
<span className="block text-xs text-faint">
Stops Traktor re-analysing the tracks when they’re loaded, which can change the
BPM or move the grid.
</span>
</span>
</label>
)}
<label className="flex cursor-pointer items-start gap-2.5">
<input type="checkbox" className="mt-0.5" checked={autoGain}
onChange={(e) => setAutoGain(e.target.checked)} />
<span className="min-w-0">
<span className="block text-sm text-text">Auto gain</span>
<span className="block text-xs text-faint">
Sets each track’s auto gain from its loudness, so tracks load at matching levels.
</span>
</span>
</label>
<div className="text-xs text-faint">
{p.normalised > 0
? `${plural(p.normalised, 'copy', 'copies')} brought to the shared level. `
: ''}
Normalising is set for all pushes in Settings → Local libraries.
</div>
{p.to_measure > 0 && (
<div className="text-xs text-faint">
{plural(p.to_measure, 'track')} measured first (about a second each).
</div>
)}
</div>
)}
{blocked === 'app_running' && (
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
Quit {p!.targets.filter((t) => t.running).map((t) => t.name).join(' and ')} to push —
it would overwrite the push when it next saves its library.
</div>
)}
{blocked === 'target_unavailable' && (
<div className="rounded border border-pink/40 bg-well px-3 py-2 text-xs text-pink">
Konduktor can’t push into every library this set is for. Check Settings → Local
libraries, or edit the set.
</div>
)}
{blocked === 'nothing_to_push' && p && (
<div className={`rounded well px-3 py-2 text-xs ${p.tracks ? 'text-pink' : 'text-muted'}`}>
{p.tracks === 0
? 'There’s nothing to push yet — add some tracks or a playlist.'
: `None of the ${plural(p.tracks, 'track')} can be pushed — their audio files are not on this disk.`}
</div>
)}
</>
)}
{job && (
<div className="space-y-3">
<div className="text-text">{job.state === 'done' ? 'Pushed.' : job.message || 'Working…'}</div>
<div className="h-2 overflow-hidden rounded-full bg-well">
<div
className={`h-full transition-[width] duration-200 ${job.state === 'failed' ? 'bg-pink' : 'bg-accent'} ${
pct == null ? 'w-1/3 animate-pulse' : ''
}`}
style={pct == null ? undefined : { width: `${pct}%` }}
/>
</div>
{pct != null && running && job.unit === 'bytes' && (
<div className="text-xs text-faint">{gb(job.done)} of {gb(job.total)}</div>
)}
{job.state === 'cancelled' && (
<div className="text-xs text-muted">
Cancelled. A library already saved keeps the push; any other was left as it was.
</div>
)}
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
{job.state === 'done' &&
results.map((r) => (
<div key={r.name} className="space-y-0.5 text-xs">
<div className="text-mint">{resultLine(r)}</div>
{r.kept.length > 0 && (
<div className="text-gold">
Left in {r.name}: {r.kept.slice(0, 4).join(', ')}
{r.kept.length > 4 && ` and ${r.kept.length - 4} more`} — {r.name} still lists
them in its History, Sampler or another list, so they stay. The next push tries
again.
</div>
)}
</div>
))}
</div>
)}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
{running ? (
<>
<button onClick={cancel} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
Cancel push
</button>
<button onClick={onClose} className="rounded-md px-3 py-1.5 text-sm text-faint hover:text-text"
title="The push keeps running">
Hide
</button>
</>
) : (
<>
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
{finished ? 'Close' : 'Cancel'}
</button>
{!finished && (
<button
disabled={starting || preview.isFetching || !p || !!blocked || p.enough_space === false}
onClick={start}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold disabled:opacity-40"
>
{starting ? 'Starting…' : overwrite ? 'Replace' : `Push ${p && !blocked ? p.pushable : ''}`.trim()}
</button>
)}
</>
)}
</div>
</div>
</div>,
document.body,
)
}
function TargetLine({ target, overwrite }: { target: PushTarget; overwrite: boolean }) {
const problem = localLibraryProblem({ ...target, detected: true })
const counts = overwrite
? 'replaced by this set'
: [
target.add && `${target.add} to add`,
target.already && `${target.already} already there`,
target.remove && `${target.remove} to remove`,
].filter(Boolean).join(' · ') || 'nothing to change'
return (
<div className="rounded-md well px-3 py-2">
<div className="flex items-baseline gap-2">
<span className="text-text">{target.name}</span>
<span className={`ml-auto text-xs ${problem || target.running ? 'text-pink' : 'text-muted'}`}>
{problem ?? (target.running ? 'running' : counts)}
</span>
</div>
{target.path && (
<div title={target.path} dir="rtl" className="truncate text-left font-mono text-[11px] text-faint">
{target.path}
</div>
)}
</div>
)
}
function resultLine(r: TargetResult): string {
if (r.replaced) return `${r.name}: replaced — ${plural(r.added, 'track')}`
const parts = [
r.added && `${r.added} added`,
r.updated && `${r.updated} updated`,
r.removed && `${r.removed} removed`,
].filter(Boolean)
return `${r.name}: ${parts.length ? parts.join(', ') : 'already up to date'}`
}
function doneMessage(name: string, result: Record<string, unknown> | null): string {
const targets = ((result as { targets?: TargetResult[] } | null)?.targets ?? []).map((t) => t.name)
return `Pushed “${name}” into ${targets.join(' and ') || 'this computer'}`
}
+13
View File
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { AppSettings } from './AppSettings'
import { useCaps } from '../lib/capabilities'
import { LocalLibrariesSettings } from './LocalLibrariesSettings'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog'
import { StemsSettings } from './StemsSettings'
@@ -22,6 +23,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [showStems, setShowStems] = useState(false)
const [showCache, setShowCache] = useState(false)
const [showApp, setShowApp] = useState(false)
const [showLocal, setShowLocal] = useState(false)
const ref = useRef<HTMLDivElement>(null)
// Path remapping is a library on THIS computer's business; a remote's
// mapping is its server's configuration.
@@ -123,6 +125,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
</button>
)}
<button
onClick={() => {
setShowLocal(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">Local libraries…</span>
<span className="text-[11px] text-faint">The Traktor and rekordbox a set is pushed into</span>
</button>
<button
onClick={() => {
setShowStems(true)
@@ -149,6 +161,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
{showLocal && <LocalLibrariesSettings onClose={() => setShowLocal(false)} />}
</div>
)
}
+19 -1
View File
@@ -6,7 +6,7 @@
* staying genuinely specific — the pre-save warning is a real, per-platform
* hazard and must not be watered down into something vague.
*/
import type { Capabilities, PlatformOption, SaveCapabilities } from '../api'
import type { Capabilities, LocalLibrary, PlatformOption, SaveCapabilities } from '../api'
export function saveLabel(save: SaveCapabilities): string {
return `Save to ${save.app_name}`
@@ -155,3 +155,21 @@ export function remoteHolder(machine: string | null, since: string | null, batch
const running = batch ? ` — ${what[batch] ?? 'a batch'} is running there, and taking over cancels it` : ''
return `${who}${when ? ` has had it open since ${when}` : ' has it open'}${running}.`
}
/** Why a DJ app's library on this computer cannot be pushed into, or null. */
export function localLibraryProblem(lib: LocalLibrary): string | null {
switch (lib.blocked) {
case null:
return null
case 'not_found':
return lib.path
? `No ${lib.name} library at ${lib.path}`
: `No ${lib.name} library found on this computer`
case 'open_in_konduktor':
return `This is the library open in Konduktor — open another one to push into it`
case 'cloud_synced':
return `Synced with ${lib.name} Cloud, so Konduktor will not write to it`
case 'unreadable':
return `Konduktor cannot read this ${lib.name} library`
}
}