mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented Discard changes button
This commit is contained in:
1 parent
681add852a
commit
28b705173e
17 files changed
+564
-43
No files matched your search
@@ -80,7 +80,9 @@ class RekordboxAdapter:
|
||||
self._store.close()
|
||||
|
||||
def reload(self) -> None:
|
||||
self._store._load()
|
||||
"""Re-read the library from disk, DISCARDING unsaved edits (see
|
||||
`RekordboxStore.discard` for why a plain re-open is not enough)."""
|
||||
self._store.discard()
|
||||
self._cloud_synced = self._store.cloud_synced
|
||||
self._rebuild()
|
||||
|
||||
|
||||
@@ -101,6 +101,24 @@ class RekordboxStore:
|
||||
self._content_cache: list | None = None
|
||||
self._by_id: dict[str, object] | None = None
|
||||
|
||||
def discard(self) -> None:
|
||||
"""Drop every unsaved edit and re-open the library as it is on disk.
|
||||
|
||||
Three things hold edits here, and all three must go: the SQLAlchemy
|
||||
session (rolled back, then closed with its engine — `_load()` alone
|
||||
would open a SECOND connection and leak the first), the buffered grid
|
||||
writes (which the next save would otherwise still write to ANLZ files),
|
||||
and the journal (else the library keeps reporting unsaved changes).
|
||||
"""
|
||||
try:
|
||||
self._db.session.rollback()
|
||||
except Exception: # noqa: BLE001 — discarding must not fail halfway
|
||||
pass
|
||||
self.close()
|
||||
self._journal = EditJournal()
|
||||
self._pending_grids.clear()
|
||||
self._load()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release the session AND the pooled connection.
|
||||
|
||||
|
||||
@@ -1241,11 +1241,14 @@ class TraktorStore:
|
||||
return key_remap
|
||||
|
||||
# ---- stem conversion ---------------------------------------------------
|
||||
#: Whether a converted entry keeps Traktor's analysis fingerprint. It is a
|
||||
#: fingerprint of the OLD file; cleared, Traktor re-analyses the new one on
|
||||
#: load (the import precedent: prep survives). Settled by the milestone-2
|
||||
#: check in Traktor 4.5.
|
||||
_KEEP_AUDIO_ID_ON_STEM = False
|
||||
#: Whether a converted entry keeps Traktor's analysis fingerprint (AUDIO_ID).
|
||||
#: KEPT, as measured in Traktor 4.5 (kit 5, 2026-09-30): with it kept, Traktor
|
||||
#: loads the stem entry as it is — cues, grid and fingerprint untouched. With
|
||||
#: it cleared, Traktor re-analyses on load: it keeps grid POSITIONS (even a
|
||||
#: hand-nudged, unlocked one) but re-measures the grid's BPM (125.000023 ->
|
||||
#: 125.00042), i.e. it rewrites prep the user set. The stem file's mix is the
|
||||
#: same audio as the original, so the old fingerprint still describes it.
|
||||
_KEEP_AUDIO_ID_ON_STEM = True
|
||||
|
||||
def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None) -> StemSwapResult:
|
||||
"""Point entries at converted stem files ("repoint"), or add entries for
|
||||
|
||||
@@ -25,6 +25,7 @@ human summary, and this module versions them.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
|
||||
@@ -51,6 +52,11 @@ class AppState:
|
||||
# This open's missing-files check (see `relocation.py`). A new one per
|
||||
# open, which is what makes the dialog ask again on a reopen.
|
||||
self.relocation: RelocationCheck | None = None
|
||||
# Serialises the operations that REPLACE or COMMIT the whole library —
|
||||
# open, save, discard (and a stem batch's swap step). A save landing in
|
||||
# the middle of another would commit a half-applied state; reentrant so
|
||||
# one of them may call another.
|
||||
self.mutation = threading.RLock()
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
@@ -95,6 +101,10 @@ class AppState:
|
||||
pass
|
||||
|
||||
def open(self, path: Path) -> None:
|
||||
with self.mutation:
|
||||
self._open(path)
|
||||
|
||||
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
|
||||
# an unrecognised or unparseable file; only commit once it has parsed.
|
||||
@@ -146,6 +156,10 @@ class AppState:
|
||||
cannot restore from.
|
||||
"""
|
||||
assert self.adapter is not None and self.path is not None
|
||||
with self.mutation:
|
||||
return self._save()
|
||||
|
||||
def _save(self):
|
||||
outcome = self.adapter.save()
|
||||
# Not every platform is versioned. A library that is more than one file
|
||||
# has no single blob that IS the library, and it says so through its
|
||||
@@ -158,6 +172,17 @@ class AppState:
|
||||
)
|
||||
return outcome, commit
|
||||
|
||||
def discard(self) -> None:
|
||||
"""Drop every unsaved edit: the library re-reads itself from disk.
|
||||
|
||||
Through the adapter's own `reload`, NOT `open` — reopening would start a
|
||||
new missing-files check and forget this session's relocation answers,
|
||||
which are not edits and survive a reload (the store keeps them).
|
||||
"""
|
||||
assert self.adapter is not None
|
||||
with self.mutation:
|
||||
self.adapter.reload()
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
|
||||
|
||||
+33
-10
@@ -163,16 +163,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
|
||||
# This checks only that the path is there at all; `can_open()` decides.
|
||||
if not path.exists():
|
||||
raise HTTPException(400, f"Not found: {path}")
|
||||
# A running analysis writes into the library being replaced; stop it, and
|
||||
# WAIT for it to stop — a job still finishing its current track would
|
||||
# otherwise keep writing (or, for file work, keep moving files) after the
|
||||
# switch. Batches check for a cancel between tracks, so this is short.
|
||||
stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)]
|
||||
for job in stopping:
|
||||
JOBS.cancel(job.id)
|
||||
for job in stopping:
|
||||
if not JOBS.wait(job.id, timeout=60):
|
||||
log.warning("batch %s (%s) still running after cancel; opening anyway", job.id, job.kind)
|
||||
_stop_batches()
|
||||
try:
|
||||
STATE.open(path)
|
||||
except AdapterError as ex:
|
||||
@@ -740,6 +731,22 @@ def state() -> EditState:
|
||||
return EditState(dirty=require_adapter().dirty, library=_library_info())
|
||||
|
||||
|
||||
@app.post("/api/discard", response_model=EditState)
|
||||
def discard_changes() -> EditState:
|
||||
"""Drop every unsaved edit — the library re-reads itself from disk.
|
||||
|
||||
A running batch is stopped first (and waited for): it writes into the
|
||||
library being discarded, so it would otherwise keep adding edits to the
|
||||
freshly reloaded one.
|
||||
"""
|
||||
adapter = require_adapter()
|
||||
if not adapter.capabilities().writable:
|
||||
raise HTTPException(409, "This library cannot be edited, so there is nothing to discard")
|
||||
_stop_batches()
|
||||
STATE.discard()
|
||||
return state()
|
||||
|
||||
|
||||
@app.post("/api/reload")
|
||||
def reload_collection() -> dict:
|
||||
if not STATE.loaded:
|
||||
@@ -1040,6 +1047,22 @@ CUE_JOB = "auto-hotcues"
|
||||
BATCH_JOBS = (GRID_JOB, CUE_JOB)
|
||||
|
||||
|
||||
def _stop_batches() -> None:
|
||||
"""Cancel every running batch analysis and WAIT for it to stop.
|
||||
|
||||
Used wherever the library is about to be replaced or reloaded: a job still
|
||||
finishing its current track would otherwise keep writing into it (or, for
|
||||
file work, keep moving files) afterwards. Batches check for a cancel
|
||||
between tracks, so this is short.
|
||||
"""
|
||||
stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)]
|
||||
for job in stopping:
|
||||
JOBS.cancel(job.id)
|
||||
for job in stopping:
|
||||
if not JOBS.wait(job.id, timeout=60):
|
||||
log.warning("batch %s (%s) still running after cancel; continuing", job.id, job.kind)
|
||||
|
||||
|
||||
def _require_no_batch() -> None:
|
||||
"""An early, friendly refusal. Not race-free on its own — the batch routes
|
||||
START through `_submit_batch`, which re-checks under the registry's lock."""
|
||||
|
||||
@@ -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_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py; do
|
||||
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Discarding unsaved edits (`POST /api/discard`, `AppState.discard`).
|
||||
|
||||
Konduktor had no discard path at all: switching library dropped edits, quitting
|
||||
killed the backend. Discard is also what a stem conversion's parked originals
|
||||
will hang on, so it has to be exact. Pins:
|
||||
|
||||
* Traktor: an edit is dropped, the library is clean, the file on disk and the
|
||||
version history are untouched — and this session's relocation answers and
|
||||
saved path mapping survive (they are not edits; reopening would lose them).
|
||||
* A running batch is stopped BEFORE the reload, so it cannot keep writing
|
||||
into the reloaded library.
|
||||
* Rekordbox: the SQLAlchemy session, the buffered ANLZ grid writes and the
|
||||
journal all go — a plain re-open left the library still "dirty" and the
|
||||
next save still writing the discarded grids.
|
||||
* A read-only library has nothing to discard (409).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-discard-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary"
|
||||
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
|
||||
|
||||
|
||||
print("== Traktor, through the routes ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
os.environ["KONDUKTOR_NML"] = str(work)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import konduktor.main as main
|
||||
from konduktor import history
|
||||
from konduktor.core.pathmap import PathMapping
|
||||
|
||||
with TestClient(main.app) as c:
|
||||
a = main.require_adapter()
|
||||
track = next(t for t in a.tracks if t.genre)
|
||||
genre = track.genre # a string: the index updates Track objects in place
|
||||
commits_before = len(history.list_history(work))
|
||||
r = c.patch("/api/tracks", json={"track_id": track.id, "fields": {"genre": "Discard me"}})
|
||||
check("(setup) an edit makes the library dirty", r.status_code == 200 and c.get("/api/state").json()["dirty"])
|
||||
session = [PathMapping.make("/Volumes/Gone", "/Volumes/Here")]
|
||||
a.set_session_mappings(session)
|
||||
a.set_path_mapping(PathMapping.make("/Old", "/New"))
|
||||
|
||||
r = c.post("/api/discard")
|
||||
check("discard answers with a clean state", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200])
|
||||
a = main.require_adapter()
|
||||
check("the edit is gone from the projection", a.track(track.id).genre == genre, a.track(track.id).genre)
|
||||
check("the file on disk was never touched", work.read_bytes() == original)
|
||||
check("no version was recorded", len(history.list_history(work)) == commits_before)
|
||||
check("this session's relocation answers survive", a.store._session_mappings == session)
|
||||
check("…and so does the saved path mapping", not a.store._path_mapping.empty)
|
||||
check("the same adapter object: a reload, not a reopen", main.STATE.adapter is a)
|
||||
|
||||
# A running batch is stopped (and waited for) before the reload.
|
||||
main.grid_detect.detect_grid = lambda p, *x, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1]
|
||||
ids = [t.id for t in a.tracks[:60]]
|
||||
jid = c.post("/api/tracks/grid/auto-batch", json={"track_ids": ids, "replace_existing": True}).json()["id"]
|
||||
time.sleep(0.2)
|
||||
r = c.post("/api/discard")
|
||||
job = main.JOBS.get(jid)
|
||||
check("a running batch has STOPPED by the time discard returns", job.finished, job.state)
|
||||
time.sleep(0.2)
|
||||
check("…and nothing it did survives the reload", c.get("/api/state").json()["dirty"] is False)
|
||||
os.environ.pop("KONDUKTOR_NML", None)
|
||||
|
||||
print("== Rekordbox: session, buffered grids and journal all go ==")
|
||||
from konduktor.adapters.rekordbox import discovery # noqa: E402
|
||||
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
|
||||
|
||||
found = discovery.detect_libraries()
|
||||
if not found:
|
||||
print(" (skipped: no Rekordbox library on this machine)")
|
||||
else:
|
||||
src = Path(found[0]["path"])
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "master.db"
|
||||
shutil.copy2(src, work)
|
||||
if (src.parent / "share").is_dir():
|
||||
shutil.copytree(src.parent / "share", Path(d) / "share")
|
||||
before = work.read_bytes()
|
||||
ad = RekordboxAdapter(work)
|
||||
track = next(t for t in ad.tracks if t.title)
|
||||
title = track.title
|
||||
ad.set_track_metadata(track.id, {"title": "Discard me"})
|
||||
cues = ad.track_cues(track.id)
|
||||
if cues is not None and cues.grid_markers:
|
||||
ad.replace_grid(track.id, [(m.start + 0.01, m.bpm) for m in cues.grid_markers])
|
||||
check("(setup) edits make it dirty", ad.dirty)
|
||||
ad.reload()
|
||||
check("after discard it is clean", ad.dirty is False)
|
||||
check("the metadata edit is gone", ad.track(track.id).title == title, ad.track(track.id).title)
|
||||
check("no buffered grid write survives for the next save", not ad._store._pending_grids)
|
||||
ad.save()
|
||||
ad.close()
|
||||
check("a save after discard writes nothing the user threw away",
|
||||
RekordboxAdapter(work).track(track.id).title == title)
|
||||
del before
|
||||
|
||||
print("== read-only ==")
|
||||
os.environ["KONDUKTOR_NML"] = ""
|
||||
with TestClient(main.app) as c:
|
||||
r = c.post("/api/library/open", json={"path": str(FIXTURE)})
|
||||
if r.status_code == 200:
|
||||
check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409)
|
||||
else:
|
||||
print(f" (skipped: fixture did not open: {r.status_code})")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -125,6 +125,7 @@ with tempfile.TemporaryDirectory() as d:
|
||||
ad = TraktorAdapter(work)
|
||||
before_cues = ad.track_cues(tid)
|
||||
before = ad.snapshot()
|
||||
audio_id = ad.store.model_entry(tid).audio_id
|
||||
written = build_stem(mp3)
|
||||
parked = park(mp3)
|
||||
stem = written.path
|
||||
@@ -140,6 +141,8 @@ with tempfile.TemporaryDirectory() as d:
|
||||
== (written.bit_rate, round(written.duration), round(written.size / 1024)),
|
||||
f"{entry.info.bitrate} {entry.info.playtime} {entry.info.filesize}")
|
||||
check("the projection calls it a stem track", ad.track(new).media_kind == "stem")
|
||||
check("Traktor's fingerprint is KEPT (cleared, Traktor re-measures the grid's BPM on load)",
|
||||
entry.audio_id == audio_id and bool(audio_id))
|
||||
after_cues = ad.track_cues(new)
|
||||
check("every cue reads back at the same DECODED second",
|
||||
[(c.slot, round(c.start, 9)) for c in after_cues.cues] == [(c.slot, round(c.start, 9)) for c in before_cues.cues],
|
||||
|
||||
Reference in new issue
Block a user