mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Extended OneLibrary support
This commit is contained in:
1 parent
0b38d4826f
commit
ba3e7c251e
14 files changed
+851
-7
No files matched your search
@@ -236,6 +236,9 @@ class OneLibraryAdapter:
|
||||
def _refuse(self, what: str):
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
|
||||
self._refuse("Editing track metadata")
|
||||
|
||||
|
||||
@@ -14,6 +14,11 @@ log = logging.getLogger(__name__)
|
||||
class OneLibraryDriver:
|
||||
platform = "onelibrary"
|
||||
display_name = "OneLibrary"
|
||||
# This platform's libraries live on plugged-in drives rather than at a
|
||||
# fixed path, so `detect()` genuinely changes between calls and the app
|
||||
# offers them as IMPORT SOURCES. Declared rather than inferred from the
|
||||
# platform name, so a future Serato-on-a-stick needs no change upstream.
|
||||
removable = True
|
||||
suffixes = (".db",)
|
||||
library_label = "exportLibrary.db"
|
||||
|
||||
|
||||
@@ -385,6 +385,14 @@ class RekordboxAdapter:
|
||||
if self._cloud_synced:
|
||||
raise Unsupported(self._readonly_reason(what))
|
||||
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
# Not a refusal in principle — Rekordbox could receive imported
|
||||
# tracks — but adding one means a djmdContent row, its lookup-table
|
||||
# foreign keys, a USN, and an ANLZ file built from scratch, which
|
||||
# is unexplored (see the export handoff). Traktor is the only
|
||||
# import target for now.
|
||||
self._refuse("Adding tracks")
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
|
||||
@@ -146,6 +146,100 @@ class TraktorAdapter:
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
return self._store.cover_art(track_id)
|
||||
|
||||
# ---- adding tracks ----------------------------------------------------
|
||||
def add_tracks(self, items: list) -> list[str]:
|
||||
"""Add tracks that came from somewhere else, with their prep.
|
||||
|
||||
Two steps, and the split is the point. The store creates a bare ENTRY —
|
||||
the only genuinely new code — and then the track's cues and grid are
|
||||
written by **replaying the ordinary commands** onto it. So an imported
|
||||
track's beatgrid goes in through the same `replace_grid` that the deck's
|
||||
Reset button uses, and inherits its companion-cue handling, its TEMPO
|
||||
mirroring and its tests, rather than growing a second implementation
|
||||
that would drift.
|
||||
|
||||
Lossiness follows the settled rule — degrade to the nearest equivalent,
|
||||
drop only where none exists:
|
||||
|
||||
* **Memory cues become hot cues in spare slots.** Traktor has no
|
||||
memory cues, and every Traktor cue occupies a slot. Filling the
|
||||
leftovers preserves the positions a DJ actually marked; when the
|
||||
bank is full the rest are dropped, because there is nowhere left.
|
||||
* **Cue colour is dropped.** Traktor derives a cue's colour from its
|
||||
type, so a free RGB value has nowhere to go.
|
||||
|
||||
Returns the new track ids, in the order the items were given.
|
||||
"""
|
||||
added: list[str] = []
|
||||
for item in items:
|
||||
audio = Path(item.audio_path)
|
||||
if not audio.is_file():
|
||||
raise InvalidCommand(f"No audio file at {audio}")
|
||||
with _translate():
|
||||
track_id = self._store.add_entry(item.track, audio)
|
||||
# Into the projection BEFORE the cues are replayed: those go through
|
||||
# the ordinary commands, and those look the track up by id.
|
||||
entry = self._store.model_entry(track_id)
|
||||
self._index.add(projection.to_track(entry))
|
||||
added.append(track_id)
|
||||
if item.cues is not None:
|
||||
self._apply_imported_cues(track_id, item.cues)
|
||||
self._refresh(track_id)
|
||||
return added
|
||||
|
||||
def _apply_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""Replay a generic TrackCues onto a freshly added entry."""
|
||||
markers = [(m.start, m.bpm) for m in (cues.grid_markers or [])]
|
||||
if markers:
|
||||
# `replace_grid`, NOT `set_analysed_grid`. The latter also places
|
||||
# Traktor's beat-1 companion cue, and that is wrong twice over here:
|
||||
# it invents a cue the source never had (companions are a Traktor
|
||||
# convention, and the project's rule is to follow them but never
|
||||
# invent one outside Auto Grid), and it occupies pad A — which
|
||||
# silently displaced the imported track's own pad A cue.
|
||||
self.replace_grid(track_id, markers)
|
||||
|
||||
slots = self.capabilities().cues.hotcue_slots
|
||||
taken = {c.slot for c in self.track_cues(track_id).cues if c.slot is not None}
|
||||
hotcues = [c for c in (cues.cues or []) if c.role == "hotcue" and c.slot is not None]
|
||||
|
||||
# Hot cues keep the pad they were on wherever that pad is free, because
|
||||
# muscle memory is most of what a hot cue layout IS.
|
||||
displaced: list = []
|
||||
for cue in sorted(hotcues, key=lambda c: c.slot):
|
||||
if cue.slot in taken or not (0 <= cue.slot < slots):
|
||||
displaced.append(cue)
|
||||
continue
|
||||
self._place_imported_cue(track_id, cue.slot, cue)
|
||||
taken.add(cue.slot)
|
||||
|
||||
# Everything without a pad of its own competes for what is left: memory
|
||||
# cues, which Traktor has no equivalent for, and any hot cue whose pad
|
||||
# was already occupied. Earliest first, so that when the bank runs out
|
||||
# it is the late cues that are lost rather than an arbitrary set — and
|
||||
# a displaced hot cue is moved rather than dropped, because losing one
|
||||
# silently is much worse than having it turn up on the wrong pad.
|
||||
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
|
||||
spare = (s for s in range(slots) if s not in taken)
|
||||
for cue in sorted(leftovers, key=lambda c: c.start):
|
||||
slot = next(spare, None)
|
||||
if slot is None:
|
||||
break # bank full: the rest are dropped, per the lossiness rule
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
|
||||
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
if cue_type not in CUE_TYPE_TO_NATIVE:
|
||||
return
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
start_sec=cue.start,
|
||||
cue_type=cue_type,
|
||||
length_sec=getattr(cue, "length", 0.0) or 0.0,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
|
||||
# ---- cues -------------------------------------------------------------
|
||||
def _native_cue_type(self, cue_type: str) -> int:
|
||||
native = CUE_TYPE_TO_NATIVE.get(cue_type)
|
||||
|
||||
@@ -34,6 +34,7 @@ from traktor_nml_utils.models.collection import (
|
||||
Entrytype,
|
||||
GridType,
|
||||
Infotype,
|
||||
Locationtype,
|
||||
Nodetype,
|
||||
Playlisttype,
|
||||
Primarykeytype,
|
||||
@@ -307,6 +308,80 @@ class TraktorStore:
|
||||
self._journal.record("track", "set", track_id, k)
|
||||
self.dirty = True
|
||||
|
||||
# ---- adding tracks --------------------------------------------------
|
||||
def add_entry(self, track, audio_path: Path) -> str:
|
||||
"""Append a brand-new ENTRY for `audio_path` and return its track id.
|
||||
|
||||
The one place Konduktor builds a collection entry instead of editing one
|
||||
Traktor wrote. Two rules make that safe:
|
||||
|
||||
* **Append only.** The new ENTRY goes on the end of COLLECTION and
|
||||
nothing else is touched, so every existing entry still renders the
|
||||
bytes it was parsed from. `test_save_fidelity.py` checks exactly
|
||||
that rather than trusting it.
|
||||
* **The primary key must be free.** Traktor keys playlist entries on
|
||||
``volume+dir+file``, so two ENTRYs sharing one is a corrupt
|
||||
collection, not a duplicate track. Importing copies audio to a fresh
|
||||
filename, which is what keeps repeat imports honest.
|
||||
|
||||
Deliberately left empty: ``audio_id`` (Traktor's analysis fingerprint)
|
||||
and ``loudness``. Both are outputs of Traktor's own analysis and cannot
|
||||
be computed here; Traktor re-analyses a track that has none. Writing a
|
||||
plausible-looking fingerprint would be inventing data.
|
||||
"""
|
||||
with self._lock:
|
||||
volume, dir_, file = os_path_to_location(Path(audio_path))
|
||||
key = f"{volume}{dir_}{file}"
|
||||
if key in self._entry_by_key:
|
||||
raise PlaylistError(
|
||||
f"The collection already has an entry for {audio_path}"
|
||||
)
|
||||
|
||||
info = Infotype(
|
||||
genre=getattr(track, "genre", None) or None,
|
||||
label=getattr(track, "label", None) or None,
|
||||
comment=getattr(track, "comment", None) or None,
|
||||
remixer=getattr(track, "remixer", None) or None,
|
||||
producer=getattr(track, "producer", None) or None,
|
||||
mix=getattr(track, "mix", None) or None,
|
||||
key=getattr(track, "key", None) or None,
|
||||
bitrate=getattr(track, "bitrate", None) or None,
|
||||
playcount=getattr(track, "playcount", None) or None,
|
||||
release_date=getattr(track, "release_date", None) or None,
|
||||
import_date=getattr(track, "import_date", None) or None,
|
||||
# Traktor's RANKING is stars x 51; an unrated track has no
|
||||
# attribute at all rather than a zero.
|
||||
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
|
||||
playtime=getattr(track, "length", None) or None,
|
||||
)
|
||||
album = None
|
||||
if getattr(track, "album", None):
|
||||
album = Albumtype(title=track.album)
|
||||
|
||||
bpm = getattr(track, "bpm", None)
|
||||
entry = Entrytype(
|
||||
location=Locationtype(volume=volume, dir=dir_, file=file),
|
||||
title=getattr(track, "title", None) or None,
|
||||
artist=getattr(track, "artist", None) or None,
|
||||
album=album,
|
||||
info=info,
|
||||
# TEMPO mirrors the first grid marker. It is set here from the
|
||||
# projected BPM so a track with no grid still shows a tempo;
|
||||
# `replace_grid` overwrites it from the markers when they land.
|
||||
tempo=Tempotype(bpm=float(bpm)) if bpm else None,
|
||||
cue_v2=[],
|
||||
)
|
||||
self._nml.collection.entry.append(entry)
|
||||
self._entry_by_key[key] = entry
|
||||
# `<COLLECTION ENTRIES="N">` is a real count Traktor writes and
|
||||
# reads, not decoration. No existing command changes how many
|
||||
# entries there are, so nothing has ever had to maintain it —
|
||||
# leaving it stale is a corrupt file that still looks well-formed.
|
||||
self._nml.collection.entries = len(self._nml.collection.entry)
|
||||
self._note("track", "add", key)
|
||||
self.dirty = True
|
||||
return key
|
||||
|
||||
def iter_entries(self):
|
||||
"""Every collection ENTRY in document order.
|
||||
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
"""The one loaded library, and the version-history bookkeeping around saving it.
|
||||
"""The loaded library, and the version-history bookkeeping around saving it.
|
||||
|
||||
Exactly one library is open at a time: that keeps every edit and every save
|
||||
unambiguous about what it targets, and it is why the adapter can own its own
|
||||
projection without anyone asking which library a command meant.
|
||||
Exactly one library is open **for editing** at a time: that keeps every edit and
|
||||
every save unambiguous about what it targets, and it is why the adapter can own
|
||||
its own projection without anyone asking which library a command meant.
|
||||
|
||||
A **source** may be open alongside it, and only alongside it. A source is a
|
||||
library being read FROM — a plugged-in OneLibrary stick whose tracks are about to
|
||||
be imported — and it is deliberately not symmetrical with the loaded library:
|
||||
|
||||
* it is **never written**, so no command can be ambiguous about its target;
|
||||
* it is **never saved**, so version history has nothing to disambiguate;
|
||||
* it is **never the fallback** when nothing is loaded — a source with no
|
||||
destination is a browser, not a library, and the routes say so.
|
||||
|
||||
That asymmetry is what keeps "exactly one library is open" true in the sense that
|
||||
mattered: there is still exactly one thing a command can mean.
|
||||
|
||||
Version history lives here rather than in the adapter. An adapter's job is to
|
||||
write its own format faithfully; knowing that Konduktor keeps a git-backed
|
||||
@@ -27,11 +39,53 @@ class AppState:
|
||||
def __init__(self) -> None:
|
||||
self.path: Path | None = None
|
||||
self.adapter: LibraryAdapter | None = None
|
||||
# The library being read FROM, if any. Read-only by contract; see the
|
||||
# module docstring for why it is not symmetrical with `adapter`.
|
||||
self.source_path: Path | None = None
|
||||
self.source: LibraryAdapter | None = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
return self.adapter is not None
|
||||
|
||||
@property
|
||||
def source_loaded(self) -> bool:
|
||||
return self.source is not None
|
||||
|
||||
# ---- the source library ---------------------------------------------
|
||||
def open_source(self, path: Path) -> None:
|
||||
"""Open a library to read from, alongside the loaded one.
|
||||
|
||||
Refuses a source that is not read-only. Nothing downstream sends it a
|
||||
command, but "this is only ever read" is the assumption the whole slot
|
||||
rests on, and an adapter is the thing that knows whether it is true —
|
||||
so it is asserted here rather than assumed everywhere else.
|
||||
"""
|
||||
adapter = registry.open_library(path)
|
||||
if adapter.capabilities().writable:
|
||||
if hasattr(adapter, "close"):
|
||||
try:
|
||||
adapter.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise ValueError(
|
||||
f"{path} is a writable library; only read-only sources "
|
||||
"(such as a OneLibrary drive) can be opened as a source"
|
||||
)
|
||||
self.close_source()
|
||||
self.source_path, self.source = path, adapter
|
||||
|
||||
def close_source(self) -> None:
|
||||
"""Release the source. Load-bearing: a source lives on a REMOVABLE drive,
|
||||
and a held file handle is what stops a stick ejecting."""
|
||||
previous, self.source = self.source, None
|
||||
self.source_path = None
|
||||
if previous is not None and hasattr(previous, "close"):
|
||||
try:
|
||||
previous.close()
|
||||
except Exception: # noqa: BLE001 — a failed close must not block
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
# The registry picks the adapter by probing the file, not by extension —
|
||||
# a Rekordbox library is a .db and a Serato one is a directory. Raises on
|
||||
|
||||
@@ -49,6 +49,31 @@ class SaveOutcome:
|
||||
tag_results: list = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class NewTrack:
|
||||
"""A track to ADD to a library, described generically.
|
||||
|
||||
Import is the first operation that puts a track into a library that never
|
||||
had one, so it needs a way to say "here is a track" without naming a
|
||||
platform. That is all this is: the generic projection of a track, plus the
|
||||
audio file it should point at.
|
||||
|
||||
* `track` carries the metadata. **Its `id` is ignored** — an id belongs to
|
||||
the library that holds the track, and this one comes from somewhere
|
||||
else. The receiving adapter assigns its own and returns it.
|
||||
* `cues` is optional because a track can be imported without prep, and
|
||||
because a platform may hold the track but not (yet) its cues.
|
||||
* `audio_path` is a path on THIS machine that must already exist. Copying
|
||||
the audio is the caller's job, deliberately: an adapter's business is
|
||||
the library, and a file copy that failed halfway is not something a
|
||||
library write should be discovering.
|
||||
"""
|
||||
|
||||
track: Track
|
||||
audio_path: Path
|
||||
cues: TrackCues | None = None
|
||||
|
||||
|
||||
class AdapterError(Exception):
|
||||
"""Base for every failure an adapter reports to the HTTP layer."""
|
||||
|
||||
@@ -97,6 +122,15 @@ class LibraryAdapter(Protocol):
|
||||
def delete_playlist(self, node_id: str) -> None: ...
|
||||
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
|
||||
|
||||
# ---- commands: adding tracks ----------------------------------------
|
||||
# The ONLY command that creates a track rather than editing one, and the
|
||||
# one place the "retained native model" rule is stretched: everywhere else
|
||||
# the write target was parsed from a real file, which is what makes the
|
||||
# fidelity guarantee hold. A new entry has no parsed original, so the rule
|
||||
# becomes "an added entry must not perturb any existing one" — which is
|
||||
# what `test_save_fidelity.py` checks rather than taking on trust.
|
||||
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
|
||||
|
||||
# ---- commands: track metadata / art ---------------------------------
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
@@ -149,6 +183,11 @@ class LibraryDriver(Protocol):
|
||||
platform: str
|
||||
display_name: str
|
||||
suffixes: tuple[str, ...]
|
||||
# True when this platform's libraries live on plugged-in media rather than at
|
||||
# a fixed path — so `detect()` genuinely changes between calls, and the app
|
||||
# can offer them as import SOURCES. Optional, and False for a platform that
|
||||
# does not set it, because most keep one library in a known place.
|
||||
removable: bool
|
||||
|
||||
def can_open(self, path: Path) -> bool: ...
|
||||
def open(self, path: Path) -> LibraryAdapter: ...
|
||||
|
||||
@@ -62,8 +62,25 @@ class EditJournal:
|
||||
}
|
||||
|
||||
def edited_tracks(self) -> set[str]:
|
||||
"""Tracks whose metadata or artwork changed."""
|
||||
return {c.target for c in self.changes if c.scope == "track" and c.target}
|
||||
"""Tracks whose metadata or artwork changed.
|
||||
|
||||
Excludes tracks that were ADDED. They are not edits: nothing about them
|
||||
changed, they simply did not exist before. Counting them here would both
|
||||
mislabel the version-history message and drag them through the file-tag
|
||||
sync, which has nothing to write for a track whose fields were never
|
||||
touched.
|
||||
"""
|
||||
return {
|
||||
c.target
|
||||
for c in self.changes
|
||||
if c.scope == "track" and c.target and c.op != "add"
|
||||
}
|
||||
|
||||
def added_tracks(self) -> set[str]:
|
||||
"""Tracks put into the library that it did not previously hold."""
|
||||
return {
|
||||
c.target for c in self.changes if c.scope == "track" and c.op == "add" and c.target
|
||||
}
|
||||
|
||||
def retarget(self, old_id: str, new_id: str) -> None:
|
||||
"""Follow a track whose id changed (a path remap rewrites LOCATIONs, and
|
||||
@@ -91,6 +108,14 @@ class EditJournal:
|
||||
def tracks(n: int) -> str:
|
||||
return f"{n} track{'' if n == 1 else 's'}"
|
||||
|
||||
# --- tracks added to the library (import) ---
|
||||
# First, because it is the largest-grained thing that can have happened:
|
||||
# "added 52 tracks" is the headline, and the cue/grid counts that follow
|
||||
# are mostly describing those same tracks' imported prep.
|
||||
n_added = len(self.added_tracks())
|
||||
if n_added:
|
||||
parts.append(f"added {tracks(n_added)}")
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self.edited_tracks() | (extra_tracks or set()))
|
||||
if n_meta:
|
||||
|
||||
@@ -38,6 +38,25 @@ class TrackIndex:
|
||||
def get(self, track_id: str) -> Track | None:
|
||||
return self.by_key.get(track_id)
|
||||
|
||||
def add(self, track: Track) -> None:
|
||||
"""Put a track the projection has never seen into it.
|
||||
|
||||
`replace` deliberately ignores an unknown id — it exists to refresh, and
|
||||
silently inventing a track would hide a bug. Adding is a different
|
||||
intent and needs saying out loud, which is why importing a track needs
|
||||
this rather than being able to reuse `replace`.
|
||||
|
||||
An id that is already present is refreshed instead of duplicated:
|
||||
`by_key` could not represent two, so appending would desynchronise it
|
||||
from `tracks`.
|
||||
"""
|
||||
with self._lock:
|
||||
if track.id in self.by_key:
|
||||
self.replace(track)
|
||||
return
|
||||
self.tracks.append(track)
|
||||
self.by_key[track.id] = track
|
||||
|
||||
def replace(self, track: Track) -> None:
|
||||
"""Refresh one track's projection in place.
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ from .schemas import (
|
||||
ReplaceGrid,
|
||||
HistoryEntry,
|
||||
OpenCollection,
|
||||
OpenSource,
|
||||
PathMappingInfo,
|
||||
PlaylistNode,
|
||||
PrefixSuggestions,
|
||||
@@ -56,6 +57,8 @@ from .schemas import (
|
||||
RenamePlaylist,
|
||||
SaveResult,
|
||||
SetEntries,
|
||||
SourceCandidate,
|
||||
SourceStatus,
|
||||
SetCue,
|
||||
SetCueType,
|
||||
SetGridLock,
|
||||
@@ -666,3 +669,167 @@ def clear_history() -> dict:
|
||||
require_adapter()
|
||||
history.clear_history(STATE.path)
|
||||
return {"status": "cleared"}
|
||||
|
||||
|
||||
# ---- import sources ---------------------------------------------------
|
||||
#
|
||||
# A SOURCE is a library being read FROM, open alongside the loaded one. Its
|
||||
# routes are read-only by construction: there is no source equivalent of any
|
||||
# command, so no route here can be confused about which library it targets.
|
||||
|
||||
|
||||
def require_source() -> LibraryAdapter:
|
||||
"""The open source, or a 409."""
|
||||
if not STATE.source_loaded:
|
||||
raise HTTPException(409, "No source library open")
|
||||
assert STATE.source is not None
|
||||
return STATE.source
|
||||
|
||||
|
||||
def _source_status() -> SourceStatus:
|
||||
if not STATE.source_loaded:
|
||||
return SourceStatus(loaded=False)
|
||||
source = STATE.source
|
||||
caps = source.capabilities()
|
||||
return SourceStatus(
|
||||
loaded=True,
|
||||
path=str(STATE.source_path),
|
||||
label=caps.save.library_label,
|
||||
platform=caps.platform,
|
||||
tracks=len(source.tracks),
|
||||
playlists=source.playlist_count(),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/sources", response_model=list[SourceCandidate])
|
||||
def sources() -> list[SourceCandidate]:
|
||||
"""Every removable library plugged in right now.
|
||||
|
||||
Unlike `/api/library/options`, this genuinely changes between two calls a
|
||||
second apart — a stick is whatever is mounted — so the UI is expected to
|
||||
poll it rather than read it once at startup.
|
||||
|
||||
Only read-only platforms are offered. A source is a thing to import FROM,
|
||||
and a writable library appearing here would invite someone to open their own
|
||||
collection as a source of itself.
|
||||
"""
|
||||
out: list[SourceCandidate] = []
|
||||
for driver in registry.drivers():
|
||||
try:
|
||||
found = driver.detect()
|
||||
except OSError:
|
||||
continue
|
||||
for candidate in found:
|
||||
path = Path(candidate["path"])
|
||||
# Removable libraries are the ones discovery finds by scanning mount
|
||||
# points. Ask the driver rather than hard-coding which platform that
|
||||
# is, so a future Serato-on-a-stick needs no change here.
|
||||
if not getattr(driver, "removable", False):
|
||||
continue
|
||||
out.append(
|
||||
SourceCandidate(
|
||||
path=str(path),
|
||||
label=candidate.get("label") or path.name,
|
||||
platform=driver.platform,
|
||||
modified=candidate.get("modified"),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@app.get("/api/source", response_model=SourceStatus)
|
||||
def source_status() -> SourceStatus:
|
||||
return _source_status()
|
||||
|
||||
|
||||
@app.post("/api/source/open", response_model=SourceStatus)
|
||||
def open_source(body: OpenSource) -> SourceStatus:
|
||||
path = Path(body.path).expanduser()
|
||||
# NOT `is_file()`, unlike opening a collection: a OneLibrary source is a
|
||||
# DRIVE, so the thing the user picks is a directory.
|
||||
if not path.exists():
|
||||
raise HTTPException(400, f"Not found: {path}")
|
||||
try:
|
||||
STATE.open_source(path)
|
||||
except ValueError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
except AdapterError as ex:
|
||||
raise HTTPException(400, f"Not a library Konduktor can read: {ex}")
|
||||
except Exception as ex: # noqa: BLE001
|
||||
raise HTTPException(400, f"Could not open that source: {ex}")
|
||||
return _source_status()
|
||||
|
||||
|
||||
@app.delete("/api/source", response_model=SourceStatus)
|
||||
def close_source() -> SourceStatus:
|
||||
"""Close the source and release its file handle.
|
||||
|
||||
Worth calling rather than leaving to chance: the source is on a removable
|
||||
drive, and a held handle is what stops a stick ejecting.
|
||||
"""
|
||||
STATE.close_source()
|
||||
return _source_status()
|
||||
|
||||
|
||||
@app.get("/api/source/capabilities", response_model=Capabilities)
|
||||
def source_capabilities() -> Capabilities:
|
||||
return require_source().capabilities()
|
||||
|
||||
|
||||
@app.get("/api/source/tracks", response_model=TrackPage)
|
||||
def source_tracks(
|
||||
q: str | None = None,
|
||||
genre: str | None = None,
|
||||
key: str | None = None,
|
||||
bpm_min: float | None = None,
|
||||
bpm_max: float | None = None,
|
||||
rating_min: int | None = Query(None, ge=0, le=5),
|
||||
has_cues: bool | None = None,
|
||||
sort: str = "artist",
|
||||
order: str = Query("asc", pattern="^(asc|desc)$"),
|
||||
limit: int = Query(100, ge=1, le=20000),
|
||||
offset: int = Query(0, ge=0),
|
||||
) -> TrackPage:
|
||||
return require_source().query_tracks(
|
||||
q=q, genre=genre, key=key, bpm_min=bpm_min, bpm_max=bpm_max,
|
||||
rating_min=rating_min, has_cues=has_cues, sort=sort, order=order,
|
||||
limit=limit, offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/source/playlists", response_model=list[PlaylistNode])
|
||||
def source_playlists() -> list[PlaylistNode]:
|
||||
return require_source().playlist_tree()
|
||||
|
||||
|
||||
@app.get("/api/source/playlists/{playlist_id}/tracks", response_model=list[Track])
|
||||
def source_playlist_tracks(playlist_id: str) -> list[Track]:
|
||||
tracks = require_source().playlist_tracks(playlist_id)
|
||||
if tracks is None:
|
||||
raise HTTPException(404, f"Playlist not found: {playlist_id}")
|
||||
return tracks
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/cues", response_model=TrackCues)
|
||||
def source_track_cues(track_id: str) -> TrackCues:
|
||||
cues = require_source().track_cues(track_id)
|
||||
if cues is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
return cues
|
||||
|
||||
|
||||
@app.get("/api/source/tracks/audio")
|
||||
def source_track_audio(track_id: str) -> FileResponse:
|
||||
"""Stream a track's audio straight off the source drive.
|
||||
|
||||
So the deck can audition a track BEFORE importing it, which is most of the
|
||||
reason the stick is browsable in the ordinary table rather than in a picker
|
||||
dialog.
|
||||
"""
|
||||
path = require_source().audio_path(track_id)
|
||||
if path is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"Audio file not found: {path}")
|
||||
mime = _AUDIO_MIME.get(path.suffix.lower(), "application/octet-stream")
|
||||
return FileResponse(path, media_type=mime)
|
||||
@@ -180,3 +180,35 @@ from .core.model import ( # noqa: E402,F401
|
||||
TrackCues,
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
|
||||
# ---- import sources ---------------------------------------------------
|
||||
#
|
||||
# A SOURCE is a library being read FROM — a plugged-in OneLibrary stick whose
|
||||
# tracks are about to be imported. It is deliberately not a `CollectionStatus`:
|
||||
# a source is never saved, never edited and never the fallback when nothing is
|
||||
# loaded, so reusing the loaded-library shape would invite routes to treat the
|
||||
# two as interchangeable.
|
||||
|
||||
|
||||
class SourceCandidate(BaseModel):
|
||||
"""A removable library Konduktor can currently see."""
|
||||
|
||||
path: str
|
||||
label: str # what a person recognises, e.g. "OneLibrary — Hardy"
|
||||
platform: str
|
||||
tracks: int | None = None # None until it is opened; a probe would be slow
|
||||
modified: float | None = None
|
||||
|
||||
|
||||
class SourceStatus(BaseModel):
|
||||
loaded: bool
|
||||
path: str | None = None
|
||||
label: str | None = None
|
||||
platform: str | None = None
|
||||
tracks: int | None = None
|
||||
playlists: int | None = None
|
||||
|
||||
|
||||
class OpenSource(BaseModel):
|
||||
path: str
|
||||
@@ -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_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_phase3.py test_history.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""Importing a OneLibrary drive into a Traktor collection.
|
||||
|
||||
The first operation that puts tracks into a library that never had them, and
|
||||
therefore the first that writes an ENTRY Traktor did not write. Two things need
|
||||
guarding, and they pull in opposite directions:
|
||||
|
||||
* **The new entries must carry the prep.** Cues on the pads they were on, the
|
||||
beatgrid including its tempo changes, and nothing silently dropped.
|
||||
* **The old entries must not move.** The whole save-fidelity guarantee rests on
|
||||
every unedited object rendering the bytes it was parsed from, and appending
|
||||
to COLLECTION is the first thing that could disturb that. So this asserts on
|
||||
rendered bytes as well as on the projection.
|
||||
|
||||
Runs against a temp copy of the real Traktor collection (gotcha 2: it is real,
|
||||
irreplaceable data) and the checked-in OneLibrary fixture drive.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from difflib import unified_diff
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-import-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
|
||||
from konduktor.adapters.onelibrary.adapter import OneLibraryAdapter # noqa: E402
|
||||
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
|
||||
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
|
||||
from konduktor.core.adapter import InvalidCommand, NewTrack, Unsupported # noqa: E402
|
||||
from konduktor.core.model import CuePoint, GridMarker, Track, TrackCues # noqa: E402
|
||||
|
||||
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 _raises(fn, exc) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except exc:
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
if not REAL.is_file() or not (FIXTURE / "PIONEER" / "rekordbox" / "exportLibrary.db").is_file():
|
||||
print(f"SKIP: need {REAL} and the OneLibrary fixture")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def fresh_collection() -> tuple[Path, Path, bytes]:
|
||||
"""A throwaway copy of the real collection, plus a folder for copied audio."""
|
||||
work = Path(tempfile.mkdtemp(prefix="konduktor-import-"))
|
||||
nml = work / "collection.nml"
|
||||
shutil.copy(REAL, nml)
|
||||
music = work / "Imported"
|
||||
music.mkdir()
|
||||
return nml, music, nml.read_bytes()
|
||||
|
||||
|
||||
def stage(src: OneLibraryAdapter, music: Path) -> list[NewTrack]:
|
||||
"""Copy the drive's audio and describe each track as a NewTrack.
|
||||
|
||||
This is what the import feature will do around the adapter: the copy is the
|
||||
caller's job, so a half-finished file copy is never something a library
|
||||
write discovers.
|
||||
"""
|
||||
items = []
|
||||
for t in src.tracks:
|
||||
target = music / Path(t.filepath).name
|
||||
shutil.copy(t.filepath, target)
|
||||
items.append(NewTrack(track=t, audio_path=target, cues=src.track_cues(t.id)))
|
||||
return items
|
||||
|
||||
|
||||
print("== a drive's tracks land in the collection ==")
|
||||
nml, music, original = fresh_collection()
|
||||
source = OneLibraryAdapter(FIXTURE)
|
||||
dest = TraktorAdapter(nml)
|
||||
before = len(dest.tracks)
|
||||
items = stage(source, music)
|
||||
ids = dest.add_tracks(items)
|
||||
|
||||
check("every staged track was added", len(ids) == len(items) == 2, str(len(ids)))
|
||||
check("the collection grew by exactly that many", len(dest.tracks) == before + 2)
|
||||
check("the new ids are unique", len(set(ids)) == len(ids))
|
||||
# A track that is not in the projection is invisible to search, playlists and
|
||||
# the deck — added but unusable.
|
||||
check("each added track is in the projection", all(dest.track(i) is not None for i in ids))
|
||||
check("and is findable by its id", all(dest.by_key.get(i) is not None for i in ids))
|
||||
|
||||
added = dest.track(ids[0])
|
||||
origin = source.tracks[0]
|
||||
check("title survives", added.title == origin.title, f"{added.title!r}")
|
||||
check("artist survives", added.artist == origin.artist)
|
||||
check("bpm survives", added.bpm == origin.bpm)
|
||||
check("label survives", added.label == origin.label)
|
||||
check("comment survives", added.comment == origin.comment)
|
||||
check("the id is the Traktor primary key, not the drive's",
|
||||
added.id != origin.id and added.id.startswith("Macintosh HD"), added.id)
|
||||
check("filepath points at the COPY, not the drive",
|
||||
str(music) in (added.filepath or ""), str(added.filepath))
|
||||
|
||||
print("== prep survives the crossing ==")
|
||||
src_cues = source.track_cues(origin.id)
|
||||
got = dest.track_cues(ids[0])
|
||||
|
||||
check("the flexible grid crosses intact",
|
||||
[(round(m.start, 3), m.bpm) for m in got.grid_markers]
|
||||
== [(round(m.start, 3), m.bpm) for m in src_cues.grid_markers],
|
||||
str([(m.start, m.bpm) for m in got.grid_markers]))
|
||||
check("both tempo segments are there", len(got.grid_markers) == 2)
|
||||
|
||||
# Hot cues must keep their PAD. Muscle memory is most of what a hotcue layout
|
||||
# is, so a cue that moves is nearly as bad as one that vanishes.
|
||||
src_hot = {c.slot: c for c in src_cues.cues if c.role == "hotcue"}
|
||||
got_by_slot = {c.slot: c for c in got.cues}
|
||||
same_pad = [
|
||||
s for s, c in src_hot.items()
|
||||
if s in got_by_slot and abs(got_by_slot[s].start - c.start) < 0.001
|
||||
]
|
||||
check("every hot cue keeps the pad it was on",
|
||||
sorted(same_pad) == sorted(src_hot), f"kept {sorted(same_pad)} of {sorted(src_hot)}")
|
||||
check("a loop stays a loop, with its length",
|
||||
got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001)
|
||||
|
||||
# Traktor has no memory cues, so they degrade into spare pads rather than being
|
||||
# dropped — the settled lossiness rule.
|
||||
n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue")
|
||||
check("memory cues are preserved in spare slots, not dropped",
|
||||
len(got.cues) == len(src_hot) + n_memory, f"{len(got.cues)} cues")
|
||||
check("and they do not overwrite a hot cue",
|
||||
len({c.slot for c in got.cues}) == len(got.cues))
|
||||
check("every imported cue occupies a real pad",
|
||||
all(c.role == "hotcue" and c.slot is not None for c in got.cues))
|
||||
|
||||
# `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both
|
||||
# invents a cue the source never had and displaces the imported pad A cue — it
|
||||
# silently ate one during development, which is why this is asserted.
|
||||
check("no beatgrid companion cue is invented",
|
||||
all(c.grid_marker is None for c in got.cues),
|
||||
str([(c.slot, c.grid_marker) for c in got.cues]))
|
||||
|
||||
print("== the existing 8,485 entries do not move ==")
|
||||
outcome = dest.save()
|
||||
after = nml.read_bytes()
|
||||
diff = list(unified_diff(original.decode("utf-8", "replace").splitlines(),
|
||||
after.decode("utf-8", "replace").splitlines(), lineterm="", n=0))
|
||||
removed = [l for l in diff if l.startswith("-") and not l.startswith("---")]
|
||||
# Exactly one line is rewritten: the one carrying <COLLECTION ENTRIES="N">, whose
|
||||
# count changed. Everything else is pure addition.
|
||||
check("only the COLLECTION header line is rewritten",
|
||||
len(removed) == 1 and "<COLLECTION ENTRIES=" in removed[0],
|
||||
f"{len(removed)} removed: {removed[:1]}")
|
||||
check("nothing else is removed or reformatted",
|
||||
all("<COLLECTION ENTRIES=" in l for l in removed))
|
||||
|
||||
# ENTRIES is a real count Traktor reads, not decoration. Nothing else in the app
|
||||
# changes how many entries exist, so nothing had ever needed to maintain it.
|
||||
import re # noqa: E402
|
||||
|
||||
declared = int(re.search(rb'<COLLECTION ENTRIES="(\d+)"', after).group(1))
|
||||
check("the ENTRIES count is updated to match",
|
||||
declared == after.count(b"<ENTRY ") == before + 2,
|
||||
f"declared {declared}, actual {after.count(b'<ENTRY ')}")
|
||||
# The version-history message is what a user reads when deciding which version
|
||||
# to roll back to, so an import must not read as an edit. Asserted on the
|
||||
# SaveOutcome because save() clears the journal.
|
||||
check("the version-history message says the tracks were ADDED",
|
||||
"Added 2 tracks" in outcome.summary, outcome.summary)
|
||||
check("and does not also call them edited",
|
||||
"edited 2 tracks" not in outcome.summary.lower(), outcome.summary)
|
||||
|
||||
print("== reopening proves it is really there ==")
|
||||
reopened = TraktorAdapter(nml)
|
||||
check("the added tracks survive a round trip", len(reopened.tracks) == before + 2)
|
||||
round_tripped = reopened.track(ids[0])
|
||||
check("with their metadata", round_tripped is not None and round_tripped.title == origin.title)
|
||||
rt_cues = reopened.track_cues(ids[0])
|
||||
check("with their grid", len(rt_cues.grid_markers) == 2)
|
||||
check("and with their cues", len(rt_cues.cues) == len(got.cues))
|
||||
|
||||
print("== refusals ==")
|
||||
check("a second import of the same file is refused, not silently duplicated",
|
||||
_raises(lambda: dest.add_tracks(items), InvalidCommand))
|
||||
missing = NewTrack(track=items[0].track, audio_path=music / "nope.mp3", cues=None)
|
||||
check("a missing audio file is refused before anything is written",
|
||||
_raises(lambda: dest.add_tracks([missing]), InvalidCommand))
|
||||
check("read-only OneLibrary refuses to receive tracks",
|
||||
_raises(lambda: source.add_tracks(items), Unsupported))
|
||||
|
||||
print("== a track with no prep at all ==")
|
||||
nml2, music2, _ = fresh_collection()
|
||||
dest2 = TraktorAdapter(nml2)
|
||||
bare_audio = music2 / "bare.mp3"
|
||||
shutil.copy(items[0].audio_path, bare_audio)
|
||||
bare = NewTrack(
|
||||
track=Track(id="ignored", title="Bare", artist="Nobody"),
|
||||
audio_path=bare_audio,
|
||||
cues=None,
|
||||
)
|
||||
bare_ids = dest2.add_tracks([bare])
|
||||
check("a track with no cues and no grid still imports", len(bare_ids) == 1)
|
||||
bare_cues = dest2.track_cues(bare_ids[0])
|
||||
check("and has no grid", bare_cues.grid_markers == [])
|
||||
check("and no cues", bare_cues.cues == [])
|
||||
check("and no BPM was invented", dest2.track(bare_ids[0]).bpm is None)
|
||||
|
||||
print("== a full hotcue bank ==")
|
||||
# Traktor has 8 pads. Nine cues cannot all fit, so the rule has to be explicit
|
||||
# about WHICH survive rather than leaving it to iteration order.
|
||||
crowded_audio = music2 / "crowded.mp3"
|
||||
shutil.copy(items[0].audio_path, crowded_audio)
|
||||
many = TrackCues(
|
||||
grid_markers=[GridMarker(start=0.0, bpm=120.0)],
|
||||
cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i)
|
||||
for i in range(8)]
|
||||
+ [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None)],
|
||||
)
|
||||
crowded_id = dest2.add_tracks([NewTrack(
|
||||
track=Track(id="ignored", title="Crowded", bpm=120.0),
|
||||
audio_path=crowded_audio,
|
||||
cues=many,
|
||||
)])[0]
|
||||
crowded = dest2.track_cues(crowded_id)
|
||||
check("the bank is filled but not overflowed", len(crowded.cues) == 8, str(len(crowded.cues)))
|
||||
check("the hot cues are the ones that survived",
|
||||
sorted(c.slot for c in crowded.cues) == list(range(8)))
|
||||
check("the memory cue that would not fit is dropped, not misplaced",
|
||||
all(c.start < 99.0 for c in crowded.cues))
|
||||
|
||||
print("== the source slot ==")
|
||||
# A source is a library read FROM, open alongside the loaded one. The whole slot
|
||||
# rests on it being read-only, so that is asserted where the source is opened
|
||||
# rather than assumed by everything downstream.
|
||||
from konduktor.app_state import AppState # noqa: E402
|
||||
|
||||
state = AppState()
|
||||
nml3, _, _ = fresh_collection()
|
||||
state.open(nml3)
|
||||
check("a collection loads as the destination", state.loaded)
|
||||
check("and no source is open yet", not state.source_loaded)
|
||||
|
||||
state.open_source(FIXTURE)
|
||||
check("a read-only drive opens as a source", state.source_loaded)
|
||||
check("the destination is untouched by opening a source",
|
||||
state.loaded and state.path == nml3)
|
||||
check("the source projects its own tracks", len(state.source.tracks) == 2)
|
||||
check("the two libraries are genuinely different objects",
|
||||
state.source is not state.adapter)
|
||||
|
||||
# Opening your own collection as a source of itself is the mistake this guards.
|
||||
before_source = state.source
|
||||
check("a WRITABLE library is refused as a source",
|
||||
_raises(lambda: state.open_source(nml3), ValueError))
|
||||
check("and the refusal leaves the existing source in place",
|
||||
state.source is before_source)
|
||||
|
||||
state.close_source()
|
||||
check("closing releases the source", not state.source_loaded)
|
||||
check("but not the destination", state.loaded)
|
||||
check("closing twice is safe", state.close_source() is None)
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Reference in new issue
Block a user