Added device file exploration and file importing

This commit is contained in:
patben8 committed 2026-09-25 23:30:24 +02:00
1 parent b9d43dd7ea
commit bd425f8cd6
18 files changed
+1814 -115

No files matched your search

+46 -2
View File
@@ -108,7 +108,22 @@ Two independent apps that talk over HTTP:
`is_os_housekeeping()` names what an OS writes into a folder by itself
(`.Spotlight-V100`, `.Trashes`, `._*`, `System Volume Information`, …), so
the export's "is this folder empty?" check does not refuse a stick's root
just because a Mac has mounted it once.
just because a Mac has mounted it once. `drives()` splits drives into
`local` (the boot disk at `/`, never its `/Volumes` alias, plus internal
drives per `diskutil`, cached per mount) and `external` — **anything
uncertain is external**, so a stick is never presented as a safe place to
reference tracks from; mounted `.dmg`s are dropped. `is_hidden()` reads
macOS's hidden FLAG (as Finder does), not a list of names.
- `folder.py` — **a folder of loose audio files read as a read-only
source** (`FolderSource`), for the sidebar's Files trees. NOT a
registered driver: `can_open("any directory")` would make every folder a
library to the picker. **This folder only** (the tree reaches
subfolders), **track id = absolute path**, tags read once per folder
mtime by `FolderScanner` — which is also the audio route's gatekeeper:
only a file a scan found is streamed, so `/api/folder/tracks/audio` cannot
read an arbitrary path. Tagged keys are deliberately dropped (every
notation there is). The listed suffixes are the collection's
`tracks.audio_formats` capability.
- `adapters/traktor/` — everything that knows NML exists.
- `store.py` (`TraktorStore`) — the retained native model: owns the parsed
dataclass NML, applies every edit, renders + saves. See "Write path".
@@ -229,6 +244,15 @@ Two independent apps that talk over HTTP:
`track_cues()`. The `PQTZ` beatgrid is the same tag as Rekordbox's, and the
collapse rule is **shared by import** rather than copied — two definitions of
"when does a tempo change start a marker" would drift silently.
- `importer.py` also serves the folder add: `reference=True` adds each file
where it is (nothing to copy or roll back), and every planned file the
destination already points at (matched on `audio_path`, never the display
`filepath`) maps to its EXISTING id instead of being added again.
**`PrepStrip` takes `origin`** (`collection`/`device`/`folder`), recorded
with the deck's track in `App` — the deck follows its TRACK's library, not
the view's, so browsing elsewhere cannot point it at endpoints that do not
know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place
that choice is made.
- `app_state.py` — the one loaded library, and the **version-history commit**.
History is app-level: the adapter returns the bytes it wrote plus a summary,
and `AppState.save()` versions them. Every write path must go through it.
@@ -325,7 +349,20 @@ Two independent apps that talk over HTTP:
view. Adding is not gated
on the library being writable, since an export set is Konduktor's own data.
`ExportDialog` shows unsupported targets **disabled with a reason** rather
than hiding them), `CollectionPicker` (**two steps: which PLATFORM, then which
than hiding them), `DevicesSection` (**every drive**, polled from
`/api/fs/drives`: external ones under Devices, the computer's own under an
expandable Local Storage. A drive carrying a OneLibrary library opens as a
device as before, and EVERY drive has a lazily-fetched **Files** tree;
clicking a folder is the `folder` source kind — its audio in the ordinary
table, read-only via `readonly_cause: 'not_in_library'`, with files the
collection already holds checked off in the # column (`TrackTable`'s
`marked`). Capped at 40% of the sidebar and self-scrolling so a deep tree
gives way before the playlists do) + `AddFilesDialog` (copy vs. leave in
place is **asked every time with nothing preselected** — the answer depends
on the drive — and warns that a referenced file on an external drive goes
missing on unplug. A playlist/export target adds to the collection first
and says so; it runs through `importer.run(reference=…, into_playlist=…)`),
`CollectionPicker` (**two steps: which PLATFORM, then which
library** — Automatic / Open last / Find manually, the last revealing a file
browser. The platform comes first because every later answer depends on it:
asked the other way round, "Automatic" had to guess ACROSS platforms and did
@@ -562,6 +599,13 @@ serialization path.** It enforces:
track spans rows in several tables plus ANLZ files, and which Rekordbox
expects deleted together is unmeasured). The journal records it as
`track/remove`, NOT an edit — otherwise history would read "edited 40 tracks".
- `test_folders.py` — the Files trees and adding loose files, through the
routes, on generated FLACs and a temp copy of the collection: a folder lists
only the visible audio DIRECTLY in it; the audio route refuses anything a
scan did not find; **a file the collection already points at is never added
twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt
collection) but still reaches the playlist/export it was headed for; "copy"
points the entry at the copy and "reference" at the original.
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -60,6 +60,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"],
removable=True,
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
artwork=True,
artwork_note=(
"Traktor caches its own cover thumbnail, so a replaced image may "
+7 -1
View File
@@ -20,7 +20,9 @@ from pydantic import BaseModel
# "Konduktor cannot write this platform YET" is a roadmap gap the user should
# expect to close, whereas "this library is synced with Rekordbox Cloud" is a
# permanent refusal protecting their other machines.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced"]
# `not_in_library` is a folder of loose files being browsed: nothing there is a
# library to write to, and the way to edit one is to add it to the collection.
ReadonlyCause = Literal["platform_incomplete", "cloud_synced", "not_in_library"]
CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
@@ -61,6 +63,10 @@ class TrackCapabilities(BaseModel):
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
removable: bool = False
# The audio files this library can hold, as lower-case suffixes. What a
# browsed folder offers to add — a file the library would refuse, or that
# the DJ app cannot play, is not worth listing as addable.
audio_formats: list[str] = [".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a"]
artwork: bool = False
artwork_note: str | None = None
+200
View File
@@ -0,0 +1,200 @@
"""A folder of loose audio files, read as if it were a (read-only) library.
The sidebar's Files trees browse any drive, and selecting a folder shows the
audio in it in the ordinary track table and deck. Projecting the folder into the
generic `Track` model is what makes that cheap: the table, the deck, the
read-only gating and the importer all already speak it, so none of them needs to
learn what a folder is.
Deliberately NOT a registered driver. `can_open()` on "any directory" would make
every folder a library to the picker, and the collection picker offering
`~/Downloads` as a library is exactly the confusion the registry exists to avoid.
This is opened by the folder routes and nothing else.
Three rules:
* **This folder only.** Subfolders are not scanned — the tree is how you get to
them — so a click on a drive root never walks the whole drive.
* **A track id is the file's absolute path.** It is the one identity a loose
file has, and it is what the audio route checks a request against.
* **Tags are read once per folder state.** Reading tags opens every file, which
on a slow stick is the whole cost; the result is cached until the folder's
own mtime changes (a file added, removed or renamed).
"""
from __future__ import annotations
import logging
import os
import threading
from pathlib import Path
from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities
from .model import PlaylistNode, Track, TrackCues
from .places import is_hidden
log = logging.getLogger(__name__)
def _first(tags, key: str) -> str | None:
try:
values = tags.get(key)
except (KeyError, ValueError):
return None
if not values:
return None
value = str(values[0]).strip()
return value or None
def _bpm(tags) -> float | None:
raw = _first(tags, "bpm")
if raw is None:
return None
try:
bpm = float(raw)
except ValueError:
return None
return bpm if 20 <= bpm <= 400 else None
def read_track(path: Path) -> Track:
"""Project one audio file. Never raises: an unreadable tag is an untitled track."""
track = Track(id=str(path), title=path.stem, filepath=str(path))
try:
import mutagen
audio = mutagen.File(path, easy=True)
except Exception: # noqa: BLE001 — a corrupt file must not hide the folder
log.debug("could not read tags from %s", path, exc_info=True)
return track
if audio is None:
return track
tags = audio.tags or {}
track.title = _first(tags, "title") or path.stem
track.artist = _first(tags, "artist")
track.album = _first(tags, "album")
track.genre = _first(tags, "genre")
track.label = _first(tags, "organization")
track.bpm = _bpm(tags)
info = getattr(audio, "info", None)
if info is not None:
length = getattr(info, "length", None)
track.length = int(round(length)) if length else None
bitrate = getattr(info, "bitrate", None)
track.bitrate = int(bitrate) if bitrate else None
# Key is left out on purpose: tagged keys arrive in every notation there is
# ("Am", "8A", "1m", "A minor"), and passing one through to a library would
# write a string its own analysis never would.
return track
def audio_files(folder: Path, formats: list[str]) -> list[Path]:
"""The visible audio files directly inside `folder`, sorted by name."""
wanted = {f.lower() for f in formats}
out: list[Path] = []
try:
with os.scandir(folder) as it:
for entry in it:
try:
if not entry.is_file() or is_hidden(entry):
continue
except OSError:
continue
if Path(entry.name).suffix.lower() in wanted:
out.append(Path(entry.path))
except OSError:
return []
return sorted(out, key=lambda p: p.name.lower())
def capabilities_for(folder: Path) -> Capabilities:
return Capabilities(
platform="folder",
writable=False,
readonly_cause="not_in_library",
tracks=TrackCapabilities(editable_fields=[], artwork=False),
save=SaveCapabilities(
app_name="Files",
library_label=folder.name or str(folder),
overwrite_risk="none",
history=False,
),
)
class FolderSource:
"""The read half of the adapter protocol, over one folder's audio files.
Only what the table, the deck and the importer ask a source for. There are
no commands at all: nothing here can be written, so nothing here pretends
it could.
"""
def __init__(self, folder: Path, tracks: list[Track]):
self.path = folder
self._tracks = tracks
self._by_id = {t.id: t for t in tracks}
@property
def tracks(self) -> list[Track]:
return self._tracks
def track(self, track_id: str) -> Track | None:
return self._by_id.get(track_id)
def track_cues(self, track_id: str) -> TrackCues | None:
return TrackCues(cues=[], grid_markers=[]) if track_id in self._by_id else None
def audio_path(self, track_id: str) -> Path | None:
return Path(track_id) if track_id in self._by_id else None
def playlist_tree(self) -> list[PlaylistNode]:
return []
def playlist_tracks(self, node_id: str) -> list[Track] | None:
return None
def capabilities(self) -> Capabilities:
return capabilities_for(self.path)
class FolderScanner:
"""Scans folders on request, caching each until its contents change.
Also the gatekeeper for streaming: `source_for_file` answers only for a file
found by a scan, so the audio route cannot be used to read an arbitrary path
off the disk — only audio the user has browsed to.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {}
def scan(self, folder: Path, formats: list[str]) -> FolderSource:
folder = Path(folder)
try:
mtime = folder.stat().st_mtime
except OSError:
mtime = -1.0
key = str(folder)
fmts = tuple(sorted(f.lower() for f in formats))
with self._lock:
hit = self._cache.get(key)
if hit is not None and hit[0] == mtime and hit[1] == fmts:
return hit[2]
source = FolderSource(folder, [read_track(p) for p in audio_files(folder, formats)])
with self._lock:
self._cache[key] = (mtime, fmts, source)
return source
def source_for_file(self, track_id: str) -> FolderSource | None:
folder = str(Path(track_id).parent)
with self._lock:
hit = self._cache.get(folder)
if hit is None or hit[2].track(track_id) is None:
return None
return hit[2]
def clear(self) -> None:
with self._lock:
self._cache.clear()
+124
View File
@@ -168,3 +168,127 @@ def volume_places() -> list[dict]:
except OSError:
continue
return out
# ---- local vs external drives -------------------------------------------------
#
# Only the boot disk is identifiable everywhere. Whether ANOTHER volume is an
# internal SSD or a USB stick needs the OS's own answer, and where that answer is
# not available (or not trustworthy — Windows reports most USB SSDs as "fixed")
# a volume is filed as EXTERNAL. Guessing "local" wrongly would present a stick
# that is about to be unplugged as a permanent home for referenced tracks.
# Keyed by (path, st_dev): a volume's answer does not change while it is mounted,
# and `diskutil` is a subprocess — too slow to run for every drive on every poll.
_mac_info_cache: dict[tuple[str, int], dict] = {}
def _mac_info(path: Path) -> dict:
import plistlib
import subprocess
try:
key = (str(path), path.stat().st_dev)
except OSError:
return {}
if key not in _mac_info_cache:
try:
out = subprocess.run(
["diskutil", "info", "-plist", str(path)],
capture_output=True, timeout=5, check=True,
).stdout
_mac_info_cache[key] = plistlib.loads(out)
except (OSError, subprocess.SubprocessError, plistlib.InvalidFileException, ValueError):
_mac_info_cache[key] = {}
return _mac_info_cache[key]
def is_internal(path: Path) -> bool:
"""Whether a non-boot volume is a drive built into this computer."""
if sys.platform != "darwin":
return False
info = _mac_info(path)
return (
bool(info.get("Internal"))
and not info.get("Ejectable")
and not info.get("RemovableMediaOrExternalDevice")
and not info.get("RemovableMedia")
)
def _is_disk_image(path: Path) -> bool:
"""A mounted .dmg (an installer, usually) — a mount, but not a drive."""
return sys.platform == "darwin" and _mac_info(path).get("BusProtocol") == "Disk Image"
def drives() -> list[dict]:
"""Every drive, split into `local` (boot + internal) and `external`.
The boot disk's path is the filesystem root, not its `/Volumes` alias: on
macOS `/Volumes/Macintosh HD` is a link back to `/`, and browsing through it
would show every path twice over.
"""
out: list[dict] = []
boot_seen = False
for vol in sorted(set(mount_points()), key=lambda p: p.name.lower()):
try:
if is_boot_volume(vol):
if boot_seen:
continue
boot_seen = True
root = Path(vol.anchor) if sys.platform == "win32" else Path("/")
out.append({"name": vol.name or str(vol), "path": str(root), "kind": "local"})
continue
if _is_disk_image(vol):
continue
kind = "local" if is_internal(vol) else "external"
out.append({"name": vol.name or str(vol), "path": str(vol), "kind": kind})
except OSError:
continue
if not boot_seen and sys.platform != "win32":
# Linux mounts nothing for the root filesystem under /media.
out.insert(0, {"name": "Computer", "path": "/", "kind": "local"})
return out
# ---- what a folder listing should show ----------------------------------------
_UF_HIDDEN = 0x8000 # macOS/BSD `chflags hidden`: /usr, /bin, /Volumes, …
_WIN_HIDDEN = 0x2 | 0x4 # FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM
def is_hidden(entry: os.DirEntry | Path) -> bool:
"""Whether a file browser should leave this entry out.
macOS hides its system folders by FLAG, not by name, so a list of names to
skip would be both incomplete and wrong on a renamed volume. The flag is what
Finder itself reads.
"""
name = entry.name
if name.startswith(".") or is_os_housekeeping(name):
return True
try:
st = entry.stat(follow_symlinks=False) if isinstance(entry, os.DirEntry) else entry.lstat()
except OSError:
return True
if getattr(st, "st_flags", 0) & _UF_HIDDEN:
return True
if getattr(st, "st_file_attributes", 0) & _WIN_HIDDEN:
return True
return False
def subfolders(path: Path) -> list[Path]:
"""The visible folders directly inside `path`, sorted as Finder would."""
out: list[Path] = []
try:
with os.scandir(path) as it:
for entry in it:
try:
if entry.is_dir(follow_symlinks=True) and not is_hidden(entry):
out.append(Path(entry.path))
except OSError:
continue
except OSError:
return []
return sorted(out, key=lambda p: p.name.lower())
+82 -10
View File
@@ -11,13 +11,22 @@ already exist when it reaches the destination, because a file copy that failed
halfway is not something a library write should be discovering.
Scope, chosen deliberately: **everything is added as a new entry**. Nothing is
matched against tracks the destination already holds, so there is no merge policy
and no cross-platform identity problem. Re-importing the same stick duplicates,
and a preview warns about that rather than preventing it.
matched against tracks the destination already holds by metadata, so there is no
merge policy and no cross-platform identity problem. Re-importing the same stick
duplicates, and a preview warns about that rather than preventing it.
The one match that IS made is by **file**: a source file the destination already
points at is never added again. Copying never hits that (it writes a fresh
path), but **referencing in place** does — the folder browser can add
`~/Music/x.mp3` to a collection that already holds it — and on Traktor two
entries for one path share a primary key, which is a corrupt collection rather
than a duplicate track. Such a file maps to the EXISTING track instead, so a
playlist or export it was headed for still gets it.
"""
from __future__ import annotations
import logging
import os
import shutil
from dataclasses import dataclass, field
from pathlib import Path
@@ -46,6 +55,9 @@ class PlannedTrack:
# True when the destination already holds a track with this filename. Only a
# warning: the user chose "add everything as new entries".
duplicate: bool = False
# The destination's own id for this exact file, when it already holds it.
# Not added again; it stands in for the new id wherever one is needed.
existing_id: str | None = None
@dataclass
@@ -56,7 +68,11 @@ class ImportPlan:
@property
def importable(self) -> list[PlannedTrack]:
return [t for t in self.tracks if not t.missing]
return [t for t in self.tracks if not t.missing and t.existing_id is None]
@property
def existing(self) -> list[PlannedTrack]:
return [t for t in self.tracks if t.existing_id is not None]
@property
def total_bytes(self) -> int:
@@ -68,6 +84,7 @@ class ImportPlan:
"importable": len(self.importable),
"missing": [t.title for t in self.tracks if t.missing],
"duplicates": [t.title for t in self.tracks if t.duplicate],
"existing": [t.title for t in self.existing],
"playlists": [name for _, name in self.playlists],
"total_bytes": self.total_bytes,
"destination": str(self.destination) if self.destination else None,
@@ -88,7 +105,29 @@ def _existing_filenames(dest) -> set[str]:
return out
def plan(source, dest, destination: Path, *, track_ids=None, playlist_ids=None) -> ImportPlan:
def _key(path: Path) -> str:
return os.path.normcase(os.path.normpath(str(path)))
def _existing_files(dest) -> dict[str, str]:
"""Every audio file the destination points at → its track id.
Resolved through the adapter's own `audio_path`, which is the only answer
that includes the volume and the active path mapping; the projected
`filepath` is a display string and is not good enough to match on.
"""
out: dict[str, str] = {}
for track in dest.tracks:
try:
path = dest.audio_path(track.id)
except Exception: # noqa: BLE001
path = None
if path is not None:
out.setdefault(_key(path), track.id)
return out
def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids=None) -> ImportPlan:
"""Work out what an import would do, WITHOUT doing any of it.
Computed fresh every time and never stored. Playlist membership on the source
@@ -126,6 +165,7 @@ def plan(source, dest, destination: Path, *, track_ids=None, playlist_ids=None)
plan.playlists.append((node_id, name))
existing = _existing_filenames(dest)
held = _existing_files(dest)
for track_id in wanted:
track = source.track(track_id)
if track is None:
@@ -140,7 +180,8 @@ def plan(source, dest, destination: Path, *, track_ids=None, playlist_ids=None)
try:
if path is not None and path.is_file():
planned.size = path.stat().st_size
planned.duplicate = path.name.lower() in existing
planned.existing_id = held.get(_key(path))
planned.duplicate = planned.existing_id is None and path.name.lower() in existing
else:
planned.missing = True
except OSError:
@@ -224,7 +265,16 @@ def copy_file(src: Path, dst: Path, handle: JobHandle, on_bytes) -> None:
shutil.copystat(src, dst, follow_symlinks=True)
def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str | None = None) -> dict:
def run(
source,
dest,
plan: ImportPlan,
handle: JobHandle,
*,
folder_name: str | None = None,
reference: bool = False,
into_playlist: str | None = None,
) -> dict:
"""Perform the import. Returns a summary dict for the job result.
Ordering is the safety property. Audio is copied FIRST and the library is
@@ -235,8 +285,14 @@ def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str |
This is a COMMITTED action — it saves at the end — rather than an in-memory
edit the Save button flushes. A multi-gigabyte copy is not a pending tweak,
and audio on disk with unsaved entries pointing at it is the worst of both.
`reference` adds each file WHERE IT IS instead of copying it, so there is no
destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit.
"""
destination = plan.destination
if not reference:
assert destination is not None
destination.mkdir(parents=True, exist_ok=True)
@@ -261,8 +317,11 @@ def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str |
try:
for planned in importable:
handle.raise_if_cancelled()
handle.progress(message=f"Copying {planned.title}")
assert planned.source_path is not None
if reference:
copied.append((planned, planned.source_path))
continue
handle.progress(message=f"Copying {planned.title}")
target = _unique_target(destination, planned.source_path.name, taken)
created.append(target) # registered BEFORE the write, so a cancel
copy_file(planned.source_path, target, handle, bump) # mid-file is cleaned
@@ -288,6 +347,17 @@ def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str |
planned.track_id: new_id
for (planned, _), new_id in zip(copied, new_ids)
}
by_source.update({t.track_id: t.existing_id for t in plan.existing})
# Every planned track's id in the destination, in plan order.
all_ids = [by_source[t.track_id] for t in plan.tracks if t.track_id in by_source]
if into_playlist is not None:
handle.progress(message="Adding to the playlist…")
current = dest.playlist_entries(into_playlist) or []
have = set(current)
dest.set_playlist_entries(
into_playlist, current + [i for i in all_ids if i not in have]
)
playlists_made = _rebuild_playlists(
source, dest, plan, by_source, folder_name, handle
@@ -297,9 +367,11 @@ def run(source, dest, plan: ImportPlan, handle: JobHandle, *, folder_name: str |
outcome, _commit = _save(dest)
return {
"tracks": len(new_ids),
"track_ids": all_ids,
"already_held": len(plan.existing),
"playlists": playlists_made,
"skipped_missing": len(plan.tracks) - len(importable),
"destination": str(destination),
"skipped_missing": len([t for t in plan.tracks if t.missing]),
"destination": str(destination) if destination else None,
"summary": getattr(outcome, "summary", ""),
}
except BaseException:
+183
View File
@@ -20,6 +20,7 @@ from .core import grid_detect, structure
from . import importer
from .core import export as core_export
from .core import places, registry
from .core.folder import FolderScanner, FolderSource
from .core.adapter import (
AdapterError,
InvalidCommand,
@@ -56,6 +57,9 @@ from .schemas import (
ExportSetMembers,
ExportSetOut,
ExportPreview,
Drive,
FolderAddRequest,
FolderTracks,
FsEntry,
FsListing,
FsPlace,
@@ -1402,6 +1406,185 @@ def source_track_audio(track_id: str) -> FileResponse:
return FileResponse(path, media_type=mime)
# ---- drives and folders -----------------------------------------------
#
# The sidebar's Devices and Local Storage trees. Browsing a folder is READ-ONLY
# and needs no library of its own: the files are projected as tracks for the
# table and deck, and adding them goes through the ordinary importer.
FOLDERS = FolderScanner()
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
"""The drive `path` lives on: the longest drive root that contains it."""
best = None
for d in drives:
root = Path(d["path"])
try:
path.relative_to(root)
except ValueError:
continue
if best is None or len(root.parts) > len(Path(best["path"]).parts):
best = d
return best
@app.get("/api/fs/drives", response_model=list[Drive])
def fs_drives() -> list[Drive]:
"""Every drive, with the OneLibrary library on it where there is one.
Polled, like `/api/sources`, because drives come and go while the app is
open. Cheap after the first call: which drives are internal is cached per
mount, since asking the OS is a subprocess on macOS.
"""
found = places.drives()
libraries = sources()
out = [Drive(**d) for d in found]
externals = [d for d in found if d["path"] != "/"]
for lib in libraries:
home = _drive_of(Path(lib.path), externals)
if home is None:
continue
for drive in out:
if drive.path == home["path"]:
drive.library = lib
return out
@app.get("/api/fs/folders", response_model=list[FsEntry])
def fs_folders(path: str) -> list[FsEntry]:
"""The visible folders directly inside `path` — one level of a Files tree."""
base = Path(path).expanduser()
if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}")
return [FsEntry(name=p.name, path=str(p)) for p in places.subfolders(base)]
def _formats() -> list[str]:
return require_adapter().capabilities().tracks.audio_formats
@app.get("/api/folder/tracks", response_model=FolderTracks)
def folder_tracks(path: str) -> FolderTracks:
"""The audio files directly inside a folder, and which are already held."""
base = Path(path).expanduser()
if not base.is_dir():
raise HTTPException(404, f"Not a folder: {base}")
source = FOLDERS.scan(base, _formats())
held = importer._existing_files(require_adapter())
drive = _drive_of(base, places.drives())
return FolderTracks(
path=str(base),
tracks=source.tracks,
in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held],
removable=drive is None or drive["kind"] == "external",
)
def _folder_track(track_id: str) -> FolderSource:
# Only a file a scan found. This is what keeps the audio route from being a
# way to read any path on the disk.
source = FOLDERS.source_for_file(track_id)
if source is None:
raise HTTPException(404, "Track not found — browse to its folder first")
return source
@app.get("/api/folder/capabilities", response_model=Capabilities)
def folder_capabilities(path: str) -> Capabilities:
from .core.folder import capabilities_for
return capabilities_for(Path(path))
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
def folder_track_cues(track_id: str) -> TrackCues:
cues = _folder_track(track_id).track_cues(track_id)
assert cues is not None
return cues
@app.get("/api/folder/tracks/audio")
def folder_track_audio(track_id: str) -> FileResponse:
path = _folder_track(track_id).audio_path(track_id)
if path is None or not path.is_file():
raise HTTPException(404, "Audio file not found")
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
return FileResponse(path, media_type=mime)
def _folder_add_plan(body: FolderAddRequest):
dest = require_adapter()
tracks = []
for track_id in body.track_ids:
track = _folder_track(track_id).track(track_id)
if track is not None:
tracks.append(track)
if not tracks:
raise HTTPException(400, "No tracks to add")
# One source across however many folders the ids came from.
source = FolderSource(Path(tracks[0].id).parent, tracks)
destination = None
if body.mode == "copy":
if not body.destination:
raise HTTPException(400, "Copying needs a destination folder")
destination = Path(body.destination).expanduser()
if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None:
raise HTTPException(404, f"Playlist not found: {body.playlist_id}")
if body.export_id is not None:
if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None:
raise HTTPException(404, f"Export not found: {body.export_id}")
return source, dest, destination, importer.plan(
source, dest, destination, track_ids=[t.id for t in tracks]
)
@app.post("/api/folder/add/preview")
def folder_add_preview(body: FolderAddRequest) -> dict:
_source, _dest, destination, plan = _folder_add_plan(body)
out = plan.as_dict(free_bytes=importer.free_bytes(destination) if destination else None)
if body.mode == "reference":
# Nothing is copied, so there is no size to fit anywhere.
out.update(total_bytes=0, free_bytes=None, enough_space=None)
drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None
out["removable"] = drive is None or drive["kind"] == "external"
return out
@app.post("/api/folder/add", response_model=JobStatus)
def folder_add(body: FolderAddRequest) -> JobStatus:
"""Add browsed files to the collection. A job, like import: copying can be long."""
source, dest, destination, plan = _folder_add_plan(body)
if not plan.importable and not plan.existing:
raise HTTPException(400, "Nothing to add (none of those files exist)")
if body.mode == "copy":
free = importer.free_bytes(destination)
if free is not None and free < plan.total_bytes + importer.SPACE_HEADROOM:
raise HTTPException(
400,
f"Not enough space: {plan.total_bytes / 1e9:.1f} GB needed, "
f"{free / 1e9:.1f} GB free at {destination}",
)
if JOBS.active("import"):
raise HTTPException(409, "An import is already running")
library = STATE.library_id
def work(handle):
result = importer.run(
source, dest, plan, handle,
reference=body.mode == "reference",
into_playlist=body.playlist_id,
)
# Export sets are Konduktor's own data, not the library's, so they are
# updated after the library has been saved rather than inside it.
if body.export_id is not None and library is not None:
exports.add(library, body.export_id, track_ids=result["track_ids"])
return result
job = JOBS.submit("import", work)
return JobStatus(**job.as_dict())
# ---- import -----------------------------------------------------------
#
# The only operation in the app that can run for minutes, so it is the only one
+41
View File
@@ -382,6 +382,47 @@ class ImportRequest(BaseModel):
folder_name: str | None = None
class Drive(BaseModel):
"""A drive in the sidebar, under Devices (`external`) or Local Storage.
`library` is the OneLibrary database on it, when there is one — the same
candidate `/api/sources` reports, attached to the drive it lives on so the
sidebar can show one row per drive rather than a device list and a drive
list that disagree about what is plugged in.
"""
name: str
path: str
kind: Literal["local", "external"]
library: SourceCandidate | None = None
class FolderTracks(BaseModel):
"""The audio files directly inside one folder, projected as tracks."""
path: str
tracks: list[Track]
# Ids (= absolute paths) of the files the collection already points at.
in_collection: list[str]
# On an external drive: a track referenced in place goes missing when the
# drive is unplugged, which the add dialog has to say.
removable: bool
class FolderAddRequest(BaseModel):
"""Add browsed files to the collection, and optionally to a playlist/export.
`mode` is asked every time rather than defaulted, because the right answer
depends on the drive and on how the DJ keeps their music.
"""
track_ids: list[str]
mode: Literal["copy", "reference"]
destination: str | None = None # required for `copy`
playlist_id: str | None = None
export_id: str | None = None
class JobStatus(BaseModel):
id: str
kind: str
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+203
View File
@@ -0,0 +1,203 @@
"""Browsing drives and folders, and adding loose files, through the routes.
Runs on a temp copy of the real collection, a temp app-data dir, and FLAC files
generated here — so the tags are known rather than borrowed from a real file.
Pins the things that would fail SILENTLY or dangerously:
* a folder lists only the audio DIRECTLY in it, and never hidden or
OS-housekeeping files (macOS writes a `._` twin beside every file on FAT);
* the audio route streams only files a scan found — it is not a way to read
any path on the disk;
* a file the collection already points at is never added twice. On Traktor two
entries for one path share a primary key, which is a corrupt collection —
and that is exactly what "add in place" would do on a second click;
* such a file still reaches the playlist or export it was headed for;
* "copy" leaves the collection pointing at the COPY, and "reference" at the
original, with nothing copied.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
import time
from pathlib import Path
import numpy as np
import soundfile as sf
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
_DATA = tempfile.TemporaryDirectory()
os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def flac(path: Path, **tags) -> Path:
from mutagen.flac import FLAC
path.parent.mkdir(parents=True, exist_ok=True)
sf.write(path, np.zeros((44100, 2), dtype="float32"), 44100, format="FLAC")
audio = FLAC(path)
for k, v in tags.items():
audio[k] = str(v)
audio.save()
return path
# ---- the folder on disk ------------------------------------------------------
music = Path(tempfile.mkdtemp()) / "Loose"
one = flac(music / "one.flac", title="First Light", artist="Someone", genre="House", bpm=124)
two = flac(music / "two.flac") # untagged: titled by its filename
flac(music / "Deeper" / "three.flac", title="Not Listed")
(music / "notes.txt").write_text("not audio")
shutil.copy2(one, music / "._one.flac") # a macOS AppleDouble twin
flac(music / ".hidden.flac")
(music / ".secret-folder").mkdir()
(music / ".Trashes").mkdir()
work = Path(tempfile.mkdtemp()) / "collection.nml"
shutil.copy2(REAL, work)
os.environ["KONDUKTOR_NML"] = str(work)
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
from konduktor import exports # noqa: E402
from konduktor.app_state import STATE # noqa: E402
from konduktor.core import places # noqa: E402
def wait(c, job):
while job["state"] == "running":
time.sleep(0.05)
job = c.get(f"/api/jobs/{job['id']}").json()
return job
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
before = len(a.tracks)
print("== drives ==")
r = c.get("/api/fs/drives")
check("answers 200", r.status_code == 200, r.text[:200])
drives = r.json()
check("the boot disk is local, at the filesystem root",
any(d["kind"] == "local" and d["path"] == "/" for d in drives), str(drives))
check("each drive is listed once", len({d["path"] for d in drives}) == len(drives))
print("== folder tree: visible folders only ==")
r = c.get("/api/fs/folders", params={"path": str(music)})
names = [e["name"] for e in r.json()]
check("lists the subfolder", names == ["Deeper"], str(names))
if sys.platform == "darwin":
flagged = music / "Flagged"
flagged.mkdir()
os.chflags(flagged, 0x8000) # UF_HIDDEN, as macOS sets on /usr and /bin
names = [e["name"] for e in c.get("/api/fs/folders", params={"path": str(music)}).json()]
check("a folder hidden by FLAG is left out, as Finder does", "Flagged" not in names, str(names))
check("a missing folder is a 404",
c.get("/api/fs/folders", params={"path": str(music / "nope")}).status_code == 404)
print("== a folder's tracks: this folder only, audio only ==")
r = c.get("/api/folder/tracks", params={"path": str(music)})
check("answers 200", r.status_code == 200, r.text[:300])
body = r.json()
ids = [t["id"] for t in body["tracks"]]
check("exactly the two visible audio files", ids == [str(one), str(two)], str(ids))
first = body["tracks"][0]
check("tags are read", (first["title"], first["artist"], first["genre"], first["bpm"])
== ("First Light", "Someone", "House", 124.0), str(first))
check("an untagged file is titled by its name", body["tracks"][1]["title"] == "two")
check("the length comes from the audio", first["length"] == 1, str(first["length"]))
check("nothing is in the collection yet", body["in_collection"] == [])
caps = c.get("/api/folder/capabilities", params={"path": str(music)}).json()
check("the view is read-only, and says why",
caps["writable"] is False and caps["readonly_cause"] == "not_in_library")
print("== the audio route streams only what a scan found ==")
r = c.get("/api/folder/tracks/audio", params={"track_id": str(one)})
check("a scanned file streams", r.status_code == 200 and len(r.content) > 0)
check("an arbitrary file does not",
c.get("/api/folder/tracks/audio", params={"track_id": "/etc/passwd"}).status_code == 404)
check("nor does real audio in a folder nobody browsed",
c.get("/api/folder/tracks/audio",
params={"track_id": str(music / "Deeper" / "three.flac")}).status_code == 404)
check("nor a hidden file beside a scanned one",
c.get("/api/folder/tracks/audio",
params={"track_id": str(music / ".hidden.flac")}).status_code == 404)
check("cues are empty, not an error",
c.get("/api/folder/tracks/cues", params={"track_id": str(one)}).json()["cues"] == [])
print("== reference in place, into a playlist ==")
playlist = a.create_playlist("Folder Test")
req = {"track_ids": [str(one)], "mode": "reference", "playlist_id": playlist}
p = c.post("/api/folder/add/preview", json=req).json()
check("the preview counts one to add", p["importable"] == 1 and p["existing"] == [], str(p))
check("and nothing to copy", p["total_bytes"] == 0)
job = wait(c, c.post("/api/folder/add", json=req).json())
check("the job finishes", job["state"] == "done", str(job))
check("one entry was added", len(a.tracks) == before + 1)
added = job["result"]["track_ids"][0]
check("it points at the ORIGINAL file", a.audio_path(added) == one, str(a.audio_path(added)))
check("its tags came with it", a.track(added).title == "First Light")
check("it is in the playlist", a.playlist_entries(playlist) == [added])
check("it was saved, not left pending", not a.dirty)
body = c.get("/api/folder/tracks", params={"path": str(music)}).json()
check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"]))
print("== a held file is never added twice, but still reaches its target ==")
library = STATE.library_id
eset = exports.create(library, name="Folder Export", target="traktor",
destination=str(Path(tempfile.mkdtemp()) / "out"))
req = {"track_ids": [str(one), str(two)], "mode": "reference",
"playlist_id": playlist, "export_id": eset.id}
p = c.post("/api/folder/add/preview", json=req).json()
check("the preview reports it as already held", p["existing"] == ["First Light"], str(p))
job = wait(c, c.post("/api/folder/add", json=req).json())
check("the job finishes", job["state"] == "done", str(job))
check("only the NEW file was added", len(a.tracks) == before + 2, f"{len(a.tracks) - before}")
check("the held one kept its id", job["result"]["track_ids"][0] == added)
new = job["result"]["track_ids"][1]
check("the playlist holds both, once each", a.playlist_entries(playlist) == [added, new],
str(a.playlist_entries(playlist)))
check("and so does the export", exports.get(library, eset.id).track_ids == [added, new])
print("== copy: the collection points at the copy ==")
three_dir = music / "Deeper"
c.get("/api/folder/tracks", params={"path": str(three_dir)})
dest = Path(tempfile.mkdtemp()) / "Imported"
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest)}
p = c.post("/api/folder/add/preview", json=req).json()
check("the preview sizes the copy", p["total_bytes"] > 0, str(p))
job = wait(c, c.post("/api/folder/add", json=req).json())
check("the job finishes", job["state"] == "done", str(job))
copied_id = job["result"]["track_ids"][0]
check("the audio was copied", (dest / "three.flac").is_file())
check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac",
str(a.audio_path(copied_id)))
check("the original is untouched", (three_dir / "three.flac").is_file())
check("copy without a destination is refused",
c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400)
check("an unscanned file cannot be added",
c.post("/api/folder/add/preview",
json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404)
print("== hidden entries ==")
check("AppleDouble twins are hidden", places.is_hidden(music / "._one.flac"))
check("OS housekeeping is hidden", places.is_hidden(music / ".Trashes"))
check("an ordinary file is not", not places.is_hidden(one))
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_DATA.cleanup()
raise SystemExit(1 if failed else 0)
+198 -28
View File
@@ -3,7 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { writeHint } from './lib/platformCopy'
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track } from './api'
import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api'
import {
COLUMN_MENU,
DEFAULT_COLUMN_ORDER,
@@ -24,6 +24,7 @@ import { PathMappingDialog } from './components/PathMappingDialog'
import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip'
import { ImportDialog } from './components/ImportDialog'
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
import { Icon } from './lib/icons'
function applyFilters(tracks: Track[], f: Filters): Track[] {
@@ -63,6 +64,14 @@ export default function App() {
const [showPaths, setShowPaths] = useState(false)
const [showHistory, setShowHistory] = useState(false)
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
// Which library the DECK's track came from — not the view's. Browsing to a
// playlist while a device or folder track is loaded must not switch the deck
// to endpoints that do not know that track.
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
// The view's origin, read by the load callbacks below (defined before it).
const viewOriginRef = useRef<TrackOrigin>('collection')
// Browsed files being added to the collection (and maybe a playlist/export).
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
const [importing, setImporting] = useState(false)
// Batch analysis (grid, or Auto Hotcues): a confirm step, then the running
@@ -79,10 +88,17 @@ export default function App() {
// Every Remove ▸ action (and the playlist Delete key) confirms first.
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
const playTrack = useCallback((t: Track) => {
const loadTrack = useCallback((t: Track) => {
setPrepTrack(t)
setPlayRequest((n) => n + 1)
setPrepOrigin(viewOriginRef.current)
}, [])
const playTrack = useCallback(
(t: Track) => {
loadTrack(t)
setPlayRequest((n) => n + 1)
},
[loadTrack],
)
// ---- configurable library columns (persisted to userprefs.json) ----
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_COLUMN_VISIBILITY)
@@ -250,9 +266,34 @@ export default function App() {
const deviceCaps = useQuery({
queryKey: ['source-capabilities'],
queryFn: api.sourceCapabilities,
enabled: viewingDevice,
enabled: viewingDevice || prepOrigin === 'device',
staleTime: Infinity,
})
// A browsed folder of loose files. Read-only like a device, for the same
// reason: its track ids (absolute paths) are not collection tracks.
const viewingFolder = source.kind === 'folder'
const folderPath = source.kind === 'folder' ? source.path : null
const folderView = useQuery({
queryKey: ['folder-tracks', folderPath],
queryFn: () => api.folderTracks(folderPath!),
enabled: loaded && viewingFolder,
})
const folderCaps = useQuery({
queryKey: ['folder-capabilities', folderPath],
queryFn: () => api.folderCapabilities(folderPath!),
enabled: loaded && viewingFolder,
staleTime: Infinity,
})
const heldInFolder = useMemo(
() => new Set(folderView.data?.in_collection ?? []),
[folderView.data],
)
viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection'
// Tracks in view belong to ANOTHER library (a device) or to none (a folder),
// so no collection command may be offered on them: their ids mean nothing to
// the collection's routes.
const viewForeign = viewingDevice || viewingFolder
const openDevice = useQuery({ queryKey: ['source'], queryFn: api.source })
const exportSets = useQuery({ queryKey: ['exports'], queryFn: api.exports, enabled: loaded })
const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists, enabled: loaded })
@@ -320,14 +361,21 @@ export default function App() {
// browsing half of the UI gates itself correctly with no new conditions.
// Falls back to the collection's until the device's resolve, so no frame
// renders without capabilities at all.
const viewCaps = viewingDevice
? (deviceCaps.data ??
// Until the device's own capabilities arrive, assume READ-ONLY rather
// than falling back to the collection's. The fallback is the safe
// direction on purpose: guessing "writable" for one frame would offer an
// edit that, if taken, would be sent to the wrong library entirely.
{ ...capabilities.data!, writable: false, readonly_cause: 'platform_incomplete' as const })
// Until a device's or folder's own capabilities arrive, assume READ-ONLY
// rather than falling back to the collection's. The fallback is the safe
// direction on purpose: guessing "writable" for one frame would offer an edit
// that, if taken, would be sent to the wrong library entirely.
const readOnlyCaps = (cause: 'platform_incomplete' | 'not_in_library') =>
capabilities.data ? { ...capabilities.data, writable: false, readonly_cause: cause } : capabilities.data!
const capsFor = (origin: TrackOrigin) =>
origin === 'device'
? (deviceCaps.data ?? readOnlyCaps('platform_incomplete'))
: origin === 'folder'
? (folderCaps.data ?? readOnlyCaps('not_in_library'))
: capabilities.data!
const viewCaps = capsFor(viewOriginRef.current)
// The deck follows its TRACK's library, not the view's.
const deckCaps = capsFor(prepOrigin)
const deviceLabel = openDevice.data?.label ?? 'device'
// One name for whatever is on screen, so the header and the status bar cannot
@@ -340,7 +388,9 @@ export default function App() {
: source.name
const isAll = source.kind === 'all'
const tracks: Track[] = viewingDevice
const tracks: Track[] = viewingFolder
? (folderView.data?.tracks ?? [])
: viewingDevice
? source.kind === 'device'
? (deviceTracks.data?.items ?? [])
: (devicePlaylistTracks.data ?? [])
@@ -353,7 +403,9 @@ export default function App() {
: isAll
? (allTracks.data?.items ?? [])
: (playlistTracks.data ?? [])
const loading = viewingDevice
const loading = viewingFolder
? folderView.isLoading
: viewingDevice
? source.kind === 'device'
? deviceTracks.isLoading
: devicePlaylistTracks.isLoading
@@ -567,7 +619,7 @@ export default function App() {
void runGridAnalysis(ids, false)
}
}
const canAnalyzeGrid = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
const canAnalyzeGrid = canEdit && !viewForeign && !!capabilities.data?.grid.editable
const startCueBatch = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t]))
@@ -580,7 +632,7 @@ export default function App() {
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'cues' })
}
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
// ---- Remove ▸ -----------------------------------------------------------
const nTracks = (n: number) => `${n} track${n === 1 ? '' : 's'}`
@@ -720,9 +772,9 @@ export default function App() {
}),
})
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable
const canClearCues = canAutoCue
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable
const exportRootId =
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
const removeItems = (ids: string[]): MenuItem[] => [
@@ -769,6 +821,23 @@ export default function App() {
]
}
// The same targets as "Add to", but each opens the add dialog: a loose file
// has to join the collection before a playlist or export can hold it.
const folderAddToItems = (ids: string[]): MenuItem[] => [
{ heading: 'Playlists', empty: addablePlaylists.length ? undefined : 'No playlists' },
...addablePlaylists.map((p) => ({
label: p.name,
hint: String(p.count),
onClick: () => setAdding({ ids, target: { kind: 'playlist' as const, id: p.id, name: p.name } }),
})),
{ heading: 'Exports', empty: exportSets.data?.length ? undefined : 'No exports yet' },
...(exportSets.data ?? []).map((set) => ({
label: set.name,
icon: <Icon name="export" size={13} />,
onClick: () => setAdding({ ids, target: { kind: 'export' as const, id: set.id, name: set.name } }),
})),
]
return (
<CapabilitiesContext.Provider value={capabilities.data!}>
{/* Floating glass panels with gaps between them: the ambient backdrop
@@ -785,11 +854,11 @@ export default function App() {
items={[
// Single-track actions are hidden, not disabled, for a multi-selection.
...(menu.ids.length === 1
? [{ label: 'Load to Deck', onClick: () => setPrepTrack(menu.track) }]
? [{ label: 'Load to Deck', onClick: () => loadTrack(menu.track) }]
: []),
// Offering "Edit Tags…" on a read-only library would open a dialog
// whose every save is refused, so it is not offered at all.
...(canEdit && menu.ids.length === 1
...(canEdit && !viewForeign && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
: []),
...(canAnalyzeGrid
@@ -815,8 +884,17 @@ export default function App() {
]
: []),
// A device's track ids belong to the stick, not the collection, so
// there is nothing they could be added to.
...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
// there is nothing they could be added to. A folder's files CAN be
// added — through the add dialog, which puts them in the
// collection first.
...(viewingFolder
? [
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) },
{ label: 'Add to', submenu: folderAddToItems(menu.ids) },
]
: viewingDevice
? []
: [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
...(() => {
const items = removeItems(menu.ids)
return items.length ? [{ label: 'Remove', submenu: items }] : []
@@ -901,14 +979,27 @@ export default function App() {
/>
)}
{adding && (
<AddFilesDialog
trackIds={adding.ids}
target={adding.target}
onClose={() => setAdding(null)}
onDone={(msg) => {
setAdding(null)
notify('success', msg)
}}
onError={onError}
/>
)}
{/* Prep strip spans the top of the window; the library sits below it. */}
<CapabilitiesContext.Provider value={viewCaps}>
<CapabilitiesContext.Provider value={deckCaps}>
<PrepStrip
track={prepTrack}
playRequest={playRequest}
onError={onError}
onNotify={notify}
fromDevice={viewingDevice}
origin={prepOrigin}
cuesRefresh={cuesRefresh}
/>
</CapabilitiesContext.Provider>
@@ -932,20 +1023,61 @@ export default function App() {
filters={filters}
onChange={setFilters}
/>
{(!isAll || viewingDevice) && (
{(!isAll || viewForeign) && (
<div className="flex items-center gap-3 border-b border-line px-4 py-2">
<span
className={`flex ${
viewingDevice ? 'text-gold' : viewingExport ? 'text-gold' : 'text-accent'
viewingDevice || viewingFolder ? 'text-gold' : viewingExport ? 'text-gold' : 'text-accent'
}`}
>
<Icon
name={viewingDevice ? 'drive' : viewingExport && source.kind === 'export' ? 'export' : 'playlist'}
name={
viewingDevice
? 'drive'
: viewingFolder
? 'folderOpen'
: viewingExport && source.kind === 'export'
? 'export'
: 'playlist'
}
size={15}
/>
</span>
<span className="font-semibold text-text">{viewName}</span>
{viewingExport ? (
<span className="font-semibold text-text" title={folderPath ?? undefined}>{viewName}</span>
{viewingFolder ? (
<>
<span className="text-xs text-faint">
{filtersActive
? `${filtered.length} of ${tracks.length} files`
: `${tracks.length} file${tracks.length === 1 ? '' : 's'}`}
{heldInFolder.size > 0 && ` · ${heldInFolder.size} already in your collection`}
{' · this folder only'}
</span>
<span className="ml-auto flex items-center gap-2">
<span className="rounded-full bg-gold/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.3)]">
Not in collection
</span>
{tracks.length > 0 && (
<button
onClick={() =>
setAdding({
// The selection when there is one, else everything in
// view that the collection does not already hold.
ids: selected.size
? filtered.filter((t) => selected.has(t.id)).map((t) => t.id)
: filtered.filter((t) => !heldInFolder.has(t.id)).map((t) => t.id),
target: null,
})
}
disabled={!selected.size && filtered.every((t) => heldInFolder.has(t.id))}
className="btn-primary rounded-full px-3 py-1 text-xs font-semibold disabled:opacity-40"
>
{selected.size ? `Add ${selected.size} to collection…` : 'Add all to collection…'}
</button>
)}
</span>
</>
) : viewingExport ? (
<>
<span className="text-xs text-faint">
{filtersActive
@@ -1034,6 +1166,44 @@ export default function App() {
onColumnSizingChange={setColumnSizing}
/>
)
) : viewingFolder ? (
/* A folder uses the plain table too, WITH selection: its bulk
action is adding the selected files to the collection. The #
column checks off the files the collection already holds. */
folderView.isError ? (
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
<div className="text-lg">Can’t read this folder</div>
<div className="text-sm text-faint">{(folderView.error as Error).message}</div>
</div>
) : filtered.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
<div className="text-lg">
{tracks.length === 0 ? 'No music here' : 'No tracks match'}
</div>
<div className="text-sm text-faint">
{tracks.length === 0
? 'This folder has no audio files directly in it — try one of its subfolders.'
: 'Try clearing some filters.'}
</div>
</div>
) : (
<TrackTable
tracks={filtered}
sorting={sorting}
onSortingChange={setSorting}
selection={{ selected, onChange: setSelected }}
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack}
activeTrackId={prepTrack?.id ?? null}
columnVisibility={columnVisibility}
columnOrder={columnOrder}
columnSizing={columnSizing}
onColumnOrderChange={setColumnOrder}
onColumnSizingChange={setColumnSizing}
/>
)
) : viewingDevice ? (
/* A device uses the plain table, not the playlist one: a stick's
playlists cannot be reordered or have entries removed, so the
+76 -1
View File
@@ -223,7 +223,7 @@ export interface SaveCapabilities {
}
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced'
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library'
export interface Capabilities {
platform: Platform
@@ -245,6 +245,8 @@ export interface Capabilities {
media_kinds: MediaKind[]
/** Tracks can be removed from the library (audio files are never touched). */
removable: boolean
/** Lower-case suffixes this library can hold — what a browsed folder lists. */
audio_formats: string[]
artwork: boolean
artwork_note: string | null
}
@@ -335,6 +337,9 @@ export interface ImportPreview {
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
@@ -342,6 +347,43 @@ export interface ImportPreview {
enough_space: boolean | null
}
// ---- 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. */
kind: 'local' | 'external'
/** The OneLibrary library on this drive, if it carries one. */
library: SourceCandidate | null
}
export interface FolderTracks {
path: string
tracks: Track[]
/** Ids of the files the collection already points at. */
in_collection: 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
export_id?: string | null
}
export interface FolderAddPreview extends ImportPreview {
removable: boolean
}
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
export interface JobStatus {
@@ -770,6 +812,20 @@ export const api = {
/** 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),
// ---- import ----
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
/** Starts the job and returns immediately — poll `job()` for progress. */
@@ -788,3 +844,22 @@ export const api = {
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)
}
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)
}
+350
View File
@@ -0,0 +1,350 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
import { FolderPicker } from './FolderPicker'
/**
* Add browsed files to the collection — and, optionally, to a playlist or export.
*
* Copy vs. leave-in-place is ASKED every time, with nothing preselected: the
* right answer depends on the drive (a stick is about to be unplugged) and on
* how the DJ keeps their music, and a remembered default would quietly apply
* last week's answer to a different drive.
*
* A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still
* go into the target.
*/
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`
}
export interface AddTarget {
kind: 'playlist' | 'export'
id: string
name: string
}
interface Props {
trackIds: string[]
target: AddTarget | null
onClose: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const [mode, setMode] = useState<'copy' | 'reference' | null>(null)
const [folder, setFolder] = useState('')
const [browsing, setBrowsing] = useState(false)
const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false)
const pollRef = useRef<number | null>(null)
// The same import folder as a device import: one place your copied music goes.
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const prefsLoaded = prefs.isSuccess
useEffect(() => {
if (!prefsLoaded || folder) return
const p = prefs.data as { importFolder?: string }
setFolder(p?.importFolder || '~/Music/Konduktor Imports')
}, [prefsLoaded, prefs.data, folder])
const body: FolderAddRequest = {
track_ids: trackIds,
// The preview needs A mode to size anything; "reference" costs nothing to
// ask about and is replaced as soon as the user picks.
mode: mode ?? 'reference',
destination: mode === 'copy' ? folder : null,
playlist_id: target?.kind === 'playlist' ? target.id : null,
export_id: target?.kind === 'export' ? target.id : null,
}
const preview = useQuery<FolderAddPreview>({
queryKey: ['folder-add-preview', trackIds, mode, folder, target?.id],
queryFn: () => api.folderAddPreview(body),
enabled: !job && (mode !== 'copy' || !!folder),
staleTime: 0,
gcTime: 0,
})
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') return
if (pollRef.current) window.clearInterval(pollRef.current)
if (next.state === 'done') {
const r = next.result as { tracks?: number; track_ids?: string[] } | null
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist'] })
qc.invalidateQueries({ queryKey: ['collection'] })
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] })
qc.invalidateQueries({ queryKey: ['folder-tracks'] })
if (target?.kind === 'export') {
qc.invalidateQueries({ queryKey: ['exports'] })
qc.invalidateQueries({ queryKey: ['export-contents', target.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', target.id] })
qc.invalidateQueries({ queryKey: ['export-loose', target.id] })
}
const added = r?.tracks ?? 0
const total = r?.track_ids?.length ?? added
onDone(
target
? `Added ${total} track${total === 1 ? '' : 's'} to ${target.name}` +
(added ? ` (${added} new to your collection)` : '')
: `Added ${added} track${added === 1 ? '' : 's'} to your collection`,
)
} else if (next.state === 'failed') {
onError(next.error || 'Adding 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, target])
const start = async () => {
setStarting(true)
try {
setJob(await api.folderAdd(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
const n = trackIds.length
const newCount = p?.importable ?? 0
const canAdd =
!starting && mode !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
p.enough_space !== false
const title = target
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
: `Add ${n} track${n === 1 ? '' : 's'} to your collection`
const option = (value: 'copy' | 'reference', label: string, detail: ReactNode) => (
<label
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
mode === value ? 'is-selected' : 'hover:bg-ink-850'
}`}
>
<input
type="radio"
name="add-mode"
checked={mode === value}
onChange={() => setMode(value)}
className="mt-0.5 accent-accent"
/>
<span className="min-w-0 flex-1">
<span className="block text-text">{label}</span>
<span className="block text-xs text-faint">{detail}</span>
</span>
</label>
)
return createPortal(
<>
{browsing && (
<FolderPicker
value={folder}
onChange={(path) => {
setFolder(path)
api.patchPrefs({ importFolder: path }).catch(() => {})
}}
onClose={() => setBrowsing(false)}
/>
)}
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
>
<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">{title}</h2>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
{target && (
<div className="text-xs text-muted">
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your
collection, so these are added to the collection first.
</div>
)}
<div className="space-y-1">
{option(
'copy',
'Copy into your import folder',
<span className="flex items-center gap-2">
<span className="min-w-0 truncate font-mono" dir="rtl" title={folder}>
{/* LRM marks: in an rtl box (for left-truncation) a
leading "~" would otherwise be moved to the end. */}
{folder ? `\u200E${folder}\u200E` : 'Loading…'}
</span>
<button
onClick={(e) => {
e.preventDefault()
setBrowsing(true)
}}
className="shrink-0 text-accent hover:underline"
>
Change…
</button>
</span>,
)}
{option(
'reference',
'Leave them where they are',
'Your collection points at these files. Nothing is copied.',
)}
</div>
{mode === 'reference' && p?.removable && (
<div className="rounded well px-3 py-2 text-xs text-gold">
These files are on an external drive. They will go missing from your
collection whenever the drive is unplugged.
</div>
)}
{preview.isError && (
<div className="text-pink">{(preview.error as Error).message}</div>
)}
{mode && p && (
<div className="space-y-2">
<div className="text-text">
{newCount} new to your collection
{mode === 'copy' && (
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span>
)}
</div>
{mode === 'copy' && p.free_bytes != null && (
<div className={p.enough_space === false ? 'text-pink' : 'text-faint'}>
{gb(p.free_bytes)} free
{p.enough_space === false && ' — not enough space'}
</div>
)}
{p.existing.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-muted">
{p.existing.length} {p.existing.length === 1 ? 'is' : 'are'} already in
your collection and will not be added again
{target ? ` — but will still go into ${target.name}` : ''}.
</div>
)}
{p.missing.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-pink">
{p.missing.length} file{p.missing.length === 1 ? ' is' : 's are'} no longer
there and will be skipped.
</div>
)}
{mode === 'copy' && p.duplicates.length > 0 && (
<div className="rounded well px-3 py-2 text-xs text-gold">
{p.duplicates.length} of these look like tracks your collection already
has. The copies will be added as new entries.
</div>
)}
</div>
)}
</>
)}
{job && (
<div className="space-y-3">
<div className="text-text">{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>
{job.state === 'cancelled' && (
<div className="text-xs text-muted">
Cancelled. Nothing was added, and any copied files were removed.
</div>
)}
{job.state === 'failed' && <div className="text-xs text-pink">{job.error}</div>}
{job.state === 'done' && <div className="text-xs text-mint">Done.</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
</button>
<button
onClick={onClose}
className="rounded-md px-3 py-1.5 text-sm text-faint hover:text-text"
title="It 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={!canAdd}
onClick={start}
title={mode === null ? 'Choose whether to copy the files first' : undefined}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold disabled:opacity-40"
>
{starting ? 'Starting…' : 'Add'}
</button>
)}
</>
)}
</div>
</div>
</div>
</>,
document.body,
)
}
+264 -57
View File
@@ -1,20 +1,22 @@
import { useEffect } from 'react'
import { useEffect, useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistNode } from '../api'
import { api, type Drive, type PlaylistNode } from '../api'
import type { Source } from './Sidebar'
import { Icon } from '../lib/icons'
/**
* Plugged-in libraries, in the sidebar, the way rekordbox and Traktor show them.
* Every drive, in the sidebar: plugged-in ones under Devices, and the computer's
* own under an expandable Local Storage.
*
* The list genuinely changes while the app is open — a device is whatever stick
* is mounted — so unlike everything else in the sidebar this POLLS. It is a
* directory stat per mount point, which is cheap enough to do every few seconds
* and the only way a drive can appear without the user reloading.
* A drive carrying a OneLibrary library opens as a device, the way rekordbox and
* Traktor show a stick: its playlists appear under it and the ordinary track
* table browses it. EVERY drive — library or not — also has a Files tree, and
* selecting a folder there shows the audio directly in it (not its subfolders:
* the tree is how you get to those, and a click on a drive root must never walk
* the whole drive).
*
* Browsing a device reuses the ordinary track table and deck: the adapter
* projects a drive into the same generic model the collection uses, so there is
* nothing here that needs its own table, its own row or its own player.
* The list genuinely changes while the app is open, so unlike everything else in
* the sidebar this POLLS. Folder levels are fetched only when expanded.
*/
const POLL_MS = 4000
@@ -28,10 +30,21 @@ interface Props {
export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
const qc = useQueryClient()
// Which rows are expanded, by a key per row kind. Not persisted: a tree
// reopening deep inside a drive that is no longer plugged in helps nobody.
const [expanded, setExpanded] = useState<Set<string>>(new Set())
const isOpenRow = (key: string) => expanded.has(key)
const setRow = (key: string, open: boolean) =>
setExpanded((prev) => {
const next = new Set(prev)
if (open) next.add(key)
else next.delete(key)
return next
})
const devices = useQuery({
queryKey: ['sources'],
queryFn: api.sources,
const drives = useQuery({
queryKey: ['drives'],
queryFn: api.drives,
refetchInterval: POLL_MS,
})
const open = useQuery({ queryKey: ['source'], queryFn: api.source })
@@ -64,24 +77,97 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
onError: (e: Error) => onError(e.message),
})
const list = drives.data ?? []
const external = list.filter((d) => d.kind === 'external')
const local = list.filter((d) => d.kind === 'local')
// A drive can be physically unplugged while it is open. Nothing crashes — the
// routes just start failing — but leaving it selected would show a library
// that is not there, so fall back to the collection.
const stillPresent =
!openPath || (devices.data ?? []).some((d) => d.path === openPath)
// that is not there, so fall back to the collection. The same goes for a
// folder on it being browsed.
const stillPresent = !openPath || list.some((d) => d.library?.path === openPath)
useEffect(() => {
if (!openPath || stillPresent || eject.isPending) return
if (!drives.isSuccess || !openPath || stillPresent || eject.isPending) return
eject.mutate()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openPath, stillPresent])
const list = devices.data ?? []
if (list.length === 0 && !openPath) return null
}, [openPath, stillPresent, drives.isSuccess])
const folderGone =
source.kind === 'folder' &&
drives.isSuccess &&
!list.some((d) => d.path === '/' || isInside(source.path, d.path))
useEffect(() => {
if (folderGone) onSelect({ kind: 'all' })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [folderGone])
const viewingDevice = source.kind === 'device' || source.kind === 'device-playlist'
const driveRow = (d: Drive, depth: number) => {
const key = `drive:${d.path}`
const expandedHere = isOpenRow(key)
const isOpen = !!d.library && d.library.path === openPath
const onClick = () => {
if (d.library) {
setRow(key, true)
if (isOpen) onSelect({ kind: 'device' })
else openDevice.mutate(d.library.path)
} else {
setRow(key, !expandedHere)
}
}
return (
<div key={d.path}>
<TreeRow
depth={depth}
icon={<span className="text-gold"><Icon name="drive" size={15} /></span>}
label={d.name}
title={d.path}
expanded={expandedHere}
onToggle={() => setRow(key, !expandedHere)}
onClick={onClick}
selected={isOpen && source.kind === 'device'}
trailing={
isOpen && open.data?.tracks != null ? (
<span className="text-[10px] text-faint">{open.data.tracks}</span>
) : undefined
}
/>
{expandedHere && (
<>
{isOpen &&
(playlists.data ?? []).map((n) => (
<DevicePlaylistRow
key={n.id}
node={n}
depth={depth + 1}
source={source}
onSelect={onSelect}
/>
))}
<FolderRow
path={d.path}
name="Files"
viewName={d.name}
icon="folder"
depth={depth + 1}
source={source}
onSelect={onSelect}
isOpenRow={isOpenRow}
setRow={setRow}
/>
</>
)}
</div>
)
}
const localKey = 'local-storage'
const localOpen = isOpenRow(localKey)
// Shrinkable and self-scrolling, capped at 40%: a deep Files tree must give
// way before the playlists do, never push them off the sidebar.
return (
<div className="flex max-h-[40%] min-h-28 flex-col">
<div className="mt-3 flex items-center justify-between px-4">
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
Devices
@@ -97,43 +183,22 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
)}
</div>
<div className="mt-1 px-2">
{list.map((d) => {
const isOpen = d.path === openPath
return (
<div key={d.path}>
<button
onClick={() =>
isOpen ? onSelect({ kind: 'device' }) : openDevice.mutate(d.path)
}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${
isOpen && source.kind === 'device'
? 'is-selected text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<span className="flex w-4 justify-center text-gold"><Icon name="drive" size={15} /></span>
<span className="flex-1 truncate" title={d.path}>
{d.label}
</span>
{isOpen && open.data?.tracks != null && (
<span className="text-[10px] text-faint">{open.data.tracks}</span>
)}
</button>
<div className="mt-1 min-h-0 overflow-y-auto px-2 pb-1">
{external.map((d) => driveRow(d, 0))}
{isOpen &&
(playlists.data ?? []).map((n) => (
<DevicePlaylistRow
key={n.id}
node={n}
depth={1}
source={source}
onSelect={onSelect}
{local.length > 0 && (
<>
<TreeRow
depth={0}
icon={<Icon name="desktop" size={15} />}
label="Local Storage"
expanded={localOpen}
onToggle={() => setRow(localKey, !localOpen)}
onClick={() => setRow(localKey, !localOpen)}
/>
))}
</div>
)
})}
{localOpen && local.map((d) => driveRow(d, 1))}
</>
)}
{openDevice.isPending && (
<div className="px-2 py-1.5 text-xs text-faint">Opening…</div>
@@ -147,10 +212,152 @@ export function DevicesSection({ source, onSelect, onError, onImport }: Props) {
</button>
)}
</div>
</div>
)
}
function isInside(path: string, root: string): boolean {
const r = root.endsWith('/') || root.endsWith('\\') ? root : `${root}/`
return path === root || path.startsWith(r) || path.startsWith(root + '\\')
}
/** Indent per level, capped so a deep folder still has room for its name. */
function indent(depth: number): number {
return 4 + Math.min(depth, 8) * 12
}
/** One row of the tree: a chevron that expands, and a label that acts. */
function TreeRow({
depth,
icon,
label,
title,
expanded,
onToggle,
onClick,
selected = false,
trailing,
}: {
depth: number
icon: ReactNode
label: string
title?: string
expanded: boolean
onToggle: () => void
onClick: () => void
selected?: boolean
trailing?: ReactNode
}) {
return (
<div
style={{ paddingLeft: indent(depth) }}
className={`flex w-full items-center gap-1 rounded-md py-1 pr-2 text-sm transition-colors ${
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<button
aria-label={expanded ? 'Collapse' : 'Expand'}
onClick={onToggle}
className="flex h-4 w-4 shrink-0 items-center justify-center text-faint hover:text-text"
>
<Icon name={expanded ? 'chevronDown' : 'chevronRight'} size={12} />
</button>
<button onClick={onClick} title={title} className="flex min-w-0 flex-1 items-center gap-2 text-left">
<span className="flex w-4 shrink-0 justify-center">{icon}</span>
<span className="flex-1 truncate">{label}</span>
{trailing}
</button>
</div>
)
}
/**
* A folder in a Files tree. Clicking it shows its audio in the table (and
* expands it); the chevron only expands. Its subfolders are fetched the first
* time it opens, one level at a time.
*/
function FolderRow({
path,
name,
viewName,
icon,
depth,
source,
onSelect,
isOpenRow,
setRow,
}: {
path: string
name: string
/** What the table's header calls this folder, when not its own name. */
viewName?: string
icon: 'folder'
depth: number
source: Source
onSelect: (s: Source) => void
isOpenRow: (key: string) => boolean
setRow: (key: string, open: boolean) => void
}) {
const key = `folder:${path}`
const expanded = isOpenRow(key)
const children = useQuery({
queryKey: ['fs-folders', path],
queryFn: () => api.folders(path),
enabled: expanded,
staleTime: 10_000,
})
const selected = source.kind === 'folder' && source.path === path
return (
<>
<TreeRow
depth={depth}
icon={
<span className={selected ? 'text-accent' : 'text-faint'}>
<Icon name={expanded ? 'folderOpen' : icon} size={14} />
</span>
}
label={name}
title={path}
expanded={expanded}
onToggle={() => setRow(key, !expanded)}
onClick={() => {
setRow(key, true)
onSelect({ kind: 'folder', path, name: viewName ?? name })
}}
selected={selected}
/>
{expanded && (
<>
{children.isLoading && (
<div style={{ paddingLeft: indent(depth + 1) + 20 }} className="py-1 text-xs text-faint">
Loading…
</div>
)}
{children.isError && (
<div style={{ paddingLeft: indent(depth + 1) + 20 }} className="py-1 text-xs text-pink">
Can’t read this folder
</div>
)}
{(children.data ?? []).map((c) => (
<FolderRow
key={c.path}
path={c.path}
name={c.name}
icon="folder"
depth={depth + 1}
source={source}
onSelect={onSelect}
isOpenRow={isOpenRow}
setRow={setRow}
/>
))}
</>
)}
</>
)
}
/**
* A playlist on the device. Deliberately NOT `NodeRow`: that one carries rename
* and delete, and every one of a device's nodes reports those as false, so
@@ -176,7 +383,7 @@ function DevicePlaylistRow({
onClick={() =>
node.selectable && onSelect({ kind: 'device-playlist', id: node.id, name: node.name })
}
style={{ paddingLeft: 8 + depth * 12 }}
style={{ paddingLeft: indent(depth) + 20 }}
className={`flex w-full items-center gap-2 rounded-md py-1 pr-2 text-left text-sm transition-colors ${
selected
? 'is-selected text-text'
+17 -13
View File
@@ -8,6 +8,9 @@ import {
type GridMarker,
type Track,
type TrackCues,
type TrackOrigin,
trackAudioUrl,
trackCuesFor,
} from '../api'
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
import { slotLabeller, useCaps } from '../lib/capabilities'
@@ -36,12 +39,13 @@ interface Props {
/** Neutral/success feedback (e.g. Auto Hotcues result). */
onNotify?: (kind: 'success' | 'error', msg: string) => void
/**
* The track came from a browsed DEVICE, not the loaded library, so its audio
* and cues must be read from the source endpoints. Every EDIT control is
* already inert here — a device's capabilities say `writable: false`, and the
* deck gates on those — so this only needs to redirect the two READS.
* Which library the track belongs to, and so which endpoints serve its audio
* and cues: the loaded collection, a browsed DEVICE, or a browsed FOLDER of
* loose files. Every EDIT control is already inert for the last two — their
* capabilities say `writable: false`, and the deck gates on those — so this
* only needs to redirect the two READS.
*/
fromDevice?: boolean
origin?: TrackOrigin
/** Bumped when something outside the deck (batch grid analysis) rewrote the
* loaded track's cues/grid, so the deck re-reads them. */
cuesRefresh?: number
@@ -85,7 +89,7 @@ export function PrepStrip({
playRequest = 0,
onError,
onNotify,
fromDevice = false,
origin = 'collection',
cuesRefresh = 0,
}: Props) {
const qc = useQueryClient()
@@ -250,8 +254,8 @@ export function PrepStrip({
// Recolour the whole app from this track's cover art. A device's art is not
// served (only its audio is), so a device track keeps the default look.
useEffect(() => {
void setAmbientFromArt(trackId && !fromDevice ? api.artUrl(trackId) : null)
}, [trackId, fromDevice])
void setAmbientFromArt(trackId && origin === 'collection' ? api.artUrl(trackId) : null)
}, [trackId, origin])
// Analyse once per track; the decoded buffer feeds both the playback and
// scratch engines (no re-decode) and both waveform views share the columns.
@@ -266,7 +270,7 @@ export function PrepStrip({
let cancelled = false
setCols(null)
setWaveStatus('loading')
analyzeWaveform(fromDevice ? api.sourceAudioUrl(trackId) : api.audioUrl(trackId))
analyzeWaveform(trackAudioUrl(origin, trackId))
.then((res) => {
if (cancelled) return
setCols(res.cols)
@@ -297,7 +301,7 @@ export function PrepStrip({
return () => {
cancelled = true
}
}, [trackId, fromDevice])
}, [trackId, origin])
// Fetch beatgrid + cue markers for the loaded track.
useEffect(() => {
@@ -307,7 +311,7 @@ export function PrepStrip({
}
let cancelled = false
setCueData(null)
;(fromDevice ? api.sourceTrackCues(trackId) : api.trackCues(trackId))
;trackCuesFor(origin, trackId)
.then((d) => {
if (cancelled) return
setCueData(d)
@@ -322,7 +326,7 @@ export function PrepStrip({
return () => {
cancelled = true
}
}, [trackId, fromDevice])
}, [trackId, origin])
// Re-read after an outside edit. Deliberately NOT the effect above: that one
// resets `originalGridRef`, and "Reset" should still restore the grid the
@@ -1128,7 +1132,7 @@ export function PrepStrip({
<div className="glass flex h-[19.75rem] shrink-0 flex-col gap-2 p-4">
{/* ---- Header: the track, its readouts, the analysis actions ---- */}
<div className="flex h-12 shrink-0 items-center gap-3">
<CoverThumb trackId={track && !fromDevice ? track.id : null} />
<CoverThumb trackId={track && origin === 'collection' ? track.id : null} />
<div className="min-w-0 flex-1">
{track ? (
<>
+4 -1
View File
@@ -27,6 +27,9 @@ export type Source =
| { kind: 'playlist'; id: string; name: string }
| { kind: 'device' }
| { kind: 'device-playlist'; id: string; name: string }
// A folder of loose files on any drive, browsed from a Files tree. Its tracks
// are not in any library until added, so the view is read-only.
| { kind: 'folder'; path: string; name: string }
// An export set. `export` is its root — every track it would ship, deduped —
// and `export-playlist` is one referenced playlist inside it, read live from
// the library rather than from the set, which is the reference doing its job.
@@ -557,7 +560,7 @@ export function Sidebar({
{/* Right-click here (below the rows) creates at the top level; rows
stop the event so they get their own menu. */}
<div
className="mt-1 flex-1 overflow-y-auto px-2 pb-4"
className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4"
onContextMenu={(e) => openMenu(e, createItems(null))}
>
{draft?.parentId === null && <DraftRow draft={draft} depth={0} actions={actions} />}
+12 -1
View File
@@ -11,6 +11,7 @@ import {
type VisibilityState,
} from '@tanstack/react-table'
import { useVirtualizer } from '@tanstack/react-virtual'
import { Icon } from '../lib/icons'
import { useCaps } from '../lib/capabilities'
import {
DndContext,
@@ -64,6 +65,9 @@ interface Props {
/** The row-number column shows these (a playlist's own 1-based positions)
* instead of the row's place in the current view. */
positions?: Map<string, number>
/** Rows to flag in the # column with a check and this tooltip — a browsed
* folder uses it for files the collection already holds. */
marked?: { ids: Set<string>; title: string }
/** A view with a manual order. `enabled` is false while a sort or filter is
* active: reordering a partial or re-sorted list would lose the real order. */
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
@@ -263,6 +267,7 @@ export function TrackTable({
onColumnSizingChange,
selection,
positions,
marked,
reorder,
onRemove,
onRowContextMenu,
@@ -569,7 +574,13 @@ export function TrackTable({
}}
>
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
{positions?.get(row.original.id) ?? vr.index + 1}
{marked?.ids.has(row.original.id) ? (
<span title={marked.title} className="inline-flex text-mint">
<Icon name="check" size={13} />
</span>
) : (
(positions?.get(row.original.id) ?? vr.index + 1)
)}
</span>
{hasPlay && (
<span className="flex w-9 shrink-0 items-center justify-center">
+3
View File
@@ -53,6 +53,8 @@ export function readOnlyNotice(caps: Capabilities): string | null {
switch (caps.readonly_cause) {
case 'cloud_synced':
return `This ${caps.save.app_name} library is synced with ${caps.save.app_name} Cloud, so Konduktor will not write to it — an edit it did not make could break syncing on your other devices.`
case 'not_in_library':
return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.'
case 'platform_incomplete':
default:
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
@@ -62,6 +64,7 @@ export function readOnlyNotice(caps: Capabilities): string | null {
/** Compact form for a badge or a disabled control's tooltip. */
export function readOnlyShort(caps: Capabilities): string | null {
if (caps.writable) return null
if (caps.readonly_cause === 'not_in_library') return 'Not in collection'
return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only'
}