Files
konduktor/frontend/src/api.ts
T

1422 lines
55 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Typed client for the Konduktor backend (Phase 1 read-only API).
export interface Track {
id: string
artist: string | null
title: string | null
album: string | null
genre: string | null
label: string | null
remixer: string | null
producer: string | null
mix: string | null
comment: string | null
/** A second free-text comment (Traktor's "Comment 2"). */
comment2: string | null
bpm: number | null
/** The platform's own display string, shown verbatim: "10m", "8A", "Am". */
key: string | null
/** Camelot wheel position 1-12 + mode, parsed by the ADAPTER — notation is
* platform knowledge, not display formatting. Null when unparseable. */
key_wheel: number | null
key_mode: 'major' | 'minor' | null
rating: number
playcount: number | null
length: number | null
bitrate: number | null
/** ISO-8601 "YYYY-MM-DD", normalised by the adapter. */
import_date: string | null
last_played: string | null
release_date: string | null
filepath: string | null
cue_count: number
hotcue_count: number
/** The occupied hotcue slots, ordered by slot — what the table's Cues column
* draws as dots. Empty until corrected where cues load lazily (OneLibrary),
* exactly like `hotcue_count`. */
hotcues: HotcueChip[]
/** 0 = no beatgrid, 1 = constant tempo, >1 = a flexible (multi-tempo) grid. */
grid_marker_count: number
grid_locked: boolean
media_kind: MediaKind
/** The track's colour tag — the platform-neutral identity — and the
* library's own display colour for it; both null when uncoloured. */
color: TrackColor | null
color_hex: string | null
/** The DJ app's own auto gain in dB (Traktor's deck gain, rekordbox's Auto
* Gain); null = the track has none. */
auto_gain_db: number | null
/** The Mastering columns' values — NOT part of the backend's `Track`: joined
* in client-side from `/api/loudness` (Konduktor's own store, keyed by the
* FILE), and only while a Mastering column is shown. Absent = unmeasured. */
loudness?: Loudness
}
/** One file's loudness (`core/loudness.py`): integrated LUFS, RMS of the
* loudest 3 s blocks (dB, AES17), true peak (dBTP), loudness range (LU) and
* PLR (true peak − LUFS, dB). `stale`: the file changed since it was measured
* — shown dimmed, still sorted on. */
export interface Loudness {
lufs: number
rms: number
true_peak: number
lra: number
plr: number
stale: boolean
}
/** One occupied hotcue slot, as the library table previews it. */
export interface HotcueChip {
slot: number
type: CueType
color: string | null // "#RRGGBB" as the platform stored it
}
export interface TrackPage {
total: number
offset: number
limit: number
items: Track[]
}
export interface GenreCount {
name: string
count: number
}
export interface Facets {
genres: GenreCount[]
keys: GenreCount[]
bpm_min: number | null
bpm_max: number | null
total_tracks: number
}
export interface PlaylistNode {
/** Opaque, adapter-minted. The UI never constructs, parses or prefixes it. */
id: string
name: string
/** For choosing an icon only — every behavioural question is answered by the
* flags below, so the UI never infers what a node can do from its kind. */
kind: PlaylistKind
count: number
children: PlaylistNode[]
selectable: boolean
can_add_tracks: boolean
can_reorder: boolean
can_rename: boolean
can_delete: boolean
can_contain_children: boolean
/** Can be dragged elsewhere in the tree (reordered, or into a folder). */
can_move: boolean
}
export type SortField =
| 'artist'
| 'title'
| 'album'
| 'genre'
| 'key'
| 'bpm'
| 'rating'
| 'playcount'
| 'import_date'
| 'length'
export interface TrackQuery {
q?: string
genre?: string
key?: string
bpm_min?: number
bpm_max?: number
rating_min?: number
has_cues?: boolean
sort?: SortField
order?: 'asc' | 'desc'
limit?: number
offset?: number
}
export type Platform = string
export type CueRole = 'hotcue' | 'memory'
export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop'
export type MediaKind = 'audio' | 'stem' | 'video'
/** A track colour tag; each library maps its own palette onto these by name. */
export type TrackColor = 'pink' | 'red' | 'orange' | 'yellow' | 'green' | 'aqua' | 'blue' | 'purple'
/** One track colour a library offers, in its own menu order. */
export interface ColorSwatch {
color: TrackColor
hex: string
/** The platform's own name for it ("Violet" in Traktor). */
label: string
}
export type PlaylistKind = 'folder' | 'playlist' | 'smart'
export type TrackField =
| 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer'
| 'producer' | 'mix' | 'release_date' | 'comment' | 'comment2' | 'rating'
export interface CuePoint {
name: string | null
type: CueType
/** A memory cue has no bank slot (Rekordbox / OneLibrary memory cues,
* Traktor's cues on no pad) and is addressed by `id`, not `slot`. */
role: CueRole
start: number // seconds
length: number // seconds (>0 for loops)
slot: number | null // bank slot; null for a cue not in a bank
color: string | null // "#RRGGBB" as the platform stored it
/** False when the adapter refuses commands on this cue. Gate on THIS, never
* on a platform-specific reason like grid_marker. */
editable: boolean
readonly_reason: 'platform_managed' | null
/** Index of the grid marker this cue mirrors, where the platform pairs them.
* A display hint only; null on platforms that do not. */
grid_marker: number | null
/** The handle the memory-cue commands take; null on a hot cue (addressed by
* slot). Opaque, and may change when THIS cue is edited — always use the
* fresh TrackCues a command returns. */
id: string | null
}
/** One beatgrid marker. Its position in the list IS its index/identity. */
export interface GridMarker {
start: number // seconds
bpm: number // governs from this marker until the next one
name: string | null // Traktor's label — display only, NOT a discriminator
companion: number | null // hotcue slot of the paired white cue, if any
}
export interface TrackCues {
/**
* The beatgrid, ordered by start. Empty = no grid, one marker = constant
* tempo, more = a flexible (multi-tempo) grid. There is deliberately no
* scalar bpm/anchor: assuming a single tempo is what made flexible grids
* render and edit wrongly.
*/
grid_markers: GridMarker[]
grid_locked: boolean
cues: CuePoint[]
}
/** A structural event an Auto Hotcues slot can be bound to (`core/structure.py`
* EVENTS; keep in lockstep with `schemas.AutoCueEvent`). */
export type AutoCueEvent =
| 'first_beat' | 'intro_end'
| 'build_1' | 'drop_1' | 'breakdown_1'
| 'build_2' | 'drop_2' | 'breakdown_2'
| 'build_3' | 'drop_3' | 'breakdown_3'
| 'outro' | 'last_beat'
export interface AutoCueSlot {
slot: number
event: AutoCueEvent
offset_beats: number
/** Replace a cue already in this slot. */
overwrite: boolean
}
/** What happened to one requested slot. `not_found`: the track has no such
* event (e.g. no third drop); `out_of_range`: the offset moves it outside the
* track; `occupied`: a cue is there and overwrite was off; `protected`: a cue
* the adapter will not replace (a grid marker's); `duplicate`: that beat
* already has a cue — one kept in the bank (the grid cue, a hand-placed cue)
* or a new one in a lower slot — whose slot is `duplicate_of`. */
export type AutoCueStatus =
| 'placed' | 'not_found' | 'out_of_range' | 'occupied' | 'protected' | 'duplicate'
export interface AutoCueOutcome {
slot: number
event: AutoCueEvent
status: AutoCueStatus
start: number | null
name: string | null
duplicate_of: number | null
}
export interface AutoHotcuesResult {
cues: TrackCues
outcomes: AutoCueOutcome[]
}
export interface CueCapabilities {
/** Whether cues can be created or changed. Symmetric with grid.editable: a
* platform can be writable overall while its cue store is not implemented. */
editable: boolean
hotcue_slots: number
slot_labels: 'number' | 'letter'
memory_cues: boolean
/** Per track; null = no limit. rekordbox stops at 10 without saying so. */
max_memory_cues: number | null
/** A memory cue's colours are its own palette, not `palette`. */
memory_color: 'none' | 'palette'
memory_palette: string[]
types: CueType[]
color: 'none' | 'free' | 'palette'
palette: string[]
named: boolean
loops: 'none' | 'cue_type' | 'separate_bank'
loop_slots: number | null
}
export interface SaveCapabilities {
/** Structured facts, never finished sentences — the UI composes the wording
* (see lib/platformCopy.ts) so it stays specific without being hard-coded. */
app_name: string
library_label: string
overwrite_risk: 'none' | 'on_exit' | 'while_running'
history: boolean
/** Written by a Konduktor export set, whose next run replaces it. */
managed_by_export: boolean
}
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
export type ReadonlyCause =
| 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
/** A library held by a server: another computer took it over / the server is unreachable. */
| 'taken_over' | 'offline'
export interface Capabilities {
platform: Platform
version: string | null
/** Whether ANY edit can be persisted.
*
* Deliberately not the same as every per-feature flag being false: "the
* platform has no such feature" and "this library cannot be written at all"
* look identical to a UI that only sees the per-feature flags, and silently
* inert controls read as a bug. Gate edit affordances on this AND on the
* per-feature flag. */
writable: boolean
readonly_cause: ReadonlyCause | null
cues: CueCapabilities
grid: { editable: boolean; flexible: boolean; lockable: boolean }
tracks: {
rating_max: number
editable_fields: TrackField[]
media_kinds: MediaKind[]
/** Tracks can be removed from the library (audio files are never touched). */
removable: boolean
/** Tracks can be added to the library (import, add browsed files). */
addable: boolean
/** The library decides where added audio goes — no copy/in-place question. */
places_audio: boolean
/** Tracks can be converted to native-instruments STEM files. */
stem_convertible: boolean
/** The musical key can be set — what key analysis writes. */
key_writable: boolean
/** Lower-case suffixes this library can hold — what a browsed folder lists. */
audio_formats: string[]
artwork: boolean
artwork_note: string | null
/** Whose filesystem an import destination is on: this computer's ('host'),
* or the machine holding the library ('library' — audio is uploaded). */
audio_destination: 'host' | 'library'
/** Added files can be left where they are rather than copied. */
reference: boolean
/** The track colours this library can store; empty = no track colour. */
colors: ColorSwatch[]
/** The library keeps a per-track auto gain (`Track.auto_gain_db`). */
auto_gain: boolean
/** Tracks' files can be normalized in place (`audio_changed`). */
normalizable: boolean
}
playlists: {
folders: boolean
smart: 'none' | 'read_only'
reorder: boolean
/** A playlist can hold the same track twice (else duplicates are skipped). */
duplicates: boolean
}
/** Path mapping / rewriting / the missing-files check apply to this library. */
paths: { remappable: boolean }
save: SaveCapabilities
}
export interface LibraryInfo {
platform: Platform
name: string // the DJ app's name, e.g. "Traktor"
library_label: string // e.g. "collection.nml"
path: string
display_name: string
version: string | null
/** Set when the library is held by a server (a saved remote). */
remote: { id: string; name: string; via: string | null } | null
}
export interface PlatformOption {
platform: Platform
name: string
library_label: string
/** Whether picking this platform's library means picking a file or a folder. */
selects: 'file' | 'directory' | 'remote'
installed: boolean
/** How many libraries this platform has right now; `installed` is `found > 0`. */
found: number
/** The library lives on plugged-in media, so `found` changes between calls —
* and `found === 0` means "nothing plugged in", not "not installed". */
removable: boolean
/** As an export target: its library is only found at a drive's ROOT. */
drive_root?: boolean
/** As an export target: only ever read on a computer, never from a drive. */
computer_only?: boolean
/** As an export target: its library can store a grid lock. */
locks_grids?: boolean
}
export interface EditState {
dirty: boolean
library: LibraryInfo
/** Converted-to-stem tracks awaiting Save or Discard (parked originals). */
pending_stems: { tracks: number; parked: number; bytes: number } | null
/** A running stem conversion's job id, so a reloaded page can find it. */
stem_job: string | null
/** What this open's crash recovery did about an interrupted conversion. */
stem_recovery: { committed: number; restored: number; kept: number } | null
/** Normalized tracks awaiting Save or Discard; `lossless` = files whose
* change Save makes permanent. */
pending_gain: { tracks: number; lossless: number } | null
/** A running Normalize's job id, so a reloaded page can find it. */
normalize_job: string | null
/** A remote library's connection, null for a local one. */
remote: RemoteConnection | null
}
/** How this computer stands with a remote library's server. `taken_over`:
* another computer holds the session, so this one is read-only. */
export interface RemoteConnection {
state: 'connected' | 'reconnecting' | 'offline' | 'taken_over'
/** The address in use ('primary' / 'fallback'), when connected. */
via: 'primary' | 'fallback' | null
/** Who took it over, when `taken_over`. */
machine: string | null
/** Something to tell the user once ("the server restarted"), with a counter
* that changes each time there is a new one. */
notice: string | null
notices: number
}
export interface CollectionStatus {
loaded: boolean
path: string | null
library: LibraryInfo | null
tracks: number | null
playlists: number | null
/** Opening a remote: the unsaved edits another computer left there. */
pending_edits?: PendingEdits | null
}
/** Unsaved edits a remote library holds that another computer made. */
export interface PendingEdits {
machine: string | null
summary: string
}
/** A saved remote — a Konduktor server this computer knows how to reach. The
* password is in the OS keychain, never here. */
export interface RemoteSettings {
id: string
name: string
host: string
port: number | null
fallback_host: string | null
fallback_port: number | null
username: string
has_password: boolean
}
export interface RemoteForm {
name: string
/** `host` or `host:port`. */
host: string
fallback_host?: string | null
username: string
/** Omitted on an edit: keep the saved one. */
password?: string
}
/** One address's answer to a handshake. */
export interface HandshakeResult {
address: 'primary' | 'fallback'
url: string
ok: boolean
error: string | null
kind: 'ok' | 'unreachable' | 'auth' | 'version' | 'other'
}
/** Someone else holds a remote's session (409 from open-remote). */
export interface RemoteInUse {
code: 'in_use'
machine: string
since: string
batch: string | null
}
export interface RemoteCacheUsage {
bytes: number
files: number
cap: number
free: number
}
export interface CollectionCandidate {
path: string
label: string
version: string | null
modified: number | null // epoch seconds
exists: boolean
}
export interface CollectionOptions {
auto: CollectionCandidate | null // best auto-detected; the first of `detected`
/** EVERY library detected for the platform, best first. One platform can
* genuinely have several at once — two Traktor versions, two sticks — and
* the picker offers the choice rather than anointing one. */
detected: CollectionCandidate[]
recent: CollectionCandidate | null // last opened (may no longer exist)
}
// ---- import sources ----
//
// A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
// tracks are about to be imported — open alongside the loaded collection. It is
// deliberately NOT a CollectionStatus: a source is never saved, never edited and
// never the fallback when nothing is loaded, and sharing a type would invite
// components to treat the two as interchangeable.
// ---- import ----
//
// Import is the only operation that can run for minutes, so it is the only one
// that is a JOB rather than a request: start it, then poll the job.
export interface ImportRequest {
/** Folder the audio is copied into. */
destination: string
/** Empty track_ids AND empty playlist_ids means the whole drive. */
track_ids?: string[]
playlist_ids?: string[]
/** Playlists land in a folder named this; null keeps them at the root. */
folder_name?: string | null
/** Every imported track (and any already held) also goes into this
* collection playlist / export — a drop of device tracks on one. */
into_playlist?: string | null
/** Where in it (a drop between rows); null appends. */
into_playlist_index?: number | null
export_id?: string | null
}
export interface ImportPreview {
tracks: number
importable: number
/** Titles whose audio file is not there — reported, then skipped. */
missing: string[]
/** Titles the collection already has by filename. A warning, not a block. */
duplicates: string[]
/** Titles whose exact FILE the collection already holds: not added again,
* but still put in the playlist/export being added to. */
existing: string[]
playlists: string[]
total_bytes: number
destination: string | null
free_bytes: number | null
enough_space: boolean | null
/** Set when the library places its own audio (`tracks.places_audio`): how
* many files will be copied onto it, and how many are already there. */
places_audio?: boolean
copied?: number
in_place?: number
}
// ---- drives and folders ----
//
// The sidebar's Devices and Local Storage trees. A browsed folder is read-only
// and is not a library: its files are projected as tracks (id = absolute path)
// so the ordinary table and deck show them, and adding goes through import.
export interface Drive {
name: string
path: string
/** `local` = boot disk or a drive built in; anything uncertain is external.
* `server` = a remote library's content folder (path `server:`). */
kind: 'local' | 'external' | 'server'
/** The OneLibrary library on this drive, if it carries one. */
library: SourceCandidate | null
}
/** A path in a remote library's content folder, as the Files routes take it:
* `server:` + the path ON THE SERVER, so it cannot be taken for the same
* path on this computer. Such files are already where the library can reach
* them, so adding one never copies or uploads it. */
export const isServerPath = (path: string) => path.startsWith('server:')
export interface FolderTracks {
path: string
tracks: Track[]
/** Collection ids of the rows that ARE collection tracks: a file the
* collection holds is listed as its track (id, key, rating, cues…), so it
* plays, edits and drags as one. Any other file is its own tags, id = path. */
in_collection: string[]
/** Those rows' collection id → the file's folder id, which adding takes. */
files: Record<string, string>
/** On an external drive — referencing in place would go missing on unplug. */
removable: boolean
}
export interface FolderAddRequest {
track_ids: string[]
mode: 'copy' | 'reference'
/** Required for `copy`. */
destination?: string | null
playlist_id?: string | null
/** Where in it (a drop between rows); null appends. */
playlist_index?: number | null
export_id?: string | null
}
export interface FolderAddPreview extends ImportPreview {
/** Some of the files to add are on an external drive. */
removable: boolean
/** How many, and on which drives — per FILE, since a drop can mix drives. */
removable_count?: number
removable_drives?: string[]
/** Copy mode: files already inside the import folder (copying makes a
* second copy beside them). */
in_destination?: number
}
/** What files dropped onto the window from the OS resolved to: the audio in
* them (folders searched all the way down), listed as a folder lists its
* files — a file the collection holds is its collection track. */
export interface DroppedFiles {
tracks: Track[]
/** Collection id → the file's folder id (= its path), for held rows. */
files: Record<string, string>
/** Dropped files that are not audio this library can hold, or are gone. */
skipped: number
/** Too many files: only the first 20,000 are included. */
truncated: boolean
}
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
export interface JobStatus {
id: string
kind: string
state: JobState
/** 0 until the job knows its size — show an indeterminate bar until positive. */
total: number
done: number
/** What done/total count: 'bytes' while copying, 'tracks' while a library
* is written; '' when unspecified. */
unit: string
message: string
/** The CURRENT item's own progress, 0..1 — so the overall bar moves within
* a long item. Resets as each item starts. */
fraction: number
/** What the current item is doing, e.g. "separating 41 %". */
status: string
result: Record<string, unknown> | null
error: string | null
started_at: number
finished_at: number | null
}
/** What the Analyze dialog asks for. BPM and Grid are independent halves of
* a beatgrid: BPM alone keeps the downbeat, Grid alone keeps the tempo.
* `replace_grid` only guards a FULL re-analysis (both ticked). Loudness goes
* to Konduktor's own store, so it works for any `origin`; BPM / Grid / Key
* only for the loaded library's tracks. */
export interface AnalyzeOptions {
bpm: boolean
grid: boolean
key: boolean
loudness: boolean
/** Write the DJ app's auto gain from the loudness (measured first if needed). */
gain: boolean
replace_grid: boolean
replace_key: boolean
replace_loudness: boolean
replace_gain: boolean
origin: TrackOrigin
}
/** What an Analyze run WOULD do — the backend's `plan_grid`, per track. */
export interface AnalyzePreview {
total: number
tracks_to_analyze: number
grid_full: number
grid_bpm: number
grid_phase: number
grid_locked: number
grid_existing: number
grid_flexible: number
/** Unlocked tracks with a grid — the grid Replace tick's count. */
with_grid: number
key_set: number
key_existing: number
/** Tracks with a key — the key Replace tick's count. */
with_key: number
loudness_measure: number
loudness_existing: number
/** Measured and not stale — the loudness Replace tick's count. */
with_loudness: number
gain_set: number
gain_existing: number
/** Tracks with an auto gain — the gain Replace tick's count. */
with_gain: number
}
/** Normalize's choices (`gain/normalize.py`). */
export interface NormalizeOptions {
measure: 'lufs' | 'rms'
target: number
ceiling: number
}
/** One track in Normalize's preview — the backend's `plan_gain`. */
export interface NormalizeRow {
track_id: string
title: string
/** The measure now; null = not measured yet (the run measures it first). */
level: number | null
/** Why nothing can be done (missing file, already pending). */
skip: string | null
gain_db?: number
outcome?: 'apply' | 'capped' | 'at_target' | 'hot_peak_left' | 'unsupported' | 'unmeasured'
short_by?: number
lossless?: boolean
}
export interface NormalizePreview {
total: number
to_change: number
to_measure: number
tracks_to_process: number
/** Lossless files that would change — permanent once saved. */
lossless: number
counts: Record<string, number>
rows: NormalizeRow[]
}
/** What a Normalize run did. */
export interface NormalizeResult {
normalised: string[]
skipped: { track_id: string; title: string; reason: string }[]
failed: { track_id: string; title: string; reason: string }[]
counts: Record<string, number>
cancelled: boolean
}
/** What an Analyze run did. */
export interface AnalyzeResult {
analysed: string[]
failed: { title: string; reason: string }[]
grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number }
key: { set: number; existing: number; none: number }
loudness: { measured: number; existing: number; none: number }
gain: { set: number; existing: number; none: number }
}
/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it
* placed on each); `failed` could not be analysed. */
export interface CueBatchResult {
tracks: string[]
cues_placed: number
grids_created: number
failed: { title: string; reason: string }[]
}
/** Convert to Stems: where the files go and what the collection does. */
export interface StemConvertOptions {
/** `replace`: the stem file supersedes the original where it lives (the
* original is parked, and Save deletes it). `destination`: a chosen folder;
* the originals are never touched. */
mode: 'replace' | 'destination'
destination?: string | null
/** `repoint`: the entry names the stem file. `add`: a new entry beside it
* (destination mode only). */
collection: 'repoint' | 'add'
playlist_id?: string | null
new_playlist?: string | null
}
export interface StemSkip {
track_id: string
title: string
reason: string
}
/** What a conversion would do (`POST /api/tracks/stems/preview`). */
export interface StemPlan {
convert: { track_id: string; title: string; target: string; reuse: boolean }[]
skipped: StemSkip[]
space: { volume: string; folder: string; bytes: number; free: number | null }[]
/** Set when the batch cannot run at all (not enough space). */
blocked: string | null
/** Audio still to separate, in seconds (reused leftovers excluded). */
seconds: number
/** What the new stem files will take on disk. */
bytes: number
/** The originals' size — what Save deletes in Replace mode. */
original_bytes: number
/** A remote library: what must cross the network (bytes; `speed` in
* bytes/s, `measured` false while it is still a default). */
transfer?: { download: number; upload: number; speed: number; measured: boolean }
}
/** A stem conversion job's `result`. */
export interface StemBatchResult {
converted: { track_id: string; new_id: string; title: string }[]
/** Old id → new id, for entries repointed at their stem file. */
renamed: Record<string, string>
/** Original id → the NEW entry added beside it. */
added: Record<string, string>
skipped: StemSkip[]
failed: StemSkip[]
cancelled: boolean
playlist_missing?: boolean
}
export type StemTarget = 'macos-arm64' | 'windows-x64-cpu' | 'windows-x64-cuda'
/** `GET /api/stems/engine`: the engine and weights on this computer. */
export interface StemEngineStatus {
supported: boolean
required_version: string
installed: { version: string; target: StemTarget; size: number | null } | null
offered_targets: StemTarget[]
download_sizes: Partial<Record<StemTarget, number | null>>
manifest_available: boolean
nvidia: { name: string; driver: string; capability: number } | null
weights: { installed: boolean; size: number; revision: string }
root: string
/** `auto` | `cpu` | `gpu`, from prefs (`stemDevice`). */
device: string
/** A running download's job id. */
install_job: string | null
}
export interface SourceCandidate {
path: string
/** What a person recognises, e.g. "OneLibrary — Hardy". */
label: string
platform: Platform
/** Null until it is opened; probing every drive would be slow. */
tracks: number | null
modified: number | null
}
export interface SourceStatus {
loaded: boolean
path: string | null
label: string | null
platform: Platform | null
tracks: number | null
playlists: number | null
}
// ---- export sets ----
//
// Konduktor's own curation, never written into the user's library, and keyed by
// the library's stable ID rather than its path — so moving a collection does not
// orphan the sets built against it.
export interface ExportSet {
id: string
name: string
/** Platform ids of the export TARGETS, e.g. ["traktor", "onelibrary"]. Never
* empty. They share one destination and ONE copy of the audio. */
targets: string[]
destination: string
playlist_ids: string[]
/** LOOSE tracks only — tracks a referenced playlist supplies are not listed. */
track_ids: string[]
/** Lock every exported grid, so Traktor does not re-analyse a track when it
* is first loaded. Set from the run dialog and remembered here. */
lock_grids: boolean
created: number
modified: number
}
export interface ExportPlaylist {
id: string
name: string
/** Deleted from the library since it was added to the set. */
missing: boolean
count: number
}
/** What a set holds RIGHT NOW. Never cache it: the references are live, so a
* playlist edited after curation changes what this returns. */
export interface ExportContents {
playlists: ExportPlaylist[]
loose: number
/** Deduped across playlists and loose tracks: one track, one file copy. */
tracks: number
/** Track ids the library no longer has. Shown, never silently dropped. */
dangling: string[]
/** Another set already writes here, and an export CLEARS its destination. */
destination_conflict: string | null
}
/** What an export would do if run now. Computed fresh every time. */
export interface ExportPreview {
tracks: number
exportable: number
/** Tracks whose copy from the last export is still current, so are kept
* rather than copied. `total_bytes` counts only what WILL be copied. */
unchanged: number
missing: string[]
playlists: string[]
total_bytes: number
destination: string | null
free_bytes: number | null
enough_space: boolean | null
/** A FACT, not a sentence — the UI words it. Null when the export can run. */
blocked: 'destination_not_empty' | 'nothing_to_export' | 'unsupported_target' | null
/** The destination already holds a Konduktor export, which will be replaced. */
replacing: boolean
/** Targets whose library is only found at a drive's root, when the destination
* is not one. A warning — the export can still run. */
not_drive_root: string[]
}
export interface FsPlace {
/** Groups the row and picks its icon. Never a finished sentence. */
kind: 'home' | 'music' | 'desktop' | 'documents' | 'downloads' | 'volume' | 'library'
name: string
path: string
}
export interface FsEntry {
name: string
path: string
}
export interface FsListing {
path: string
parent: string | null
home: string
dirs: FsEntry[]
files: FsEntry[]
}
export interface SaveResult {
saved: boolean
commit: string | null
playlists: number
}
export interface HistoryEntry {
id: string
timestamp: string
summary: string
}
export interface PathMapping {
from: string
to: string
}
export interface RemapSample {
from: string
to: string
exists: boolean
}
export interface RemapPreview {
total: number
matched: number
existing: number
samples: RemapSample[]
/** Target paths more than one track would land on. Non-zero = the rewrite
* would be refused (two entries sharing a path corrupt the library). */
collisions: number
collision_samples: string[]
}
/** One place a stored volume's tracks were found — a mapping the user can pick. */
export interface RelocationCandidate {
from: string
to: string
/** Of the volume's tracks, how many exist under this mapping. */
found: number
}
/** A stored volume in which NO track resolves, and where its tracks are now.
* `ambiguous`: more than one candidate resolves most of it (a drive and its
* backup clone) — the user chooses, nothing is preselected. */
export interface RelocationVolume {
/** How the library names the place, e.g. Traktor's "X:". */
label: string
root: string
total: number
status: 'found' | 'ambiguous' | 'not_found'
candidates: RelocationCandidate[]
}
/** The open-time missing-files check. `volumes` is empty once answered, so it
* is safe to refetch. */
export interface Relocation {
scanning: boolean
volumes: RelocationVolume[]
}
export interface RelocationApplied {
mappings: number
tracks: number
}
export interface RemapResult {
rewritten: number
commit: string | null
}
export interface PrefixSuggestions {
primary: string
groups: { prefix: string; count: number }[]
}
// API origin. In the packaged desktop app the frontend is served from
// tauri://localhost, so it can't use relative /api paths: the sidecar's
// http://127.0.0.1:<port> is only known once it has started, and the startup
// screen (StartupScreen.tsx) sets it here before anything else renders. In the
// browser dev server it stays '', so URLs are relative and Vite proxies /api.
export let API_BASE = ''
export function setApiBase(url: string): void {
API_BASE = url
}
async function getJSON<T>(url: string): Promise<T> {
const res = await fetch(API_BASE + url)
if (!res.ok) throw new Error(`${res.status} ${res.statusText} — ${url}`)
return res.json() as Promise<T>
}
/** A refusal from the backend. `message` is always a sentence; `detail` keeps
* a structured answer (e.g. `{code: 'in_use', machine, since}`) for the few
* callers that act on it rather than just showing it. */
export class ApiError extends Error {
status: number
detail: unknown
constructor(status: number, message: string, detail: unknown) {
super(message)
this.status = status
this.detail = detail
}
}
async function send<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(API_BASE + url, {
method,
headers: body ? { 'Content-Type': 'application/json' } : undefined,
body: body ? JSON.stringify(body) : undefined,
})
if (!res.ok) {
let message = `${res.status} ${res.statusText}`
let detail: unknown = null
try {
const j = await res.json()
if (j.detail) {
detail = j.detail
if (typeof j.detail === 'string') message = j.detail
else if (typeof j.detail?.message === 'string') message = j.detail.message
}
} catch {
/* ignore */
}
throw new ApiError(res.status, message, detail)
}
return res.json() as Promise<T>
}
function qs(params: Record<string, unknown>): string {
const p = new URLSearchParams()
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== null && v !== '') p.set(k, String(v))
}
const s = p.toString()
return s ? `?${s}` : ''
}
export const api = {
// ---- collection selection ----
collection: () => getJSON<CollectionStatus>('/api/library'),
openCollection: (path: string) =>
send<CollectionStatus>('POST', '/api/library/open', { path }),
// Both take the chosen platform, because the picker asks for it FIRST: the
// shortcuts and the browsable files are only meaningful inside that answer.
collectionOptions: (platform?: string) =>
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
/** Folders on the machine that HOLDS the library (a remote's server),
* confined to its content folder — `home` is that folder. */
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
// ---- remote libraries ----
remotes: () => getJSON<RemoteSettings[]>('/api/remotes'),
addRemote: (form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('POST', '/api/remotes', form),
editRemote: (id: string, form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('PATCH', `/api/remotes/${id}`, form),
deleteRemote: (id: string) => send<{ status: string }>('DELETE', `/api/remotes/${id}`),
openRemote: (id: string, takeover = false) =>
send<CollectionStatus>('POST', '/api/library/open-remote', { remote_id: id, takeover }),
remoteCache: () => getJSON<RemoteCacheUsage>('/api/remote-cache'),
clearRemoteCache: () => send<{ freed: number }>('DELETE', '/api/remote-cache'),
// Re-asked rather than cached: drives come and go while a dialog is open.
places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`),
// ---- export sets ----
//
// 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),
updateExport: (
id: string,
body: Partial<Pick<ExportSet, 'name' | 'targets' | 'destination' | 'lock_grids'>>,
) =>
send<ExportSet>('PATCH', `/api/exports/${encodeURIComponent(id)}`, body),
deleteExport: (id: string) =>
send<{ deleted: boolean }>('DELETE', `/api/exports/${encodeURIComponent(id)}`),
addToExport: (id: string, body: { track_ids?: string[]; playlist_ids?: string[] }) =>
send<ExportSet>('POST', `/api/exports/${encodeURIComponent(id)}/add`, body),
// Removes LOOSE tracks and WHOLE playlists. There is deliberately no way to
// remove one track from a referenced playlist: the reference is live, so that
// would need an exclusion list — hidden state deciding future exports.
removeFromExport: (id: string, body: { track_ids?: string[]; playlist_ids?: string[] }) =>
send<ExportSet>('POST', `/api/exports/${encodeURIComponent(id)}/remove`, body),
exportContents: (id: string) =>
getJSON<ExportContents>(`/api/exports/${encodeURIComponent(id)}/contents`),
exportTracks: (id: string) =>
getJSON<Track[]>(`/api/exports/${encodeURIComponent(id)}/tracks`),
// Only the tracks added individually — the "Other" bucket, which becomes its
// own playlist in the exported library. Not a filter on exportTracks: that one
// is everything the export would ship, playlists included and deduped.
exportLooseTracks: (id: string) =>
getJSON<Track[]>(`/api/exports/${encodeURIComponent(id)}/loose`),
exportPlaylistTracks: (id: string, playlistId: string) =>
getJSON<Track[]>(
`/api/exports/${encodeURIComponent(id)}/playlists/${encodeURIComponent(playlistId)}/tracks`,
),
// Every platform, with `installed` standing for "can be an export target".
// Unsupported ones are returned too, so the UI shows them disabled with a
// reason rather than hiding them — an absent option reads as a missing
// feature, a disabled one reads as a roadmap.
exportTargets: () => getJSON<PlatformOption[]>('/api/export-targets'),
exportPreview: (id: string) =>
send<ExportPreview>('POST', `/api/exports/${encodeURIComponent(id)}/preview`, {}),
// The run dialog's options travel with the click; the set remembers them.
runExport: (id: string, body: { lock_grids?: boolean } = {}) =>
send<JobStatus>('POST', `/api/exports/${encodeURIComponent(id)}/run`, body),
// ---- path remapping (per-collection OS-path prefix translation) ----
getPathMapping: () => getJSON<PathMapping>('/api/library/path-mapping'),
suggestPrefix: () =>
getJSON<PrefixSuggestions>('/api/library/path-mapping/suggest'),
putPathMapping: (m: PathMapping) =>
send<PathMapping>('PUT', '/api/library/path-mapping', m),
previewRemap: (from: string, to: string) =>
getJSON<RemapPreview>(
`/api/library/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,
),
// Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history).
remapPaths: (from: string, to: string) =>
send<RemapResult>('POST', '/api/library/remap-paths', { from, to }),
// The open-time missing-files check; answering with no mappings is "Not now".
// Applied mappings last for this session only.
relocation: () => getJSON<Relocation>('/api/library/relocation'),
answerRelocation: (mappings: PathMapping[]) =>
send<RelocationApplied>('POST', '/api/library/relocation', { mappings }),
capabilities: () => getJSON<Capabilities>('/api/capabilities'),
platforms: () => getJSON<PlatformOption[]>('/api/platforms'),
facets: () => getJSON<Facets>('/api/facets'),
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
tracks: (query: TrackQuery) =>
getJSON<TrackPage>(`/api/tracks${qs(query as Record<string, unknown>)}`),
playlistTracks: (id: string) =>
getJSON<Track[]>(`/api/playlists/${id}/tracks`),
// ---- writes ----
state: () => getJSON<EditState>('/api/state'),
createPlaylist: (name: string, parentId?: string) =>
send<PlaylistNode>('POST', '/api/playlists', { name, parent_id: parentId ?? null }),
createFolder: (name: string, parentId?: string) =>
send<PlaylistNode>('POST', '/api/playlists/folders', { name, parent_id: parentId ?? null }),
renamePlaylist: (nodeId: string, name: string) =>
send<{ status: string }>('PATCH', `/api/playlists/${encodeURIComponent(nodeId)}`, { name }),
deletePlaylist: (nodeId: string) =>
send<{ status: string }>('DELETE', `/api/playlists/${encodeURIComponent(nodeId)}`),
setEntries: (nodeId: string, trackIds: string[]) =>
send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, {
track_ids: trackIds,
}),
/** Append tracks. `duplicates` decides tracks already there: skip them,
* add them again (where `playlists.duplicates`), or `ask` — nothing changes
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */
/** `index`: insert at this position among the current entries; null appends. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip', index: number | null = null) =>
send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
'POST',
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
{ track_ids: trackIds, duplicates, index },
),
/** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
send<{ status: string; id: string }>('POST', '/api/playlists/move', {
node_id: nodeId,
parent_id: parentId,
index,
}),
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
patchPrefs: (patch: Record<string, unknown>) =>
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
save: () => send<SaveResult>('POST', '/api/save'),
/** Drop every unsaved edit; the library re-reads itself from disk. */
discard: () => send<EditState>('POST', '/api/discard'),
// ---- version history ----
history: () => getJSON<HistoryEntry[]>('/api/history'),
restoreVersion: (id: string) =>
send<CollectionStatus>('POST', `/api/history/${id}/restore`),
clearHistory: () => send<{ status: string }>('DELETE', '/api/history'),
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
setTrackColor: (trackIds: string[], color: TrackColor | null) =>
send<{ status: string; tracks: Track[] }>('PATCH', '/api/tracks/color', {
track_ids: trackIds,
color,
}),
artUrl: (trackId: string) =>
`${API_BASE}/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
audioUrl: (trackId: string) =>
`${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
trackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
createCue: (
trackId: string,
slot: number,
start: number,
type: CueType,
length = 0,
name?: string,
) =>
send<TrackCues>('POST', '/api/tracks/cue', {
track_id: trackId,
slot,
start,
type,
length,
name,
}),
// Analyses the track's structure on its beatgrid and places the template:
// one event (+ offset in beats) per slot. Every slot reports an outcome.
autoCues: (trackId: string, slots: AutoCueSlot[]) =>
send<AutoHotcuesResult>('POST', '/api/tracks/cue/auto', {
track_id: trackId,
slots,
}),
/** The deck's Analyze: BPM + grid (on Traktor also hotcue 1) and, where the
* library stores one, the key — from one decode. Returns the cues; the key
* lands on the track, so refetch the track lists. */
autoGrid: (trackId: string) =>
send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }),
/** The Mastering columns' values for these tracks — measured ones only. */
loudness: (origin: TrackOrigin, trackIds: string[]) =>
send<{ values: Record<string, Loudness> }>('POST', '/api/loudness', { origin, track_ids: trackIds }),
/** Measure one track's loudness now (the deck's Analyze where it cannot
* write a grid: a read-only library, a device, a loose file). */
measureLoudness: (origin: TrackOrigin, trackId: string) =>
send<Loudness>('POST', '/api/tracks/loudness', { origin, track_id: trackId }),
/** Auto Hotcues over many tracks, one template for all, as a job. A track
* without a grid gets one analysed first. The finished job's `result` is a
* `CueBatchResult`. */
autoCuesBatch: (trackIds: string[], slots: AutoCueSlot[]) =>
send<JobStatus>('POST', '/api/tracks/cue/auto-batch', { track_ids: trackIds, slots }),
/** Delete these tracks' beatgrids; locked grids are skipped and counted. */
clearGrids: (trackIds: string[]) =>
send<{ cleared: number; locked: number; empty: number }>('POST', '/api/tracks/grid/clear', {
track_ids: trackIds,
}),
/** Empty these tracks' whole hotcue bank (the grid is untouched). */
clearHotcues: (trackIds: string[]) =>
send<{ tracks: number; cues: number }>('POST', '/api/tracks/cue/clear', { track_ids: trackIds }),
/** Remove tracks from the library and every playlist. Audio files stay. */
removeTracks: (trackIds: string[]) =>
send<{ removed: number }>('POST', '/api/tracks/remove', { track_ids: trackIds }),
stemPreview: (trackIds: string[], opts: StemConvertOptions) =>
send<StemPlan>('POST', '/api/tracks/stems/preview', { track_ids: trackIds, ...opts }),
/** Starts a `stem-conversion` job; its `result` is a `StemBatchResult`. */
stemConvert: (trackIds: string[], opts: StemConvertOptions) =>
send<JobStatus>('POST', '/api/tracks/stems/convert', { track_ids: trackIds, ...opts }),
stemEngine: () => getJSON<StemEngineStatus>('/api/stems/engine'),
/** Starts a `stem-engine-install` job, counting bytes (engine + weights). */
stemEngineInstall: (target?: StemTarget | null) =>
send<JobStatus>('POST', '/api/stems/engine/install', { target: target ?? null, weights: true }),
stemSideload: (path: string, kind: 'engine' | 'weights') =>
send<StemEngineStatus>('POST', '/api/stems/engine/sideload', { path, kind }),
stemEngineRemove: () => send<StemEngineStatus>('DELETE', '/api/stems/engine'),
analyzePreview: (trackIds: string[], opts: AnalyzeOptions) =>
send<AnalyzePreview>('POST', '/api/tracks/analyze/preview', { track_ids: trackIds, ...opts }),
normalizePreview: (trackIds: string[], opts: NormalizeOptions) =>
send<NormalizePreview>('POST', '/api/tracks/normalize/preview', { track_ids: trackIds, ...opts }),
/** Starts a Normalize job; its `result` is a `NormalizeResult`. */
normalize: (trackIds: string[], opts: NormalizeOptions) =>
send<JobStatus>('POST', '/api/tracks/normalize', { track_ids: trackIds, ...opts }),
/** Starts an analysis job; its `result` is an `AnalyzeResult`. */
analyze: (trackIds: string[], opts: AnalyzeOptions) =>
send<JobStatus>('POST', '/api/tracks/analyze', { track_ids: trackIds, ...opts }),
setCueType: (trackId: string, slot: number, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/cue', { track_id: trackId, slot, type }),
/** Recolour a cue from `capabilities.cues.palette`; null = uncoloured. */
setCueColor: (trackId: string, slot: number, color: string | null) =>
send<TrackCues>('PATCH', '/api/tracks/cue/color', { track_id: trackId, slot, color }),
deleteCue: (trackId: string, slot: number) =>
send<TrackCues>(
'DELETE',
`/api/tracks/cue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`,
),
/** A memory cue (a memory loop when `length` > 0). Refused past
* `capabilities.cues.max_memory_cues`. */
addMemoryCue: (trackId: string, start: number, type: CueType, length = 0) =>
send<TrackCues>('POST', '/api/tracks/memory-cue', { track_id: trackId, start, type, length }),
/** `cueId` is `CuePoint.id`; null / '' clears the name. */
renameMemoryCue: (trackId: string, cueId: string, name: string | null) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue', { track_id: trackId, cue_id: cueId, name }),
/** A point type from `capabilities.cues.types`; a memory loop is not retyped. */
setMemoryCueType: (trackId: string, cueId: string, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue/type', { track_id: trackId, cue_id: cueId, type }),
/** From `capabilities.cues.memory_palette`; null = uncoloured. */
setMemoryCueColor: (trackId: string, cueId: string, color: string | null) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue/color', {
track_id: trackId,
cue_id: cueId,
color,
}),
deleteMemoryCue: (trackId: string, cueId: string) =>
send<TrackCues>(
'DELETE',
`/api/tracks/memory-cue?track_id=${encodeURIComponent(trackId)}&cue_id=${encodeURIComponent(cueId)}`,
),
/** Retempo and/or move one marker. `index` is its position in grid_markers;
* a move is clamped between its neighbours rather than reordering them. */
setGridMarker: (trackId: string, index: number, patch: { bpm?: number; start?: number }) =>
send<TrackCues>('PATCH', '/api/tracks/grid/marker', {
track_id: trackId,
index,
...patch,
}),
/** Add a marker. Omitting `bpm` inherits the tempo governing that position. */
addGridMarker: (trackId: string, start: number, bpm?: number) =>
send<TrackCues>('POST', '/api/tracks/grid/marker', { track_id: trackId, start, bpm }),
deleteGridMarker: (trackId: string, index: number) =>
send<TrackCues>(
'DELETE',
`/api/tracks/grid/marker?track_id=${encodeURIComponent(trackId)}&index=${index}`,
),
/** Replace the whole grid (the deck's Reset). `[]` clears it. */
replaceGridMarkers: (trackId: string, markers: GridMarker[]) =>
send<TrackCues>('PUT', '/api/tracks/grid', { track_id: trackId, markers }),
deleteGrid: (trackId: string) =>
send<TrackCues>('DELETE', `/api/tracks/grid?track_id=${encodeURIComponent(trackId)}`),
setGridLock: (trackId: string, locked: boolean) =>
send<TrackCues>('PATCH', '/api/tracks/grid/lock', { track_id: trackId, locked }),
// ---- import sources ----
// `sources()` genuinely changes between calls — a stick is whatever is
// mounted — so callers are expected to poll it rather than read it once.
sources: () => getJSON<SourceCandidate[]>('/api/sources'),
source: () => getJSON<SourceStatus>('/api/source'),
openSource: (path: string) => send<SourceStatus>('POST', '/api/source/open', { path }),
/** Releases the drive's file handle — without this a stick will not eject. */
closeSource: () => send<SourceStatus>('DELETE', '/api/source'),
sourceCapabilities: () => getJSON<Capabilities>('/api/source/capabilities'),
sourceTracks: (query: TrackQuery = {}) =>
getJSON<TrackPage>(`/api/source/tracks${qs(query as Record<string, unknown>)}`),
sourcePlaylists: () => getJSON<PlaylistNode[]>('/api/source/playlists'),
sourcePlaylistTracks: (id: string) =>
getJSON<Track[]>(`/api/source/playlists/${encodeURIComponent(id)}/tracks`),
sourceTrackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/source/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
/** Audition a track off the stick before importing it. */
sourceAudioUrl: (trackId: string) =>
`${API_BASE}/api/source/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
// ---- drives and folders ----
drives: () => getJSON<Drive[]>('/api/fs/drives'),
folders: (path: string) => getJSON<FsEntry[]>(`/api/fs/folders?path=${encodeURIComponent(path)}`),
folderTracks: (path: string) =>
getJSON<FolderTracks>(`/api/folder/tracks?path=${encodeURIComponent(path)}`),
folderCapabilities: (path: string) =>
getJSON<Capabilities>(`/api/folder/capabilities?path=${encodeURIComponent(path)}`),
folderTrackCues: (trackId: string) =>
getJSON<TrackCues>(`/api/folder/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
folderAudioUrl: (trackId: string) =>
`${API_BASE}/api/folder/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
folderAddPreview: (body: FolderAddRequest) =>
send<FolderAddPreview>('POST', '/api/folder/add/preview', body),
folderAdd: (body: FolderAddRequest) => send<JobStatus>('POST', '/api/folder/add', body),
folderDropped: (paths: string[]) => send<DroppedFiles>('POST', '/api/folder/dropped', { paths }),
// ---- import ----
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
/** Starts the job and returns immediately — poll `job()` for progress. */
startImport: (body: ImportRequest) => send<JobStatus>('POST', '/api/import', body),
job: (id: string) => getJSON<JobStatus>(`/api/jobs/${encodeURIComponent(id)}`),
/** A request, not a kill: the job stops at its next checkpoint and cleans up,
* so expect `state` to stay 'running' for a moment after this resolves. */
cancelJob: (id: string) =>
send<JobStatus>('POST', `/api/jobs/${encodeURIComponent(id)}/cancel`),
uploadArt: async (trackId: string, file: File) => {
const fd = new FormData()
fd.append('track_id', trackId)
fd.append('file', file)
const res = await fetch(`${API_BASE}/api/tracks/art`, { method: 'PUT', body: fd })
if (!res.ok) throw new Error(`Cover upload failed (${res.status})`)
return res.json()
},
}
/**
* Which library a track in view belongs to. Ids are only unique WITHIN one —
* a device's track and a collection track can share an id — so anything that
* fetches by id must know which one it is asking.
*/
export type TrackOrigin = 'collection' | 'device' | 'folder'
export function trackAudioUrl(origin: TrackOrigin, trackId: string): string {
if (origin === 'device') return api.sourceAudioUrl(trackId)
if (origin === 'folder') return api.folderAudioUrl(trackId)
return api.audioUrl(trackId)
}
/** One stem a stem file carries, in stream order (stem k = stream k+1). */
export interface StemInfo {
name: string
/** "#RRGGBB", as the file names it. */
color: string
}
/** The stems the track's FILE carries — empty for anything that is not a
* playable stem file, whatever the library says about it. */
export async function trackStemsFor(origin: TrackOrigin, trackId: string): Promise<StemInfo[]> {
const base = origin === 'device' ? '/api/source/tracks/stems' : origin === 'folder' ? '/api/folder/tracks/stems' : '/api/tracks/stems'
const res = await getJSON<{ stems: StemInfo[] }>(`${base}?track_id=${encodeURIComponent(trackId)}`)
return res.stems
}
/** Stem `k` (0-based) of a stem file, served as a file of its own: a browser
* decodes only an MP4's first audio stream, which is the mix. */
export function trackStemUrl(origin: TrackOrigin, trackId: string, k: number): string {
return `${trackAudioUrl(origin, trackId)}&stem=${k}`
}
export function trackCuesFor(origin: TrackOrigin, trackId: string): Promise<TrackCues> {
if (origin === 'device') return api.sourceTrackCues(trackId)
if (origin === 'folder') return api.folderTrackCues(trackId)
return api.trackCues(trackId)
}