"""Browsing drives and folders, and adding loose files, through the routes. Runs on a temp copy of the real collection, a temp app-data dir, and FLAC files generated here — so the tags are known rather than borrowed from a real file. Pins the things that would fail SILENTLY or dangerously: * a folder lists only the audio DIRECTLY in it, and never hidden or OS-housekeeping files (macOS writes a `._` twin beside every file on FAT); * the audio route streams only files a scan found — it is not a way to read any path on the disk; * a file the collection already points at is never added twice. On Traktor two entries for one path share a primary key, which is a corrupt collection — and that is exactly what "add in place" would do on a second click; * such a file still reaches the playlist or export it was headed for; * "copy" leaves the collection pointing at the COPY, and "reference" at the original, with nothing copied. """ from __future__ import annotations import os import shutil import sys import tempfile import time from pathlib import Path import numpy as np import soundfile as sf REAL = Path(__file__).resolve().parents[1] / "collection.nml" _DATA = tempfile.TemporaryDirectory() os.environ["KONDUKTOR_DATA_DIR"] = _DATA.name failed = False def check(label, cond, detail=""): global failed print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) if not cond: failed = True def flac(path: Path, **tags) -> Path: from mutagen.flac import FLAC path.parent.mkdir(parents=True, exist_ok=True) sf.write(path, np.zeros((44100, 2), dtype="float32"), 44100, format="FLAC") audio = FLAC(path) for k, v in tags.items(): audio[k] = str(v) audio.save() return path # ---- the folder on disk ------------------------------------------------------ music = Path(tempfile.mkdtemp()) / "Loose" one = flac(music / "one.flac", title="First Light", artist="Someone", genre="House", bpm=124) two = flac(music / "two.flac") # untagged: titled by its filename flac(music / "Deeper" / "three.flac", title="Not Listed") (music / "notes.txt").write_text("not audio") shutil.copy2(one, music / "._one.flac") # a macOS AppleDouble twin flac(music / ".hidden.flac") (music / ".secret-folder").mkdir() (music / ".Trashes").mkdir() work = Path(tempfile.mkdtemp()) / "collection.nml" shutil.copy2(REAL, work) os.environ["KONDUKTOR_NML"] = str(work) from fastapi.testclient import TestClient # noqa: E402 import konduktor.main as main # noqa: E402 from konduktor import exports # noqa: E402 from konduktor.app_state import STATE # noqa: E402 from konduktor.core import places # noqa: E402 def wait(c, job): while job["state"] == "running": time.sleep(0.05) job = c.get(f"/api/jobs/{job['id']}").json() return job with TestClient(main.app, raise_server_exceptions=False) as c: a = main.require_adapter() before = len(a.tracks) print("== drives ==") r = c.get("/api/fs/drives") check("answers 200", r.status_code == 200, r.text[:200]) drives = r.json() check("the boot disk is local, at the filesystem root", any(d["kind"] == "local" and d["path"] == "/" for d in drives), str(drives)) check("each drive is listed once", len({d["path"] for d in drives}) == len(drives)) print("== folder tree: visible folders only ==") r = c.get("/api/fs/folders", params={"path": str(music)}) names = [e["name"] for e in r.json()] check("lists the subfolder", names == ["Deeper"], str(names)) if sys.platform == "darwin": flagged = music / "Flagged" flagged.mkdir() os.chflags(flagged, 0x8000) # UF_HIDDEN, as macOS sets on /usr and /bin names = [e["name"] for e in c.get("/api/fs/folders", params={"path": str(music)}).json()] check("a folder hidden by FLAG is left out, as Finder does", "Flagged" not in names, str(names)) check("a missing folder is a 404", c.get("/api/fs/folders", params={"path": str(music / "nope")}).status_code == 404) print("== a folder's tracks: this folder only, audio only ==") r = c.get("/api/folder/tracks", params={"path": str(music)}) check("answers 200", r.status_code == 200, r.text[:300]) body = r.json() ids = [t["id"] for t in body["tracks"]] check("exactly the two visible audio files", ids == [str(one), str(two)], str(ids)) first = body["tracks"][0] check("tags are read", (first["title"], first["artist"], first["genre"], first["bpm"]) == ("First Light", "Someone", "House", 124.0), str(first)) check("an untagged file is titled by its name", body["tracks"][1]["title"] == "two") check("the length comes from the audio", first["length"] == 1, str(first["length"])) check("nothing is in the collection yet", body["in_collection"] == []) caps = c.get("/api/folder/capabilities", params={"path": str(music)}).json() check("the view is read-only, and says why", caps["writable"] is False and caps["readonly_cause"] == "not_in_library") print("== the audio route streams only what a scan found ==") r = c.get("/api/folder/tracks/audio", params={"track_id": str(one)}) check("a scanned file streams", r.status_code == 200 and len(r.content) > 0) check("an arbitrary file does not", c.get("/api/folder/tracks/audio", params={"track_id": "/etc/passwd"}).status_code == 404) check("nor does real audio in a folder nobody browsed", c.get("/api/folder/tracks/audio", params={"track_id": str(music / "Deeper" / "three.flac")}).status_code == 404) check("nor a hidden file beside a scanned one", c.get("/api/folder/tracks/audio", params={"track_id": str(music / ".hidden.flac")}).status_code == 404) check("cues are empty, not an error", c.get("/api/folder/tracks/cues", params={"track_id": str(one)}).json()["cues"] == []) print("== reference in place, into a playlist ==") playlist = a.create_playlist("Folder Test") req = {"track_ids": [str(one)], "mode": "reference", "playlist_id": playlist} p = c.post("/api/folder/add/preview", json=req).json() check("the preview counts one to add", p["importable"] == 1 and p["existing"] == [], str(p)) check("and nothing to copy", p["total_bytes"] == 0) job = wait(c, c.post("/api/folder/add", json=req).json()) check("the job finishes", job["state"] == "done", str(job)) check("one entry was added", len(a.tracks) == before + 1) added = job["result"]["track_ids"][0] check("it points at the ORIGINAL file", a.audio_path(added) == one, str(a.audio_path(added))) check("its tags came with it", a.track(added).title == "First Light") check("it is in the playlist", a.playlist_entries(playlist) == [added]) check("it was saved, not left pending", not a.dirty) body = c.get("/api/folder/tracks", params={"path": str(music)}).json() check("the folder now marks it as held", body["in_collection"] == [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 eset = exports.create(library, name="Folder Export", targets=["traktor"], destination=str(Path(tempfile.mkdtemp()) / "out")) req = {"track_ids": [str(one), str(two)], "mode": "reference", "playlist_id": playlist, "export_id": eset.id} p = c.post("/api/folder/add/preview", json=req).json() check("the preview reports it as already held", p["existing"] == ["First Light"], str(p)) job = wait(c, c.post("/api/folder/add", json=req).json()) check("the job finishes", job["state"] == "done", str(job)) check("only the NEW file was added", len(a.tracks) == before + 2, f"{len(a.tracks) - before}") check("the held one kept its id", job["result"]["track_ids"][0] == added) new = job["result"]["track_ids"][1] check("the playlist holds both, once each", a.playlist_entries(playlist) == [added, new], str(a.playlist_entries(playlist))) check("and so does the export", exports.get(library, eset.id).track_ids == [added, new]) print("== copy: the collection points at the copy ==") three_dir = music / "Deeper" c.get("/api/folder/tracks", params={"path": str(three_dir)}) dest = Path(tempfile.mkdtemp()) / "Imported" # Dropped between the playlist's rows: inserted there, not appended. req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest), "playlist_id": playlist, "playlist_index": 1} p = c.post("/api/folder/add/preview", json=req).json() check("the preview sizes the copy", p["total_bytes"] > 0, str(p)) job = wait(c, c.post("/api/folder/add", json=req).json()) check("the job finishes", job["state"] == "done", str(job)) copied_id = job["result"]["track_ids"][0] check("the audio was copied", (dest / "three.flac").is_file()) check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac", str(a.audio_path(copied_id))) check("the original is untouched", (three_dir / "three.flac").is_file()) check("it went into the playlist AT the index", a.playlist_entries(playlist) == [added, copied_id, new], str(a.playlist_entries(playlist))) check("copy without a destination is refused", c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400) check("an unscanned file cannot be added", c.post("/api/folder/add/preview", json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404) print("== a drop onto the window: folders all the way down, files as themselves ==") drop = Path(tempfile.mkdtemp()) / "Dropped" d_a = flac(drop / "Album" / "a.flac", title="Dropped A") d_b = flac(drop / "Album" / "CD2" / "b.flac") (drop / "Album" / "cover.jpg").write_bytes(b"not audio") flac(drop / "Album" / ".cache" / "h.flac") single = flac(drop / "Loose" / "single.flac", title="Single") sibling = flac(drop / "Loose" / "sibling.flac") (drop / "Loose" / "readme.txt").write_text("not audio") r = c.post("/api/folder/dropped", json={"paths": [ str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"), str(drop / "gone.flac"), str(single), str(d_a), ]}) check("answers 200", r.status_code == 200, r.text[:300]) body = r.json() ids = [t["id"] for t in body["tracks"]] check("the folder's audio, subfolders included, then the file — each once", ids == [str(d_a), str(d_b), str(single)], str(ids)) check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids) check("a dropped non-audio file and a missing one are counted as skipped", body["skipped"] == 2, str(body["skipped"])) check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2) check("tags are read", body["tracks"][0]["title"] == "Dropped A") check("not truncated", body["truncated"] is False) check("a dropped file streams", c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200) check("so does one found inside a dropped folder", c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200) check("but not its undropped sibling", c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404) listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]] check("browsing that folder afterwards still lists ALL of it", listed == [str(sibling), str(single)], str(listed)) r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]}) check("a non-audio file is never made streamable", r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={ "track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404) capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1) check("past the cap the rest are left out, and it says so", len(capped.tracks) == 1 and capped.truncated) body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json() check("a dropped file the collection holds IS its collection track", [t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)}, str(body)) req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")} p = c.post("/api/folder/add/preview", json=req).json() check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p)) req["destination"] = str(Path(tempfile.mkdtemp())) p = c.post("/api/folder/add/preview", json=req).json() check("…and not elsewhere", p.get("in_destination") == 0, str(p)) real_drives = main.places.drives main.places.drives = lambda: [ {"name": "Computer", "path": drop.anchor, "kind": "local"}, {"name": "Stick", "path": str(drop / "Album"), "kind": "external"}, ] try: req = {"track_ids": [str(d_a), str(single)], "mode": "reference"} p = c.post("/api/folder/add/preview", json=req).json() check("the external-drive warning counts files per drive, not by the first", p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"], str(p)) p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)], "mode": "reference"}).json() check("…whichever file comes first", p["removable_count"] == 1, str(p)) finally: main.places.drives = real_drives n = len(a.tracks) job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)], "mode": "reference"}).json()) check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2, str(job)) print("== Rekordbox: the same route adds to a master.db ==") from konduktor.adapters.rekordbox import discovery as rb_discovery found = rb_discovery.detect_libraries() if not found: print(" (skipped: no Rekordbox library on this machine)") else: rb_src = Path(found[0]["path"]).parent rb_dir = Path(tempfile.mkdtemp()) / "rekordbox" rb_dir.mkdir() for name in ("master.db", "masterPlaylists6.xml"): if (rb_src / name).exists(): shutil.copy2(rb_src / name, rb_dir / name) if (rb_src / "share").is_dir(): shutil.copytree(rb_src / "share", rb_dir / "share") r = c.post("/api/library/open", json={"path": str(rb_dir / "master.db")}) check("a Rekordbox copy opens", r.status_code == 200, r.text[:300]) caps = c.get("/api/capabilities").json() check("it advertises adding", caps["tracks"]["addable"] is True) rb = main.require_adapter() n_before = len(rb.tracks) req = {"track_ids": [str(two)], "mode": "reference"} job = wait(c, c.post("/api/folder/add", json=req).json()) check("the job finishes", job["state"] == "done", str(job)) new_ids = (job.get("result") or {}).get("track_ids") or [] check("one track was added", len(rb.tracks) == n_before + 1 and len(new_ids) == 1) if new_ids: check("it points at the original file", rb.audio_path(new_ids[0]) == two) row = rb._store.content(new_ids[0]) dat = rb_dir / "share" / row.AnalysisDataPath.lstrip("/") check("its analysis file was written", dat.is_file(), str(dat)) check("and saved, not left pending", not rb.dirty) rb.close() print("== a stick places its own audio; a library that cannot add refuses ==") # A COPY: opened as THE library, a OneLibrary drive is editable. fixture = Path(tempfile.mkdtemp()) / "onelibrary" shutil.copytree(Path(__file__).resolve().parent / "fixtures" / "onelibrary", fixture) r = c.post("/api/library/open", json={"path": str(fixture)}) if r.status_code == 200: # No mode and no destination: the library decides (decision 7). r = c.post("/api/folder/add/preview", json={"track_ids": [str(two)], "mode": "copy"}) body = r.json() if r.status_code == 200 else {} check("a stick's preview needs no destination, and counts the copy", r.status_code == 200 and body.get("places_audio") and body.get("copied") == 1 and body.get("in_place") == 0, f"{r.status_code} {r.text[:200]}") adapter = main.STATE.adapter real = adapter.capabilities caps = real() adapter.capabilities = lambda: caps.model_copy( update={"tracks": caps.tracks.model_copy(update={"addable": False})}) try: check("a library whose capabilities say it cannot add refuses the route (422)", c.post("/api/folder/add/preview", json={"track_ids": [str(two)], "mode": "reference"}).status_code == 422) finally: adapter.capabilities = real else: print(f" (skipped: fixture did not open — {r.status_code})") print("== hidden entries ==") check("AppleDouble twins are hidden", places.is_hidden(music / "._one.flac")) check("OS housekeeping is hidden", places.is_hidden(music / ".Trashes")) check("an ordinary file is not", not places.is_hidden(one)) print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) _DATA.cleanup() raise SystemExit(1 if failed else 0)