mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Added support for remote file exploring
This commit is contained in:
1 parent
966f3fe8c5
commit
40630ff78e
18 files changed
+717
-70
No files matched your search
@@ -568,7 +568,11 @@ Two independent apps that talk over HTTP:
|
||||
/ `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED
|
||||
to the content folder — resolve then `is_relative_to`, so neither `..`
|
||||
nor a symlink escapes — never overwriting, `-2` suffixes, per-session
|
||||
so a cancel deletes only its own), `fs/list|space`, `save`, `discard`,
|
||||
so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads`
|
||||
(the content folder as a Files tree: tags via the shared `FolderScanner`,
|
||||
file facts, `held` = file → the library's id; audio only for a file a
|
||||
listing returned, confined; `leads` = the analysis lead per file, None
|
||||
unless the platform analyses), `save`, `discard`,
|
||||
`history`, `export-sets`, and the stems routes below. Capabilities are
|
||||
the adapter's plus `tracks.audio_destination="library"`,
|
||||
`reference=False`, `paths.remappable=False`, `overwrite_risk="none"`.
|
||||
@@ -617,6 +621,21 @@ Two independent apps that talk over HTTP:
|
||||
Rekordbox's add analysis — waveform, grid AND key — is computed HERE
|
||||
(`core/add_analysis.prepare` with the lead the upload reports, sent as
|
||||
`NewTrack.analysis`).
|
||||
**The content folder browsed like a drive** (decided 2026-10-10,
|
||||
`folder.py`): `/api/fs/drives` lists the server FIRST (`kind:
|
||||
"server"`, path `server:`) while a remote is open, and the ordinary
|
||||
Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` +
|
||||
the path ON THE SERVER — so the folder view, deck and add dialog need no
|
||||
second set of routes, and a server path is never taken for the same path
|
||||
here. `RemoteAdapter.folder_listing` remembers what was listed
|
||||
(`ServerFiles`, a read-only source); `folder_audio` downloads into the
|
||||
shared cache by the same facts as a library track's. Adding one is IN
|
||||
PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`):
|
||||
nothing uploaded, nothing asked; files the library holds map to their
|
||||
ids; where the server reports a lead the file is fetched and analysed
|
||||
here, as an upload is. Server paths go back to the server in its own
|
||||
spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on
|
||||
Windows.
|
||||
**Convert to Stems** (`stems/remote_convert.py`): the server plans
|
||||
(`/v1/stems/plan`, its `convert.plan`), this computer downloads,
|
||||
separates and encodes, uploads each verified file (`/v1/stems/stage`,
|
||||
@@ -791,9 +810,17 @@ Two independent apps that talk over HTTP:
|
||||
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`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
table, with files the collection already holds checked off in the #
|
||||
column (`TrackTable`'s `marked`). **A held file's row IS the collection
|
||||
track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps
|
||||
its collection id back to the folder id that adding takes): it shows the
|
||||
collection's key/rating/cues/plays, loads into the deck as origin
|
||||
`collection` (`loadTrack`), edits inline and from the menu, and drops onto
|
||||
a playlist directly. The table runs on the COLLECTION's capabilities; a
|
||||
LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor
|
||||
opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add
|
||||
it first (`askToAdd`), and in the deck it stays read-only
|
||||
(`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for
|
||||
editing…"** — the drive row's right-click menu, and a button while browsing
|
||||
a device whose caps say `browsing` — opens it as THE library via App's
|
||||
`openForEditing` (unsaved-edits confirm, source closed, library opened).
|
||||
@@ -1413,7 +1440,11 @@ serialization path.** It enforces:
|
||||
only the edited `<ENTRY>` THROUGH the trip, one download per file, Analyze
|
||||
on the cached copy, export (and a re-export copying nothing), an upload
|
||||
stored in the mapping's stored form, takeover → read-only at once,
|
||||
reopening names the holder and the edits left, leaving releases.
|
||||
reopening names the holder and the edits left, leaving releases. And the
|
||||
content folder as a drive: listed first, confined, held files ticked off,
|
||||
auditioned with one download, an add IN PLACE (no upload, the held one not
|
||||
added twice, both into the playlist, analysed here when the server reports
|
||||
a lead).
|
||||
- `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine:
|
||||
the plan's transfer and two-machine space, Replace parks and swaps ON THE
|
||||
SERVER (saved file untouched until Save, which deletes the parked
|
||||
|
||||
@@ -30,6 +30,7 @@ from ... import remote_protocol as rp
|
||||
from ...core.adapter import (
|
||||
AudioFacts,
|
||||
FileTagResult,
|
||||
NotFound,
|
||||
SaveOutcome,
|
||||
Unavailable,
|
||||
Unsupported,
|
||||
@@ -39,6 +40,7 @@ from ...core.query import TrackIndex
|
||||
from .cache import RemoteAudioCache, StaleFacts
|
||||
from .cache import shared as shared_cache
|
||||
from .client import RemoteClient, SessionLost
|
||||
from .folder import ServerFile, ServerFiles
|
||||
from .session import RemoteSession
|
||||
|
||||
_NOT_HERE = "A remote library's paths are the server's configuration"
|
||||
@@ -60,6 +62,13 @@ class RemoteAdapter:
|
||||
self._facts: dict[str, AudioFacts] = {}
|
||||
#: Server path of an upload → (the local file it came from, its analysis lead).
|
||||
self._uploads: dict[str, tuple[Path, float | None]] = {}
|
||||
#: Content-folder files a listing returned, by their server path.
|
||||
self._listed: dict[str, ServerFile] = {}
|
||||
#: `str(Path(p))` → `p` for every server path this side has turned into
|
||||
#: a `Path` (an upload's target, a listed file): on Windows that
|
||||
#: conversion rewrites the separators, and the server must get its own
|
||||
#: spelling back.
|
||||
self._server_paths: dict[str, str] = {}
|
||||
self._dirty = bool(hello.get("dirty"))
|
||||
self._load()
|
||||
|
||||
@@ -260,6 +269,7 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead"))
|
||||
self._server_paths[str(Path(landed["path"]))] = landed["path"]
|
||||
return Path(landed["path"])
|
||||
|
||||
def free_space(self, path: str) -> int:
|
||||
@@ -268,8 +278,13 @@ class RemoteAdapter:
|
||||
|
||||
def delete_upload(self, path) -> None:
|
||||
"""Undo `upload_audio` (a cancelled or failed import)."""
|
||||
self._uploads.pop(str(path), None)
|
||||
self.client.delete_upload(str(path))
|
||||
key = self._server_key(path)
|
||||
self._uploads.pop(key, None)
|
||||
self.client.delete_upload(key)
|
||||
|
||||
def _server_key(self, path) -> str:
|
||||
text = str(path)
|
||||
return self._server_paths.get(text, text)
|
||||
|
||||
def add_tracks(self, items, *, checkpoint=None):
|
||||
"""Add uploaded files. Where the platform analyses what it adds (the
|
||||
@@ -279,10 +294,20 @@ class RemoteAdapter:
|
||||
|
||||
wire = []
|
||||
total = len(items)
|
||||
for n, item in enumerate(items, start=1):
|
||||
key = str(item.audio_path)
|
||||
keys = [self._server_key(item.audio_path) for item in items]
|
||||
# Files already in the content folder (added in place): the server says
|
||||
# whether the platform analyses, and only then is the file fetched.
|
||||
in_place = [k for k, item in zip(keys, items)
|
||||
if item.analysis is None and k not in self._uploads and k in self._listed]
|
||||
leads = self.client.folder_leads(in_place) if in_place else {}
|
||||
for n, (item, key) in enumerate(zip(items, keys), start=1):
|
||||
source, lead = self._uploads.get(key, (None, None))
|
||||
analysis = item.analysis
|
||||
if analysis is None and source is None and leads.get(key) is not None:
|
||||
lead = leads[key]
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total)
|
||||
source = self.folder_audio(key)
|
||||
if analysis is None and lead is not None and source is not None:
|
||||
if checkpoint is not None:
|
||||
checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total)
|
||||
@@ -302,8 +327,8 @@ class RemoteAdapter:
|
||||
self.session.lost(ex.holder)
|
||||
raise
|
||||
self._apply(envelope)
|
||||
for item in items:
|
||||
self._uploads.pop(str(item.audio_path), None)
|
||||
for key in keys:
|
||||
self._uploads.pop(key, None)
|
||||
return envelope["result"]
|
||||
|
||||
def apply_stem_swaps(self, swaps, *, add_to_playlist=None):
|
||||
@@ -393,6 +418,46 @@ class RemoteAdapter:
|
||||
facts = self.audio_facts([track_id]).get(track_id)
|
||||
return self.cache.get(facts) if facts else None
|
||||
|
||||
# ---- the content folder, browsed --------------------------------------------------
|
||||
def folder_listing(self, path: str | None) -> ServerFiles:
|
||||
"""The audio directly inside a content folder (None: the folder itself),
|
||||
as the server lists it — and remembered, so a file can then be played
|
||||
or added by its path."""
|
||||
listing = ServerFiles.from_wire(self, self.client.folder_tracks(path))
|
||||
with self._lock:
|
||||
self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path}
|
||||
self._listed.update(listing.files)
|
||||
self._server_paths.update({str(Path(k)): k for k in listing.files})
|
||||
return listing
|
||||
|
||||
def listed_files(self, paths) -> ServerFiles | None:
|
||||
"""The listed files among `paths` as one source (they may come from
|
||||
several folders); None when none of them was listed."""
|
||||
with self._lock:
|
||||
found = [self._listed[p] for p in paths if p in self._listed]
|
||||
return ServerFiles(self, found[0].folder, found) if found else None
|
||||
|
||||
def folder_audio(self, path: str, *, progress=None) -> Path:
|
||||
"""A local copy of a listed file, downloaded into the shared cache —
|
||||
keyed by the same facts as a library track's, so a file that is both
|
||||
downloads once."""
|
||||
for attempt in range(2):
|
||||
with self._lock:
|
||||
found = self._listed.get(path)
|
||||
if found is None:
|
||||
raise NotFound("File not found — browse to its folder first")
|
||||
cached = self.cache.get(found.facts)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.cache.fetch(
|
||||
found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress))
|
||||
except StaleFacts:
|
||||
if attempt:
|
||||
raise
|
||||
self.folder_listing(found.folder) # changed on the server: re-read it
|
||||
raise NotFound(path)
|
||||
|
||||
# ---- paths: the server's business ------------------------------------------------
|
||||
def set_path_mapping(self, mapping):
|
||||
raise Unsupported(_NOT_HERE)
|
||||
|
||||
@@ -246,6 +246,29 @@ class RemoteClient:
|
||||
def fs_list(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json()
|
||||
|
||||
def folder_tracks(self, path: str | None) -> dict:
|
||||
return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None,
|
||||
timeout=None).json()
|
||||
|
||||
def folder_leads(self, paths: list[str]) -> dict[str, float | None]:
|
||||
return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"]
|
||||
|
||||
def folder_download(self, path: str, target: Path, *, progress=None) -> dict:
|
||||
"""Stream a listed content-folder file into `target` (as `download`)."""
|
||||
with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response:
|
||||
if response.status_code >= 400:
|
||||
response.read()
|
||||
self.check(response)
|
||||
with open(target, "wb") as out:
|
||||
for chunk in response.iter_bytes(1 << 20):
|
||||
out.write(chunk)
|
||||
if progress is not None:
|
||||
progress(len(chunk))
|
||||
return {
|
||||
"size": int(response.headers.get("X-Konduktor-Size") or 0),
|
||||
"mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0),
|
||||
}
|
||||
|
||||
def fs_space(self, path: str | None) -> int:
|
||||
return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"])
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The server's content folder, browsed from this computer like a drive.
|
||||
|
||||
The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a
|
||||
remote library the music lives in the server's content folder, which this
|
||||
computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file
|
||||
facts, and which files the library already holds) and this module holds the
|
||||
answer as a read-only SOURCE, the shape the table, the deck and the importer
|
||||
already read.
|
||||
|
||||
Adding one of these files never uploads anything: it is already where the
|
||||
library can reach it, so it is added IN PLACE (`on_library_host`), and the
|
||||
importer skips both the copy and the copy-or-reference question.
|
||||
|
||||
Ids are the file's path ON THE SERVER — a string, never a `Path` on this side
|
||||
until the importer needs one, because a server path is not a path here (on a
|
||||
Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.adapter import AudioFacts
|
||||
from ...core.model import PlaylistNode, Track, TrackCues
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerFile:
|
||||
folder: str
|
||||
track: Track
|
||||
facts: AudioFacts
|
||||
#: The library's id for this file, when it already points at it.
|
||||
held: str | None = None
|
||||
|
||||
|
||||
class ServerFiles:
|
||||
"""Files in the content folder, as the read half of a source."""
|
||||
|
||||
#: The importer's cue that these are already on the machine holding the
|
||||
#: library: added where they are, neither copied nor uploaded.
|
||||
on_library_host = True
|
||||
|
||||
def __init__(self, adapter, path: str, files: list[ServerFile]):
|
||||
self.adapter = adapter
|
||||
self.path = path
|
||||
self._files = {f.track.id: f for f in files}
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, adapter, body: dict) -> "ServerFiles":
|
||||
folder = body["path"]
|
||||
facts = body.get("files") or {}
|
||||
held = body.get("held") or {}
|
||||
files = []
|
||||
for raw in body.get("tracks") or []:
|
||||
track = Track.model_validate(raw)
|
||||
fact = facts.get(track.id)
|
||||
if fact is None:
|
||||
continue
|
||||
files.append(ServerFile(
|
||||
folder=folder, track=track,
|
||||
facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])),
|
||||
held=held.get(track.id),
|
||||
))
|
||||
return cls(adapter, folder, files)
|
||||
|
||||
@property
|
||||
def files(self) -> dict[str, ServerFile]:
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def tracks(self) -> list[Track]:
|
||||
return [f.track for f in self._files.values()]
|
||||
|
||||
def track(self, track_id: str) -> Track | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.track if found else None
|
||||
|
||||
def held(self, track_id: str) -> str | None:
|
||||
found = self._files.get(track_id)
|
||||
return found.held if found else None
|
||||
|
||||
def size(self, track_id: str) -> int:
|
||||
found = self._files.get(track_id)
|
||||
return found.facts.size if found else 0
|
||||
|
||||
def track_cues(self, track_id: str) -> TrackCues | None:
|
||||
return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None
|
||||
|
||||
def audio_facts(self, track_ids) -> dict[str, AudioFacts]:
|
||||
return {t: self._files[t].facts for t in track_ids if t in self._files}
|
||||
|
||||
def audio_path(self, track_id: str, *, progress=None) -> Path | None:
|
||||
"""A local copy (downloaded into the shared cache, like a library track)."""
|
||||
if track_id not in self._files:
|
||||
return None
|
||||
return self.adapter.folder_audio(track_id, progress=progress)
|
||||
|
||||
def playlist_tree(self) -> list[PlaylistNode]:
|
||||
return []
|
||||
|
||||
def playlist_tracks(self, node_id: str) -> list[Track] | None:
|
||||
return None
|
||||
@@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids
|
||||
return plan
|
||||
|
||||
|
||||
def plan_on_host(source, track_ids) -> ImportPlan:
|
||||
"""A plan for files that are already on the machine holding the library — a
|
||||
remote library's content folder, browsed from this computer
|
||||
(`source.on_library_host`). Nothing is checked on THIS disk, where those
|
||||
paths mean nothing: the source says each file's size and which ones the
|
||||
library already holds. Added in place (`run(reference=True)`), so there is
|
||||
no destination and nothing to copy.
|
||||
"""
|
||||
plan = ImportPlan(destination=None)
|
||||
for track_id in dict.fromkeys(track_ids):
|
||||
track = source.track(track_id)
|
||||
if track is None:
|
||||
continue
|
||||
name = track_id.replace("\\", "/").rsplit("/", 1)[-1]
|
||||
plan.tracks.append(PlannedTrack(
|
||||
track_id=track_id,
|
||||
title=track.title or name,
|
||||
source_path=Path(track_id),
|
||||
size=source.size(track_id),
|
||||
existing_id=source.held(track_id),
|
||||
))
|
||||
return plan
|
||||
|
||||
|
||||
def _playlist_name(source, node_id: str) -> str | None:
|
||||
for nid, name in _all_playlists(source):
|
||||
if nid == node_id:
|
||||
@@ -321,7 +345,7 @@ def run(
|
||||
# a folder on the server, instead of copied here. Nothing can be left in
|
||||
# place — the server cannot see this computer's files.
|
||||
uploads = not places and uploads_audio(dest)
|
||||
if uploads and reference:
|
||||
if uploads and reference and not getattr(source, "on_library_host", False):
|
||||
raise ValueError("A remote library cannot reference files on this computer")
|
||||
if not reference and not places and not uploads:
|
||||
assert destination is not None
|
||||
|
||||
+124
-12
@@ -2183,6 +2183,50 @@ def source_track_stems(track_id: str) -> dict:
|
||||
|
||||
FOLDERS = FolderScanner()
|
||||
|
||||
# A remote library's content folder rides the same routes. Its paths carry this
|
||||
# prefix, so a path on the server can never be taken for the same path on this
|
||||
# computer — and the UI's folder view, deck and add dialog need no second set of
|
||||
# routes. The prefix alone is the content folder itself.
|
||||
SERVER_FOLDER = "server:"
|
||||
|
||||
|
||||
def _on_server(path: str) -> str | None:
|
||||
"""The server path behind a prefixed one ('' = the content folder), else None."""
|
||||
return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None
|
||||
|
||||
|
||||
def _server_track(track: Track) -> Track:
|
||||
return track.model_copy(update={"id": SERVER_FOLDER + track.id})
|
||||
|
||||
|
||||
def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]:
|
||||
"""A folder's files as table rows. Where the library holds a file, the row
|
||||
IS the library's track — its key, rating, comments, cues and plays, and
|
||||
its id, so it plays, edits and drags as the collection track it is
|
||||
(decided 2026-10-10) — else the file's own tags. Also returns library id →
|
||||
the file's folder id, for the rows that are library tracks: adding still
|
||||
speaks in folder ids."""
|
||||
rows: list[Track] = []
|
||||
files: dict[str, str] = {}
|
||||
for track in tracks:
|
||||
known = held_of(track)
|
||||
held = dest.track(known) if known else None
|
||||
if held is None or held.id in files:
|
||||
rows.append(track)
|
||||
continue
|
||||
rows.append(held)
|
||||
files[held.id] = track.id
|
||||
return rows, files
|
||||
|
||||
|
||||
def _server_file(track_id: str) -> tuple[object, str]:
|
||||
"""The remote adapter and the server path of a listed content-folder file."""
|
||||
adapter = _require_remote()
|
||||
raw = _on_server(track_id) or ""
|
||||
if adapter.listed_files([raw]) is None:
|
||||
raise HTTPException(404, "Track not found — browse to its folder first")
|
||||
return adapter, raw
|
||||
|
||||
|
||||
def _drive_of(path: Path, drives: list[dict]) -> dict | None:
|
||||
"""The drive `path` lives on: the longest drive root that contains it."""
|
||||
@@ -2209,6 +2253,10 @@ def fs_drives() -> list[Drive]:
|
||||
found = places.drives()
|
||||
libraries = sources()
|
||||
out = [Drive(**d) for d in found]
|
||||
if STATE.remote is not None and STATE.remote_config is not None:
|
||||
# The server holding the library, first: its content folder is where
|
||||
# this library's music is, and this computer cannot see it otherwise.
|
||||
out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server"))
|
||||
externals = [d for d in found if d["path"] != "/"]
|
||||
for lib in libraries:
|
||||
home = _drive_of(Path(lib.path), externals)
|
||||
@@ -2223,6 +2271,11 @@ def fs_drives() -> list[Drive]:
|
||||
@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."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
listing = _require_remote().client.fs_list(raw or None)
|
||||
return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"])
|
||||
for e in listing["entries"] if e["is_dir"]]
|
||||
base = Path(path).expanduser()
|
||||
if not base.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {base}")
|
||||
@@ -2236,16 +2289,27 @@ def _formats() -> list[str]:
|
||||
@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."""
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
adapter = _require_remote()
|
||||
listing = adapter.folder_listing(raw or None)
|
||||
rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks],
|
||||
lambda t: listing.held(t.id[len(SERVER_FOLDER):]))
|
||||
return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows,
|
||||
in_collection=list(files), files=files, removable=False)
|
||||
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())
|
||||
dest = require_adapter()
|
||||
held = importer._existing_files(dest)
|
||||
rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id))))
|
||||
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],
|
||||
tracks=rows,
|
||||
in_collection=list(files),
|
||||
files=files,
|
||||
removable=drive is None or drive["kind"] == "external",
|
||||
)
|
||||
|
||||
@@ -2263,11 +2327,17 @@ def _folder_track(track_id: str) -> FolderSource:
|
||||
def folder_capabilities(path: str) -> Capabilities:
|
||||
from .core.folder import capabilities_for
|
||||
|
||||
raw = _on_server(path)
|
||||
if raw is not None:
|
||||
return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server"))
|
||||
return capabilities_for(Path(path))
|
||||
|
||||
|
||||
@app.get("/api/folder/tracks/cues", response_model=TrackCues)
|
||||
def folder_track_cues(track_id: str) -> TrackCues:
|
||||
if _on_server(track_id) is not None:
|
||||
_server_file(track_id)
|
||||
return TrackCues(cues=[], grid_markers=[])
|
||||
cues = _folder_track(track_id).track_cues(track_id)
|
||||
assert cues is not None
|
||||
return cues
|
||||
@@ -2275,7 +2345,11 @@ def folder_track_cues(track_id: str) -> TrackCues:
|
||||
|
||||
@app.get("/api/folder/tracks/audio")
|
||||
def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
path = _folder_track(track_id).audio_path(track_id)
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
path = adapter.folder_audio(raw) # this computer's copy, as for a library track
|
||||
else:
|
||||
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")
|
||||
if stem is not None:
|
||||
@@ -2286,6 +2360,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse:
|
||||
|
||||
@app.get("/api/folder/tracks/stems")
|
||||
def folder_track_stems(track_id: str) -> dict:
|
||||
if _on_server(track_id) is not None:
|
||||
adapter, raw = _server_file(track_id)
|
||||
return _stem_layout_of(adapter.folder_audio(raw))
|
||||
return _stem_layout_of(_folder_track(track_id).audio_path(track_id))
|
||||
|
||||
|
||||
@@ -2295,6 +2372,34 @@ def _require_addable(dest) -> None:
|
||||
raise HTTPException(422, "Tracks cannot be added to this library")
|
||||
|
||||
|
||||
def _check_add_targets(dest, body: FolderAddRequest) -> None:
|
||||
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}")
|
||||
|
||||
|
||||
def _is_server_add(body: FolderAddRequest) -> bool:
|
||||
on_server = [_on_server(t) is not None for t in body.track_ids]
|
||||
if any(on_server) and not all(on_server):
|
||||
raise HTTPException(400, "Files on the server and on this computer are added separately")
|
||||
return bool(on_server) and all(on_server)
|
||||
|
||||
|
||||
def _server_add_plan(body: FolderAddRequest):
|
||||
"""Files in the remote library's content folder: already where the library
|
||||
can reach them, so they are added IN PLACE — nothing uploaded, nothing asked."""
|
||||
dest = _require_remote()
|
||||
_require_addable(dest)
|
||||
paths = [_on_server(t) for t in body.track_ids]
|
||||
source = dest.listed_files(paths)
|
||||
if source is None:
|
||||
raise HTTPException(400, "No tracks to add")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, importer.plan_on_host(source, paths)
|
||||
|
||||
|
||||
def _folder_add_plan(body: FolderAddRequest):
|
||||
dest = require_adapter()
|
||||
_require_addable(dest)
|
||||
@@ -2315,11 +2420,7 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
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}")
|
||||
_check_add_targets(dest, body)
|
||||
return source, dest, destination, importer.plan(
|
||||
source, dest, destination, track_ids=[t.id for t in tracks]
|
||||
)
|
||||
@@ -2327,6 +2428,11 @@ def _folder_add_plan(body: FolderAddRequest):
|
||||
|
||||
@app.post("/api/folder/add/preview")
|
||||
def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
if _is_server_add(body):
|
||||
_source, _dest, plan = _server_add_plan(body)
|
||||
out = plan.as_dict()
|
||||
out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False)
|
||||
return out
|
||||
_source, dest, destination, plan = _folder_add_plan(body)
|
||||
out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None)
|
||||
if importer.places_audio(dest):
|
||||
@@ -2343,10 +2449,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict:
|
||||
def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
"""Add browsed files to the collection. A job, like import: copying can be long."""
|
||||
_require_no_pending_stems("Adding files")
|
||||
source, dest, destination, plan = _folder_add_plan(body)
|
||||
in_place = _is_server_add(body)
|
||||
if in_place:
|
||||
source, dest, plan = _server_add_plan(body)
|
||||
destination = None
|
||||
else:
|
||||
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" or importer.places_audio(dest):
|
||||
# Nothing is copied in place, so there is no space to check.
|
||||
if not in_place and (body.mode == "copy" or importer.places_audio(dest)):
|
||||
free = importer.free_bytes(destination, dest)
|
||||
needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes
|
||||
if free is not None and free < needed + importer.SPACE_HEADROOM:
|
||||
@@ -2362,7 +2474,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
|
||||
def work(handle):
|
||||
result = importer.run(
|
||||
source, dest, plan, handle,
|
||||
reference=body.mode == "reference",
|
||||
reference=in_place or body.mode == "reference",
|
||||
into_playlist=body.playlist_id,
|
||||
)
|
||||
# Export sets are Konduktor's own data, not the library's, so they are
|
||||
|
||||
@@ -35,7 +35,8 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: at least its own: minors only add. Bump the minor for an added route or
|
||||
#: method, the major for anything an older client would misread.
|
||||
#: 1.1 — `move_playlist` (sidebar drag and drop).
|
||||
API_VERSION: tuple[int, int] = (1, 1)
|
||||
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
|
||||
API_VERSION: tuple[int, int] = (1, 2)
|
||||
|
||||
#: How long a session survives without a heartbeat, and how often the holder
|
||||
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
|
||||
|
||||
@@ -521,11 +521,15 @@ class Drive(BaseModel):
|
||||
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.
|
||||
|
||||
`server` is a remote library's content folder (path `server:`), listed
|
||||
first while a remote library is open — the one place its music can be
|
||||
browsed by folder from this computer.
|
||||
"""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
kind: Literal["local", "external"]
|
||||
kind: Literal["local", "external", "server"]
|
||||
library: SourceCandidate | None = None
|
||||
|
||||
|
||||
@@ -533,9 +537,13 @@ class FolderTracks(BaseModel):
|
||||
"""The audio files directly inside one folder, projected as tracks."""
|
||||
|
||||
path: str
|
||||
# A file the collection holds is listed AS the collection's track (its id,
|
||||
# key, rating, cues…); any other file as its own tags, id = its path.
|
||||
tracks: list[Track]
|
||||
# Ids (= absolute paths) of the files the collection already points at.
|
||||
# Collection ids of the rows that are collection tracks.
|
||||
in_collection: list[str]
|
||||
# Those rows' collection id → the file's folder id, which adding takes.
|
||||
files: dict[str, 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
|
||||
|
||||
@@ -44,6 +44,7 @@ from ..core.adapter import (
|
||||
NotFound,
|
||||
Unsupported,
|
||||
)
|
||||
from ..core.folder import FolderScanner
|
||||
from ..core.places import is_os_housekeeping
|
||||
from .config import ConfigError, ServerConfig
|
||||
from .session import InUse, Lost, SessionLock
|
||||
@@ -65,6 +66,10 @@ class Server:
|
||||
self.lock = lock or SessionLock()
|
||||
self.rev = 0
|
||||
self._rev_lock = threading.Lock()
|
||||
#: The content folder's audio as browsed from a client's Files tree —
|
||||
#: tags read once per folder state, and the gatekeeper for streaming
|
||||
#: one of those files (only a file a listing found is served).
|
||||
self.folders = FolderScanner()
|
||||
|
||||
# ---- opening ---------------------------------------------------------------
|
||||
def open(self) -> None:
|
||||
@@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI:
|
||||
"entries": entries,
|
||||
}
|
||||
|
||||
@app.get("/v1/folder/tracks")
|
||||
def folder_tracks(path: str | None = None) -> dict:
|
||||
"""The audio directly inside a content folder, projected as tracks — the
|
||||
client's Files tree for the server, like `/api/folder/tracks` for a
|
||||
drive of its own. Tags only (no decoding). `held` maps each file the
|
||||
library already points at to the library's id for it, so the client
|
||||
can tick it off and add it to a playlist without adding it twice."""
|
||||
from .. import importer
|
||||
|
||||
folder = server.confine(path)
|
||||
if not folder.is_dir():
|
||||
raise HTTPException(404, f"Not a folder: {folder}")
|
||||
adapter = server.adapter
|
||||
source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats)
|
||||
library = importer._existing_files(adapter)
|
||||
files, held = {}, {}
|
||||
for track in source.tracks:
|
||||
try:
|
||||
st = Path(track.id).stat()
|
||||
except OSError:
|
||||
continue
|
||||
files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
known = library.get(importer._key(Path(track.id)))
|
||||
if known is not None:
|
||||
held[track.id] = known
|
||||
return {
|
||||
"path": str(folder),
|
||||
"tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files],
|
||||
"files": files,
|
||||
"held": held,
|
||||
}
|
||||
|
||||
def listed_file(path: str) -> Path:
|
||||
# Confined (a symlink in a listing cannot lead out of the content
|
||||
# folder), and only a file a listing found: this is not a way to read
|
||||
# any path on the server.
|
||||
server.confine(path)
|
||||
source = server.folders.source_for_file(path)
|
||||
if source is None:
|
||||
raise HTTPException(404, "File not found — list its folder first")
|
||||
target = Path(path)
|
||||
if not target.is_file():
|
||||
raise HTTPException(404, "The audio file is missing")
|
||||
return target
|
||||
|
||||
@app.get("/v1/folder/audio")
|
||||
def folder_audio(path: str):
|
||||
target = listed_file(path)
|
||||
st = target.stat()
|
||||
media = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
|
||||
return FileResponse(target, media_type=media, headers={
|
||||
"X-Konduktor-Size": str(st.st_size),
|
||||
"X-Konduktor-Mtime-Ns": str(st.st_mtime_ns),
|
||||
})
|
||||
|
||||
@app.post("/v1/folder/leads")
|
||||
def folder_leads(body: dict = Body(...)) -> dict:
|
||||
"""The analysis lead of each listed file, as an upload reports it: what
|
||||
a client adding these files IN PLACE measures with. None for every file
|
||||
when the platform does not analyse what it adds."""
|
||||
lead = getattr(server.adapter, "analysis_lead", None)
|
||||
out = {}
|
||||
for path in body.get("paths") or []:
|
||||
target = listed_file(str(path))
|
||||
out[str(path)] = lead(target) if lead else None
|
||||
return {"leads": out}
|
||||
|
||||
@app.get("/v1/fs/space")
|
||||
def fs_space(path: str | None = None) -> dict:
|
||||
folder = server.confine(path)
|
||||
|
||||
@@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
|
||||
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"]))
|
||||
check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"]))
|
||||
row = next((t for t in body["tracks"] if t["id"] == added), None)
|
||||
check("…its row IS the collection track (its id and data), mapped back to the file",
|
||||
row is not None and body["files"] == {added: str(one)}
|
||||
and row["import_date"] == a.track(added).import_date, str(body["files"]))
|
||||
|
||||
print("== a held file is never added twice, but still reaches its target ==")
|
||||
library = STATE.library_id
|
||||
|
||||
@@ -293,6 +293,91 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3")
|
||||
for tr in main.require_adapter().tracks))
|
||||
|
||||
print("== the content folder, browsed like a drive ==")
|
||||
loose = make_mp3(content / "Crate" / "Loose One.mp3", seconds=3, seed=11)
|
||||
drives = c.get("/api/fs/drives").json()
|
||||
check("the server is listed first among the drives, under the remote's name",
|
||||
drives and drives[0] == {"name": "NAS", "path": "server:", "kind": "server", "library": None},
|
||||
drives[:1])
|
||||
tops = c.get("/api/fs/folders", params={"path": "server:"}).json()
|
||||
check("its Files tree starts at the content folder",
|
||||
{e["name"] for e in tops} >= {"Crate", "Mapped"}
|
||||
and all(e["path"].startswith("server:") for e in tops), tops)
|
||||
r = c.get("/api/folder/tracks", params={"path": f"server:{content}/Mapped"})
|
||||
listed = r.json()
|
||||
check("a folder's files the library holds are listed AS its tracks, ticked off",
|
||||
r.status_code == 200 and sorted(tr["id"] for tr in listed["tracks"]) == sorted(ids)
|
||||
and sorted(listed["in_collection"]) == sorted(ids) and not listed["removable"]
|
||||
and all(v.startswith("server:") for v in listed["files"].values()), r.text[:300])
|
||||
check("…with the collection's data, not the file's tags",
|
||||
next(tr for tr in listed["tracks"] if tr["id"] == target)["genre"] == "Remote Edit")
|
||||
r = c.get("/api/folder/tracks", params={"path": "server:/etc"})
|
||||
check("…and nothing outside the content folder is listed", r.status_code == 400, r.text[:200])
|
||||
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
|
||||
loose_id = f"server:{loose}"
|
||||
check("a file the library does not hold is listed unticked",
|
||||
[tr["id"] for tr in crate["tracks"]] == [loose_id] and crate["in_collection"] == [])
|
||||
caps = c.get("/api/folder/capabilities", params={"path": f"server:{content}/Crate"}).json()
|
||||
check("…read-only, like any browsed folder", not caps["writable"]
|
||||
and caps["readonly_cause"] == "not_in_library")
|
||||
folder_downloads = []
|
||||
real_folder_download = adapter.client.folder_download
|
||||
adapter.client.folder_download = lambda *a, **k: (folder_downloads.append(a[0]),
|
||||
real_folder_download(*a, **k))[1]
|
||||
r = c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
|
||||
check("the deck can audition it", r.status_code == 200 and r.content == loose.read_bytes())
|
||||
c.get("/api/folder/tracks/audio", params={"track_id": loose_id})
|
||||
check("…downloaded once", folder_downloads == [str(loose)], folder_downloads)
|
||||
r = c.get("/api/folder/tracks/audio", params={"track_id": f"server:{content}/Crate/nope.mp3"})
|
||||
check("a file no listing returned is not served", r.status_code == 404)
|
||||
srv_unlisted = httpx.get(f"http://127.0.0.1:{port}/v1/folder/audio",
|
||||
params={"path": str(work)}, auth=("dj", "secret"))
|
||||
check("…nor, asked of the server directly, anything outside the content folder",
|
||||
srv_unlisted.status_code == 400, srv_unlisted.text[:200])
|
||||
|
||||
pl = c.post("/api/playlists", json={"name": "From the server"}).json()["id"]
|
||||
held_track = listed["in_collection"][0]
|
||||
held_id = listed["files"][held_track] # adding speaks in folder ids
|
||||
add = {"track_ids": [loose_id, held_id], "mode": "reference", "playlist_id": pl}
|
||||
r = c.post("/api/folder/add/preview", json=add)
|
||||
pv = r.json()
|
||||
check("(preview) one new, one already held, nothing to copy",
|
||||
r.status_code == 200 and pv["importable"] == 1 and len(pv["existing"]) == 1
|
||||
and pv["total_bytes"] == 0 and pv["enough_space"] is None, r.text[:300])
|
||||
mixed = c.post("/api/folder/add/preview", json={**add, "track_ids": [loose_id, str(incoming)]})
|
||||
check("files here and on the server are not mixed in one add", mixed.status_code == 400)
|
||||
# Pretend the platform analyses what it adds (as Rekordbox does): the file
|
||||
# is then fetched and analysed HERE, and the server receives the result.
|
||||
received = []
|
||||
real_add = server_adapter.add_tracks
|
||||
server_adapter.add_tracks = lambda items, **k: (received.extend(items), real_add(items, **k))[1]
|
||||
server_adapter.analysis_lead = lambda path: 0.0
|
||||
before = sorted(p.name for p in content.rglob("*") if p.is_file())
|
||||
job = c.post("/api/folder/add", json=add).json()
|
||||
for _ in range(400):
|
||||
j = c.get(f"/api/jobs/{job['id']}").json()
|
||||
if j["state"] != "running":
|
||||
break
|
||||
time.sleep(0.05)
|
||||
del server_adapter.analysis_lead
|
||||
server_adapter.add_tracks = real_add
|
||||
added = [tr for tr in server_adapter.tracks if server_adapter.audio_path(tr.id) == loose]
|
||||
check("the file is added to the library WHERE IT IS", j["state"] == "done" and len(added) == 1,
|
||||
j.get("error"))
|
||||
check("…nothing uploaded or copied", sorted(p.name for p in content.rglob("*") if p.is_file()) == before)
|
||||
check("…analysed here on the cached copy, the result sent along",
|
||||
len(received) == 1 and received[0].analysis is not None and folder_downloads == [str(loose)],
|
||||
f"{len(received)} {folder_downloads}")
|
||||
entries = server_adapter.playlist_entries(pl) or []
|
||||
check("…both land in the playlist, the held one not added twice",
|
||||
added and entries == [added[0].id, held_track]
|
||||
and len(server_adapter.tracks) == len(main.require_adapter().tracks), entries)
|
||||
crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json()
|
||||
check("…and the folder now shows it ticked off, as the collection track",
|
||||
crate["in_collection"] == [added[0].id] and crate["files"] == {added[0].id: loose_id}
|
||||
if added else False, crate)
|
||||
check("the save is versioned on the server", not server_adapter.dirty)
|
||||
|
||||
print("== another computer takes over ==")
|
||||
other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret")
|
||||
other.acquire("other-client", "Studio iMac", takeover=True)
|
||||
|
||||
+92
-27
@@ -8,6 +8,7 @@ import { addTracksToPlaylist } from './lib/addTracks'
|
||||
import { useDropTarget } from './lib/drag'
|
||||
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
|
||||
import { confirmDiscardUnsaved } from './lib/unsaved'
|
||||
import { askConfirm } from './lib/confirm'
|
||||
import {
|
||||
COLUMN_MENU,
|
||||
DEFAULT_COLUMN_ORDER,
|
||||
@@ -80,6 +81,9 @@ export default function App() {
|
||||
const [prepOrigin, setPrepOrigin] = useState<TrackOrigin>('collection')
|
||||
// The view's origin, read by the load callbacks below (defined before it).
|
||||
const viewOriginRef = useRef<TrackOrigin>('collection')
|
||||
// The browsed folder's rows that ARE collection tracks: collection id → the
|
||||
// file's folder id. A ref, for the callbacks below that outlive a render.
|
||||
const folderFilesRef = useRef<Record<string, string>>({})
|
||||
// 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
|
||||
@@ -108,7 +112,9 @@ export default function App() {
|
||||
|
||||
const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
|
||||
setPrepTrack(t)
|
||||
setPrepOrigin(origin)
|
||||
// A folder row the collection holds IS the collection track, so the deck
|
||||
// loads it as one: its cues and grid, and editable (decided 2026-10-10).
|
||||
setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin)
|
||||
}, [])
|
||||
const playTrack = useCallback(
|
||||
(t: Track) => {
|
||||
@@ -307,6 +313,11 @@ export default function App() {
|
||||
() => new Set(folderView.data?.in_collection ?? []),
|
||||
[folderView.data],
|
||||
)
|
||||
const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data])
|
||||
folderFilesRef.current = viewingFolder ? folderFiles : {}
|
||||
// Adding speaks in FOLDER ids; a row the collection holds carries its
|
||||
// collection id, and maps back (the add dialog then reports it as held).
|
||||
const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id)
|
||||
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
|
||||
@@ -368,10 +379,16 @@ export default function App() {
|
||||
// asked (decided 2026-10-06).
|
||||
const addForeign = useCallback(
|
||||
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'folder') setAdding({ ids, target })
|
||||
else if (origin === 'device') setImportDrop({ ids, target })
|
||||
if (origin === 'folder') {
|
||||
const files = folderFilesRef.current
|
||||
// Rows that are all collection tracks already: nothing to add first.
|
||||
if (ids.every((id) => files[id])) {
|
||||
if (target.kind === 'playlist') void addToPlaylist(target.id, ids)
|
||||
else void addToExport(target.id, ids)
|
||||
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
|
||||
} else if (origin === 'device') setImportDrop({ ids, target })
|
||||
},
|
||||
[],
|
||||
[addToPlaylist, addToExport],
|
||||
)
|
||||
const [deckDropRef, deckOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'tracks' ? true : null),
|
||||
@@ -407,7 +424,10 @@ export default function App() {
|
||||
: origin === 'folder'
|
||||
? (folderCaps.data ?? readOnlyCaps('not_in_library'))
|
||||
: capabilities.data!
|
||||
const viewCaps = capsFor(viewOriginRef.current)
|
||||
// A folder's table runs on the COLLECTION's: the rows it holds are collection
|
||||
// tracks and edit as such, and a loose row asks to be added first
|
||||
// (`folderMayEdit`) rather than rendering inert.
|
||||
const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current)
|
||||
// The deck follows its TRACK's library, not the view's.
|
||||
const deckCaps = capsFor(prepOrigin)
|
||||
|
||||
@@ -443,9 +463,12 @@ export default function App() {
|
||||
// PrepStrip keys its audio on the id, so a new object for the same id
|
||||
// reloads nothing.
|
||||
useEffect(() => {
|
||||
if (!prepTrack || viewOriginRef.current !== prepOrigin) return
|
||||
if (!prepTrack) return
|
||||
const fresh = tracks.find((t) => t.id === prepTrack.id)
|
||||
if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
if (!fresh) return
|
||||
const origin =
|
||||
viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current
|
||||
if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh)
|
||||
// Only a refetch of the list matters; prepTrack is read, not tracked.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tracks])
|
||||
@@ -636,7 +659,7 @@ export default function App() {
|
||||
}
|
||||
|
||||
// ---- Convert to Stems ------------------------------------------------------
|
||||
const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible
|
||||
const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible
|
||||
const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (state === 'failed' || !r) {
|
||||
@@ -788,7 +811,7 @@ export default function App() {
|
||||
// the rest with a reason.
|
||||
const canAnalyzeGrid = !!capabilities.data?.grid.editable
|
||||
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
|
||||
const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey)
|
||||
const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey)
|
||||
|
||||
const startCueBatch = (ids: string[]) => {
|
||||
const byId = new Map(tracks.map((t) => [t.id, t]))
|
||||
@@ -801,7 +824,7 @@ export default function App() {
|
||||
setBatchCancelling(false)
|
||||
setBatchJob({ id: job.id, kind: 'cues' })
|
||||
}
|
||||
const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
|
||||
|
||||
|
||||
// ---- Remove ▸ -----------------------------------------------------------
|
||||
@@ -934,12 +957,48 @@ export default function App() {
|
||||
}),
|
||||
})
|
||||
|
||||
const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable
|
||||
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
|
||||
const canClearCues = canAutoCue
|
||||
const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable
|
||||
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
|
||||
// The COLLECTION's capabilities, deliberately: adding happens while a folder
|
||||
// or device is on screen, whose own capabilities are read-only.
|
||||
const canAddTracks = canEdit && !!capabilities.data?.tracks.addable
|
||||
|
||||
// In a folder, only the rows the collection holds can be edited. Anything
|
||||
// that would edit a loose file says so and offers to add it, rather than
|
||||
// being absent or silently inert (decided 2026-10-10).
|
||||
const askToAdd = async (ids: string[]) => {
|
||||
const loose = ids.filter((id) => !folderFiles[id])
|
||||
if (!loose.length) return
|
||||
const first = tracks.find((t) => t.id === loose[0])
|
||||
const what =
|
||||
loose.length === 1
|
||||
? `“${first?.title || 'This file'}” is not in your collection`
|
||||
: `${loose.length} of these files are not in your collection`
|
||||
if (!canAddTracks) {
|
||||
notify('error', `${what}, and tracks cannot be added to this library.`)
|
||||
return
|
||||
}
|
||||
const add = await askConfirm({
|
||||
title: 'Add to your collection first',
|
||||
body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`,
|
||||
confirmLabel: 'Add to Collection…',
|
||||
tone: 'primary',
|
||||
})
|
||||
if (add) setAdding({ ids: loose, target: null })
|
||||
}
|
||||
const folderEditField = (track: Track, field: keyof Track, value: string | number) => {
|
||||
if (folderFiles[track.id]) editField(track, field, value)
|
||||
else void askToAdd([track.id])
|
||||
}
|
||||
const folderMayEdit = (track: Track) => {
|
||||
if (folderFiles[track.id]) return true
|
||||
void askToAdd([track.id])
|
||||
return false
|
||||
}
|
||||
// The open menu's loose files: every editing item then asks to add them.
|
||||
const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : []
|
||||
const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn)
|
||||
const exportRootId =
|
||||
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
|
||||
const removeItems = (ids: string[]): MenuItem[] => [
|
||||
@@ -1023,8 +1082,8 @@ export default function App() {
|
||||
: []),
|
||||
// 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 && !viewForeign && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }]
|
||||
...(canEdit && !viewingDevice && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
|
||||
: []),
|
||||
...(canAnalyze
|
||||
? [
|
||||
@@ -1032,7 +1091,7 @@ export default function App() {
|
||||
label: 'Analyze…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setAnalyzing(menu.ids),
|
||||
onClick: gated(() => setAnalyzing(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -1044,20 +1103,20 @@ export default function App() {
|
||||
label: 'Auto Hotcues…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => startCueBatch(menu.ids),
|
||||
onClick: gated(() => startCueBatch(menu.ids)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Shown disabled WITH a reason where the platform cannot play stem
|
||||
// files as stems, rather than hidden: a missing item reads as a bug.
|
||||
...(canEdit && !viewForeign
|
||||
...(canEdit && !viewingDevice
|
||||
? [
|
||||
canStems
|
||||
? {
|
||||
label: 'Convert to Stems…',
|
||||
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
|
||||
disabled: !!batchJob,
|
||||
onClick: () => setStemDialog(menu.ids),
|
||||
onClick: gated(() => setStemDialog(menu.ids)),
|
||||
}
|
||||
: {
|
||||
label: 'Convert to Stems…',
|
||||
@@ -1070,12 +1129,14 @@ 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. A folder's files CAN be
|
||||
// added — through the add dialog, which puts them in the
|
||||
// collection first.
|
||||
// collection first; rows it already holds are collection tracks.
|
||||
...(viewingFolder
|
||||
? canAddTracks
|
||||
? !menuLoose.length
|
||||
? [{ label: 'Add to', submenu: addToItems(menu.ids) }]
|
||||
: canAddTracks
|
||||
? [
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(menu.ids) },
|
||||
{ label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) },
|
||||
{ label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) },
|
||||
]
|
||||
: [{
|
||||
label: 'Add to Collection…',
|
||||
@@ -1092,7 +1153,7 @@ export default function App() {
|
||||
? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }]
|
||||
: []),
|
||||
...(() => {
|
||||
const items = removeItems(menu.ids)
|
||||
const items = menuLoose.length ? [] : removeItems(menu.ids)
|
||||
return items.length ? [{ label: 'Remove', submenu: items }] : []
|
||||
})(),
|
||||
]}
|
||||
@@ -1315,9 +1376,11 @@ export default function App() {
|
||||
{' · 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 > heldInFolder.size && (
|
||||
<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 && canAddTracks && (
|
||||
<button
|
||||
onClick={() =>
|
||||
@@ -1325,7 +1388,7 @@ export default function App() {
|
||||
// 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)
|
||||
? toFolderIds(filtered.filter((t) => selected.has(t.id)).map((t) => t.id))
|
||||
: filtered.filter((t) => !heldInFolder.has(t.id)).map((t) => t.id),
|
||||
target: null,
|
||||
})
|
||||
@@ -1459,6 +1522,8 @@ export default function App() {
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? folderEditField : undefined}
|
||||
mayEdit={folderMayEdit}
|
||||
activeTrackId={prepTrack?.id ?? null}
|
||||
activePlaying={deckPlaying}
|
||||
columnVisibility={columnVisibility}
|
||||
|
||||
+14
-3
@@ -478,17 +478,28 @@ export interface ImportPreview {
|
||||
export interface Drive {
|
||||
name: string
|
||||
path: string
|
||||
/** `local` = boot disk or a drive built in; anything uncertain is external. */
|
||||
kind: 'local' | 'external'
|
||||
/** `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[]
|
||||
/** Ids of the files the collection already points at. */
|
||||
/** 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
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { placedAudioSummary } from '../lib/platformCopy'
|
||||
import { FolderPicker } from './FolderPicker'
|
||||
@@ -20,7 +20,10 @@ import { FolderPicker } from './FolderPicker'
|
||||
*
|
||||
* A library held by a server (`tracks.audio_destination === 'library'`) is the
|
||||
* other exception: it cannot see this computer's files, so the only choice is
|
||||
* which folder ON THE SERVER they are uploaded into.
|
||||
* which folder ON THE SERVER they are uploaded into — unless the files were
|
||||
* browsed in that server's own content folder: they are already where the
|
||||
* library can reach them, so they are added in place, uploaded nowhere and
|
||||
* nothing asked (decided 2026-10-10).
|
||||
*
|
||||
* 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
|
||||
@@ -57,11 +60,15 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
// decides copy vs in place itself, so there is nothing to ask.
|
||||
const caps = useCaps()
|
||||
const places = caps.tracks.places_audio
|
||||
// Already in the server's content folder: added where they are.
|
||||
const onServer = trackIds.length > 0 && trackIds.every(isServerPath)
|
||||
// Uploaded into a folder on the server: nothing to ask but where.
|
||||
const uploads = !places && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
|
||||
const uploads = !places && !onServer && caps.tracks.audio_destination === 'library'
|
||||
const [mode, setMode] = useState<'copy' | 'reference' | null>(
|
||||
onServer ? 'reference' : uploads ? 'copy' : null,
|
||||
)
|
||||
const [folder, setFolder] = useState('')
|
||||
const remote = useServerImportFolder(uploads)
|
||||
const remote = useServerImportFolder(uploads || onServer)
|
||||
const [browsing, setBrowsing] = useState(false)
|
||||
const [job, setJob] = useState<JobStatus | null>(null)
|
||||
const [starting, setStarting] = useState(false)
|
||||
@@ -251,7 +258,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && (
|
||||
{onServer && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-muted">
|
||||
Already on {remote.serverName}, so your collection points at them where they
|
||||
are. Nothing is uploaded or copied.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && !onServer && (
|
||||
<div className="space-y-1">
|
||||
{option(
|
||||
'copy',
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type Drive, type PlaylistNode } from '../api'
|
||||
import { api, isServerPath, type Drive, type PlaylistNode } from '../api'
|
||||
import type { Source } from './Sidebar'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
|
||||
/**
|
||||
* Every drive, in the sidebar: plugged-in ones under Devices, and the computer's
|
||||
* own under an expandable Local Storage.
|
||||
* own under an expandable Local Storage. While a remote library is open, the
|
||||
* server holding it comes first: its content folder, browsed like any drive.
|
||||
*
|
||||
* 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
|
||||
@@ -86,13 +87,15 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
|
||||
})
|
||||
|
||||
const list = drives.data ?? []
|
||||
const server = list.filter((d) => d.kind === 'server')
|
||||
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. The same goes for a
|
||||
// folder on it being browsed.
|
||||
// folder on it being browsed — and for a folder on the server, the remote
|
||||
// library being closed.
|
||||
const stillPresent = !openPath || list.some((d) => d.library?.path === openPath)
|
||||
useEffect(() => {
|
||||
if (!drives.isSuccess || !openPath || stillPresent || eject.isPending) return
|
||||
@@ -102,7 +105,11 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
|
||||
const folderGone =
|
||||
source.kind === 'folder' &&
|
||||
drives.isSuccess &&
|
||||
!list.some((d) => d.path === '/' || isInside(source.path, d.path))
|
||||
!list.some((d) =>
|
||||
isServerPath(source.path)
|
||||
? d.kind === 'server'
|
||||
: d.path === '/' || isInside(source.path, d.path),
|
||||
)
|
||||
useEffect(() => {
|
||||
if (folderGone) onSelect({ kind: 'all' })
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -137,7 +144,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
|
||||
<div key={d.path}>
|
||||
<TreeRow
|
||||
depth={depth}
|
||||
icon={<span className="text-gold"><Icon name="drive" size={15} /></span>}
|
||||
icon={<span className="text-gold"><Icon name={d.kind === 'server' ? 'server' : 'drive'} size={15} /></span>}
|
||||
label={d.name}
|
||||
title={d.path}
|
||||
expanded={expandedHere}
|
||||
@@ -212,6 +219,7 @@ export function DevicesSection({ source, onSelect, onError, onImport, onOpenLibr
|
||||
</div>
|
||||
|
||||
<div className="mt-1 min-h-0 overflow-y-auto px-2 pb-1">
|
||||
{server.map((d) => driveRow(d, 0))}
|
||||
{external.map((d) => driveRow(d, 0))}
|
||||
|
||||
{local.length > 0 && (
|
||||
|
||||
@@ -82,6 +82,8 @@ interface Props {
|
||||
onHeaderContextMenu?: (x: number, y: number) => void
|
||||
onPlay?: (track: Track) => void
|
||||
onEditField?: (track: Track, field: keyof Track, value: string | number) => void
|
||||
/** Per-row gate on opening an inline editor (`TableMeta.mayEdit`). */
|
||||
mayEdit?: (track: Track) => boolean
|
||||
activeTrackId?: string | null
|
||||
/** Whether the deck is playing `activeTrackId` (vs. loaded but paused). */
|
||||
activePlaying?: boolean
|
||||
@@ -287,6 +289,7 @@ export function TrackTable({
|
||||
onHeaderContextMenu,
|
||||
onPlay,
|
||||
onEditField,
|
||||
mayEdit,
|
||||
activeTrackId,
|
||||
activePlaying = false,
|
||||
}: Props) {
|
||||
@@ -299,7 +302,7 @@ export function TrackTable({
|
||||
data,
|
||||
columns: TRACK_COLUMNS,
|
||||
state: { sorting, columnVisibility, columnOrder, columnSizing },
|
||||
meta: { onEditField, editableFields },
|
||||
meta: { onEditField, editableFields, mayEdit },
|
||||
onSortingChange: (updater) =>
|
||||
onSortingChange(typeof updater === 'function' ? updater(sorting) : updater),
|
||||
onColumnSizingChange: (updater) =>
|
||||
|
||||
@@ -29,6 +29,10 @@ declare module '@tanstack/react-table' {
|
||||
* platforms genuinely differ in WHICH fields they accept. Undefined means
|
||||
* "not gated" — every field with a handler stays editable. */
|
||||
editableFields?: ReadonlySet<string>
|
||||
/** Asked before an inline editor opens on a row; false keeps it closed.
|
||||
* A view mixing editable rows with others (a folder: collection tracks
|
||||
* beside loose files) answers per row — and says why itself. */
|
||||
mayEdit?: (track: Track) => boolean
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +46,7 @@ function InlineEdit({
|
||||
onCommit,
|
||||
className = 'w-full min-w-0 truncate text-muted',
|
||||
readOnly = false,
|
||||
onBegin,
|
||||
}: {
|
||||
value: string | null
|
||||
display?: ReactNode
|
||||
@@ -49,6 +54,8 @@ function InlineEdit({
|
||||
className?: string
|
||||
/** Render the value without offering an editor. */
|
||||
readOnly?: boolean
|
||||
/** Asked on double-click; false keeps the editor closed. */
|
||||
onBegin?: () => boolean
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [val, setVal] = useState('')
|
||||
@@ -91,6 +98,7 @@ function InlineEdit({
|
||||
<div
|
||||
onDoubleClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (onBegin && !onBegin()) return
|
||||
setVal(value ?? '')
|
||||
setEditing(true)
|
||||
}}
|
||||
@@ -102,6 +110,11 @@ function InlineEdit({
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether this row's editor may open (`TableMeta.mayEdit`). */
|
||||
function mayBegin(c: CellContext<Track, unknown>): boolean {
|
||||
return c.table.options.meta?.mayEdit?.(c.row.original) ?? true
|
||||
}
|
||||
|
||||
/** Whether this table may edit `field`, per the platform's capabilities. */
|
||||
function canEdit(c: CellContext<Track, unknown>, field: string): boolean {
|
||||
const meta = c.table.options.meta
|
||||
@@ -116,6 +129,7 @@ function editable(field: keyof Track, className?: string) {
|
||||
value={c.getValue() as string | null}
|
||||
className={className}
|
||||
readOnly={!canEdit(c, field)}
|
||||
onBegin={() => mayBegin(c)}
|
||||
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, field, v)}
|
||||
/>
|
||||
)
|
||||
@@ -137,12 +151,14 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
|
||||
display={title || <span className="text-faint">Untitled</span>}
|
||||
className="w-full min-w-0 truncate font-medium text-text group-data-[active]:text-accent"
|
||||
readOnly={!canEdit(c, 'title')}
|
||||
onBegin={() => mayBegin(c)}
|
||||
onCommit={(v) => edit?.(r, 'title', v)}
|
||||
/>
|
||||
<InlineEdit
|
||||
value={r.artist}
|
||||
className="w-full min-w-0 truncate text-xs text-muted"
|
||||
readOnly={!canEdit(c, 'artist')}
|
||||
onBegin={() => mayBegin(c)}
|
||||
onCommit={(v) => edit?.(r, 'artist', v)}
|
||||
/>
|
||||
</div>
|
||||
@@ -310,6 +326,7 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
|
||||
value={c.getValue() as string | null}
|
||||
display={<span className="tabular-nums text-muted">{formatDate(c.getValue() as string | null)}</span>}
|
||||
readOnly={!canEdit(c, 'release_date')}
|
||||
onBegin={() => mayBegin(c)}
|
||||
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'release_date', v)}
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -11,6 +11,8 @@ const TRACK_LIST_KEYS = [
|
||||
['export-tracks'],
|
||||
['export-playlist-tracks'],
|
||||
['export-loose'],
|
||||
// A folder lists the files the collection holds AS collection tracks.
|
||||
['folder-tracks'],
|
||||
] as const
|
||||
|
||||
/** Refetch every collection track list, plus the unsaved-edits state. */
|
||||
|
||||
Reference in new issue
Block a user