"""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 , whose # count changed. Everything else is pure addition. check("only the COLLECTION header line is rewritten", len(removed) == 1 and "