Implemented midi support`

This commit is contained in:
patben8 committed 2026-11-03 22:56:19 +01:00
1 parent f55b8f06e4
commit 8d0817b39e
41 files changed
+2827 -26

No files matched your search

+54 -4
View File
@@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests).
"""
from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass
@@ -16,7 +17,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from . import __version__, exporter, exports, local_push, loudness_store, prefs
from . import __version__, exporter, exports, local_push, loudness_store, paths, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect, key_detect, loudness, structure
@@ -38,6 +39,7 @@ from .core.capabilities import Capabilities
from .jobs import JOBS, Job, JobBusy
from .core.pathmap import PathMapping
from .schemas import (
MidiExportRequest,
Relocation,
RelocationApplied,
RelocationApply,
@@ -582,13 +584,14 @@ def fs_places(platform: str | None = None) -> list[FsPlace]:
@app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
def fs_list(path: str | None = None, platform: str | None = None, suffix: str | None = None) -> FsListing:
"""List directories and openable library files for the in-app file browser.
`platform` narrows the files to that platform's own: a Traktor browse that
also listed `master.db` would be offering a file the chosen adapter cannot
open. A platform whose library is a directory contributes no suffixes at
all, so its browse shows folders only.
all, so its browse shows folders only. `suffix` instead lists files whose
NAME ends with it (a MIDI mapping's `.konduktor-midi.json`).
"""
base = Path(path).expanduser() if path else Path.home()
if not base.exists() or not base.is_dir():
@@ -604,7 +607,7 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
try:
if entry.is_dir():
dirs.append(FsEntry(name=entry.name, path=str(entry)))
elif entry.suffix.lower() in suffixes:
elif entry.name.lower().endswith(suffix.lower()) if suffix else entry.suffix.lower() in suffixes:
files.append(FsEntry(name=entry.name, path=str(entry)))
except OSError:
continue
@@ -616,6 +619,53 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
)
# ---- MIDI controller mappings ---------------------------------------------------
#
# A mapping lives in userprefs (`midiMappings`, written by the UI like any pref);
# these two only move one to and from a FILE, so mappings can be shared. The
# content is the UI's to validate (lib/midi/mapping.sanitizeMapping): here it
# only has to be a small JSON object of the right version.
MIDI_MAPPING_SUFFIX = ".konduktor-midi.json"
_MIDI_MAPPING_MAX_BYTES = 1_000_000
@app.post("/api/midi/export")
def midi_export(req: MidiExportRequest) -> dict:
"""Write a mapping into `dir` as `<name>.konduktor-midi.json`. Never
overwrites: an existing file gets a `-2`, `-3`… beside it."""
folder = Path(req.dir).expanduser()
if not folder.is_dir():
raise HTTPException(400, f"Not a folder: {req.dir}")
if req.mapping.get("version") != 1:
raise HTTPException(400, "Not a MIDI mapping")
stem = "".join("_" if c in '/\\:*?"<>|' else c for c in req.name).strip(" .") or "MIDI mapping"
target = folder / f"{stem}{MIDI_MAPPING_SUFFIX}"
n = 2
while target.exists():
target = folder / f"{stem}-{n}{MIDI_MAPPING_SUFFIX}"
n += 1
paths.write_json(target, req.mapping)
return {"path": str(target)}
@app.get("/api/midi/import")
def midi_import(path: str) -> dict:
"""Read a mapping file (size-capped; must be a version-1 JSON object)."""
file = Path(path).expanduser()
if not file.is_file():
raise HTTPException(404, f"No such file: {path}")
if file.stat().st_size > _MIDI_MAPPING_MAX_BYTES:
raise HTTPException(400, "That file is too large to be a MIDI mapping")
try:
data = json.loads(file.read_text(encoding="utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
raise HTTPException(400, "That file is not a MIDI mapping") from None
if not isinstance(data, dict) or data.get("version") != 1:
raise HTTPException(400, "That file is not a MIDI mapping")
return {"mapping": data}
# ---- export sets -------------------------------------------------------------
#
# Curation, not library data: a set is Konduktor's own record of what to export,
+8
View File
@@ -818,3 +818,11 @@ class NormalizeRequest(BaseModel):
measure: Literal["lufs", "rms"] = "lufs"
target: float = -9.0
ceiling: float = -1.0
class MidiExportRequest(BaseModel):
"""A controller mapping written to a file (`/api/midi/export`). Its shape
is the UI's (`lib/midi/mapping.ts`); only the version is checked here."""
dir: str
name: str
mapping: dict
+1 -1
View File
@@ -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_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_midi_mappings.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+80
View File
@@ -0,0 +1,80 @@
"""MIDI controller mappings moved to and from FILES (`/api/midi/export`,
`/api/midi/import`) — the only backend part of controller support; the
mapping itself lives in userprefs and is validated by the UI.
Pins what would hurt silently: an export never overwrites a file (a shared
mapping saved twice must not replace the first), the name cannot steer the
file outside the chosen folder, and import refuses anything that is not a
small version-1 JSON object rather than handing the UI garbage. The file
browser's `suffix` filter lists the mapping files.
"""
import json
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from konduktor import prefs
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.main import fs_list, midi_export, midi_import # noqa: E402
from konduktor.schemas import MidiExportRequest # 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 refused(fn, status):
try:
fn()
except HTTPException as e:
return e.status_code == status
return False
folder = Path(_TMP.name) / "maps"
folder.mkdir()
mapping = {"version": 1, "shift": "note:1:63", "bindings": {"note:1:11": {"encoding": "button", "normal": "deck.A.play"}}}
print("export")
first = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping=mapping))["path"])
check("written as <name>.konduktor-midi.json", first.name == "DDJ-400.konduktor-midi.json")
check("holds the mapping", json.loads(first.read_text()) == mapping)
second = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping={"version": 1}))["path"])
check("never overwrites: a second export is -2", second.name == "DDJ-400-2.konduktor-midi.json")
check("the first file is untouched", json.loads(first.read_text()) == mapping)
sneaky = Path(midi_export(MidiExportRequest(dir=str(folder), name="../../escape", mapping=mapping))["path"])
check("a name cannot leave the folder", sneaky.parent == folder, str(sneaky))
check("a missing folder is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder / "nope"), name="x", mapping=mapping)), 400))
check("a non-mapping is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder), name="x", mapping={"version": 9})), 400))
print("import")
check("reads back what was exported", midi_import(str(first))["mapping"] == mapping)
bad = folder / "bad.konduktor-midi.json"
bad.write_text("{not json")
check("invalid JSON refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps([1, 2]))
check("not an object refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps({"version": 2}))
check("wrong version refused", refused(lambda: midi_import(str(bad)), 400))
big = folder / "big.konduktor-midi.json"
big.write_text(json.dumps({"version": 1, "pad": "x" * 1_100_000}))
check("an oversized file refused", refused(lambda: midi_import(str(big)), 400))
check("a missing file is 404", refused(lambda: midi_import(str(folder / "absent.json")), 404))
print("file browser")
(folder / "notes.json").write_text("{}")
listed = {f.name for f in fs_list(path=str(folder), suffix=".konduktor-midi.json").files}
check("the suffix lists mapping files only", "notes.json" not in listed and first.name in listed, str(listed))
sys.exit(1 if failed else 0)